From d72fa882aab2963bf4bcefa2c96e4c421d20f19d Mon Sep 17 00:00:00 2001 From: Dotta Date: Sun, 15 Nov 2026 15:46:29 -0600 Subject: [PATCH] Use the provider working directory for workspace stamp recovery Keep stamp commands portable to confined runtimes without widening their workspace boundary. Join the existing committed native status event in the hosted fixture before asserting domain completion, within the original case budget. Co-Authored-By: Codex --- .../dot-hosted-useful.postgres.test.ts | 37 +++++++++++++--- .../helpers/owned-linux/child-client.ts | 1 + .../helpers/owned-linux/normal-app-child.ts | 18 +++++++- .../__tests__/native-workspace-sync.test.ts | 42 +++++++++++++++---- .../native-runtime/native-workspace-sync.ts | 2 - 5 files changed, 84 insertions(+), 16 deletions(-) diff --git a/server/src/__tests__/dot-hosted-useful.postgres.test.ts b/server/src/__tests__/dot-hosted-useful.postgres.test.ts index 989578a7916..509c6a74995 100644 --- a/server/src/__tests__/dot-hosted-useful.postgres.test.ts +++ b/server/src/__tests__/dot-hosted-useful.postgres.test.ts @@ -26,9 +26,9 @@ import { pathToFileURL } from "node:url"; import request from "supertest"; import { startMinio, objectStoreServerEnvironment, type ObjectStore } from "../../../tests/restart-chaos/object-store.js"; import { startStorageFaultProxy } from "../../../tests/restart-chaos/storage-proxy.js"; -import { eq } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { applyPendingMigrations, createDb, closeRegisteredClients, authUsers, companies, mcpOauthGrants, agents, dotAgentBindings, dotRunnerAssignments, dotRunnerOperations, mcpOauthRequests, mcpOauthTokens, mcpOauthClientChanges, mcpOauthClientMirrorState, mcpOauthDeviceRequests, heartbeatRuns, agentWakeupRequests, completionContracts, nativeRunResults, nativeRunFinalizations, issues, mcpEventDeliveries, mcpEventSubscriptions } from "@paperclipai/db"; +import { applyPendingMigrations, createDb, closeRegisteredClients, authUsers, companies, mcpOauthGrants, agents, dotAgentBindings, dotRunnerAssignments, dotRunnerOperations, mcpOauthRequests, mcpOauthTokens, mcpOauthClientChanges, mcpOauthClientMirrorState, mcpOauthDeviceRequests, heartbeatRuns, agentWakeupRequests, completionContracts, workAssessments, statusDecisions, nativeRunResults, nativeRunFinalizations, issues, mcpEventDeliveries, mcpEventSubscriptions } from "@paperclipai/db"; import { resolveExternalTestDatabaseUrl } from "../lib/dedicated-test-database-url.js"; import { accessService } from "../services/access.js"; import { instanceSettingsService } from "../services/instance-settings.js"; @@ -116,6 +116,9 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device let physicalApp:Awaited>|undefined; let childControl:ReturnType|undefined; let childSnapshot:ChildSnapshot|undefined; + const committedStatusSchema=z.object({kind:z.literal("native-status-committed"),companyId:z.uuid(),issueId:z.uuid(),runId:z.uuid(),decisionId:z.uuid(),assessmentId:z.uuid(),toStatus:z.string()}); + type CommittedStatus=z.infer; + let statusDecisionWaiter:{companyId:string;issueId:string;runId:string;resolve:(value:CommittedStatus)=>void}|undefined; const retiredChildren:ChildSnapshot[]=[]; const physicalOwners:Array>>=[]; const knownChildProcesses:Array<{child:import("node:child_process").ChildProcess;owner:ReturnType}>=[]; @@ -466,7 +469,10 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device registerActualChild:(child,owner)=>{ knownChildProcesses.push({child,owner}); childControl=attachDotChild(child,event=>{ - if(event.kind==="dcr-committed"){ + if(event.kind==="native-status-committed"){ + const value=committedStatusSchema.parse(event),waiting=statusDecisionWaiter; + if(waiting&&value.companyId===waiting.companyId&&value.issueId===waiting.issueId&&value.runId===waiting.runId)waiting.resolve(value); + }else if(event.kind==="dcr-committed"){ actualDeviceRegistrationCalls++;actualDeviceClientId=z.string().min(1).parse(event.clientId); const revision=z.number().int().positive().parse(event.revision); if(holdDeviceMirrorAck){deviceAckTargetRevision=revision;resolveDeviceAckTarget?.(revision);} @@ -917,9 +923,28 @@ describe.skipIf(!url||!cloudDatabaseUrl)("current normal hosted Dot OAuth/device const conflict=await tool(raw,"paperclip_dot_tool",{assignmentId:assignment.id,requestId:writeId,...writeArgs,arguments:{...writeArgs.arguments,body:"changed"}});expect(conflict.body.result.isError).toBe(true);expect((await documentService(db).getIssueDocumentByKey(task.id,"report"))?.body).toBe("17 + 25 = 42."); const [run]=await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,runId));const [contract]=await db.select().from(completionContracts).where(eq(completionContracts.id,run.completionContractId!));const specification=z.object({revision:z.string(),criteria:z.array(z.object({id:z.string()}))}).passthrough().parse(contract.contractJson); const result={reportedWorkDisposition:"completed",summary:"Saved the arithmetic report.",completionClaim:{contractRevision:specification.revision,objectiveSatisfied:true,criteria:specification.criteria.map(criterion=>({criterionId:criterion.id,status:"passed",evidenceRefs:[]})),remainingWork:[]},evidence:[],verification:[{commandOrCheck:"Read the persisted report: 17 + 25 = 42.",status:"pass"}]}; - expect((await operation("paperclip_dot_tool",{name:"paperclip_finish",arguments:result})).receipt).toMatchObject({status:"completed",isError:false}); - await operation("paperclip_dot_finish",{result});await childControl!.request({command:"drain-run",runId},childDeadline()); - const [settledAssignment]=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id));expect(settledAssignment.status).toBe("settled");const successorResults=await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId,runId));expect(successorResults).toHaveLength(1);const [settledTask]=await db.select().from(issues).where(eq(issues.id,task.id));expect(settledTask.status).toBe("done"); + const committedStatus=await(async()=>{ + const committed=new Promise(resolve=>{statusDecisionWaiter={companyId,issueId:task.id,runId,resolve};}); + let timer:ReturnType|undefined; + try{ + await childControl!.request({command:"observe-status-decision",issueId:task.id,runId},childDeadline()); + expect((await operation("paperclip_dot_tool",{name:"paperclip_finish",arguments:result})).receipt).toMatchObject({status:"completed",isError:false}); + await operation("paperclip_dot_finish",{result}); + await childControl!.request({command:"drain-run",runId},childDeadline()); // Execution drain is distinct from the committed domain decision. + const remaining=caseStarted+90_000-performance.now();expect(remaining).toBeGreaterThan(0); + return await Promise.race([committed,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("No matching committed native status decision within the original case deadline")),remaining);})]); + }finally{clearTimeout(timer);statusDecisionWaiter=undefined;} + })(); + const [settledAssignment]=await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id,assignment.id));expect(settledAssignment.status).toBe("settled"); + // Enrich the existing one result read; no extra query or polling owner. + const committedRows=await db.select({result:nativeRunResults,assessment:workAssessments,decision:statusDecisions}).from(nativeRunResults) + .leftJoin(workAssessments,and(eq(workAssessments.id,committedStatus.assessmentId),eq(workAssessments.resultId,nativeRunResults.id))) + .leftJoin(statusDecisions,and(eq(statusDecisions.id,committedStatus.decisionId),eq(statusDecisions.assessmentId,workAssessments.id))) + .where(eq(nativeRunResults.runId,runId)); + const successorResults=committedRows.map(row=>row.result);expect(successorResults).toHaveLength(1); + expect(committedRows[0].assessment).toMatchObject({id:committedStatus.assessmentId,companyId,issueId:task.id,runId,resultId:successorResults[0].id}); + expect(committedRows[0].decision).toMatchObject({id:committedStatus.decisionId,companyId,issueId:task.id,runId,assessmentId:committedStatus.assessmentId,applicationState:"applied",toStatus:committedStatus.toStatus}); + const [settledTask]=await db.select().from(issues).where(eq(issues.id,task.id));expect(settledTask.status).toBe("done"); const passiveConnectionSnapshot=async(deadline=childDeadline())=>{ const child=await syncChildObservation(deadline),all=[...retiredChildren,child]; return{clients:databaseObservation.clients+all.reduce((n,v)=>n+v.database.clients,0), diff --git a/server/src/__tests__/helpers/owned-linux/child-client.ts b/server/src/__tests__/helpers/owned-linux/child-client.ts index ff8cf17e12c..9970e712dbf 100644 --- a/server/src/__tests__/helpers/owned-linux/child-client.ts +++ b/server/src/__tests__/helpers/owned-linux/child-client.ts @@ -6,6 +6,7 @@ export type ChildSnapshot={owner:ReturnType>["snapshot"]>}; export type ChildControl={command:"snapshot"|"inspect"}|{command:"health";value:"ready"|"unavailable"|"wake-once-then-unavailable"} |{command:"device-stage";value:"first-select"|"retry-select"|"none"} + |{command:"observe-status-decision";issueId:string;runId:string} |{command:"drain-run";runId:string}|{command:"stop-checkpointed";runId:string;environmentId:string}; export function attachDotChild(child:ChildProcess,onEvent:(event:Record)=>void){ let serial=0,failures=0;const pending=new Mapvoid;reject:(error:Error)=>void}>(); diff --git a/server/src/__tests__/helpers/owned-linux/normal-app-child.ts b/server/src/__tests__/helpers/owned-linux/normal-app-child.ts index e524b58b53e..6cefdbe8570 100644 --- a/server/src/__tests__/helpers/owned-linux/normal-app-child.ts +++ b/server/src/__tests__/helpers/owned-linux/normal-app-child.ts @@ -23,6 +23,7 @@ let ports:Awaited>; try{ports=await installDotChildPorts({...input,deviceStage:()=>stage,emit:send,probeWitnessRoot:input.linuxInput.providerRoot});} catch(primary){try{restoreCA();}catch(cleanup){throw new AggregateError([primary,cleanup],"owned_dot_child_port_setup_failed");}throw primary;} let owner:Awaited>|undefined; +let stopStatusDecisionEvents=()=>{}; let shutting:Promise|undefined; const shutdown=()=>shutting??=(async()=>{ try{const nativeRecovery=owner?.snapshot().nativeRecovery; @@ -30,7 +31,7 @@ const shutdown=()=>shutting??=(async()=>{ await owner?.stop();const snapshot=ports.snapshot();assert.equal(snapshot.connections,0);assert.equal(snapshot.dedicated,0);assert.equal(snapshot.listeners,0); assert.equal(snapshot.observerPending,0);assert.equal(snapshot.observerFailures,0);assert.equal(snapshot.overflow,0); send({kind:"stopped",pid:process.pid,owner:owner?.snapshot(),snapshot}); - }finally{try{ports.restore();}finally{restoreCA();}} + }finally{try{stopStatusDecisionEvents();}finally{try{ports.restore();}finally{restoreCA();}}} })(); try{ const {startNormalDotAppGeneration}=await import("./normal-app-generation.js"); @@ -42,6 +43,7 @@ try{ z.object({command:z.literal("snapshot"),id:z.number().int()}).strict(), z.object({command:z.literal("health"),id:z.number().int(),value:z.enum(["ready","unavailable","wake-once-then-unavailable"])}).strict(), z.object({command:z.literal("device-stage"),id:z.number().int(),value:z.enum(["first-select","retry-select","none"])}).strict(), + z.object({command:z.literal("observe-status-decision"),id:z.number().int(),issueId:z.uuid(),runId:z.uuid()}).strict(), z.object({command:z.literal("drain-run"),id:z.number().int(),runId:z.uuid()}).strict(), z.object({command:z.literal("stop-checkpointed"),id:z.number().int(),runId:z.uuid(),environmentId:z.uuid()}).strict(), z.object({command:z.literal("inspect"),id:z.number().int()}).strict(), @@ -51,6 +53,20 @@ try{ if(message.command==="health")health=message.value; if(message.command==="device-stage")stage=message.value==="none"?undefined:message.value; let result:unknown; + if(message.command==="observe-status-decision"){ + stopStatusDecisionEvents(); + const {subscribeCompanyLiveEvents}=await import("../../../services/live-events.js"); + const statusDecisionEvent=z.object({action:z.enum(["issue.updated","issue.status_decision_recorded"]),entityType:z.literal("issue"),entityId:z.uuid(),issueId:z.uuid(),runId:z.uuid(), + details:z.object({source:z.literal("native_status_decision"),decisionId:z.uuid(),assessmentId:z.uuid(),toStatus:z.string()}).passthrough()}).passthrough(); + stopStatusDecisionEvents=subscribeCompanyLiveEvents(input.companyId,event=>{ + if(event.type!=="activity.logged"||event.companyId!==input.companyId)return; + const parsed=statusDecisionEvent.safeParse(event.payload);if(!parsed.success)return; + const value=parsed.data;if(value.entityId!==message.issueId||value.issueId!==message.issueId||value.runId!==message.runId)return; + stopStatusDecisionEvents(); // Exact commit removes the observer BEFORE publication to the parent and quiet checks. + send({kind:"native-status-committed",companyId:input.companyId,issueId:value.issueId,runId:value.runId, + decisionId:value.details.decisionId,assessmentId:value.details.assessmentId,toStatus:value.details.toStatus}); + }); + } if(message.command==="drain-run")await owner!.heartbeat.waitForRunExecutionDrain(message.runId,{timeoutMs:15000}); if(message.command==="stop-checkpointed"){ const {stopCheckpointedOwnedRun}=await import("./checkpointed-fault.js"); diff --git a/server/src/__tests__/native-workspace-sync.test.ts b/server/src/__tests__/native-workspace-sync.test.ts index 563b4aa0572..cc50f547782 100644 --- a/server/src/__tests__/native-workspace-sync.test.ts +++ b/server/src/__tests__/native-workspace-sync.test.ts @@ -1,4 +1,6 @@ -import { mkdtemp, readdir, rm, mkdir, writeFile, readFile, appendFile, symlink, stat } from "node:fs/promises"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { mkdtemp, readdir, rm, mkdir, writeFile, readFile, appendFile, symlink, stat, realpath } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -273,13 +275,16 @@ describe("native workspace sync durable metadata", () => { ).resolves.toMatchObject({ descriptor }); }); - it("repairs finalized remote and lease stamps after an interrupted commit", async () => { + it.each(["realized", "missing"] as const)("repairs finalized remote and lease stamps through confined command execution (%s workspace)", async (workspaceState) => { const paperclipHome = await mkdtemp( path.join(os.tmpdir(), "paperclip-native-workspace-sync-repair-"), ); cleanupDirs.push(paperclipHome); process.env.PAPERCLIP_HOME = paperclipHome; process.env.PAPERCLIP_INSTANCE_ID = "descriptor-repair-test"; + const remoteRoot = await realpath(paperclipHome); + const remoteCwd = path.join(remoteRoot, "workspace"); + if (workspaceState === "realized") await mkdir(remoteCwd); const baseline = { exclude: [".paperclip-runtime"], entries: new Map([ @@ -299,7 +304,7 @@ describe("native workspace sync durable metadata", () => { leaseId: "lease-1", providerLeaseId: "sandbox-1", localCwd: path.join(paperclipHome, "workspace"), - remoteCwd: "/workspace", + remoteCwd, }, state: "finalized" as const, baselineSha256: directorySnapshotSha256(baseline), @@ -344,10 +349,30 @@ describe("native workspace sync durable metadata", () => { }), }), }; - const execute = vi - .fn() - .mockResolvedValueOnce({ timedOut: false, exitCode: 1, stdout: "" }) - .mockResolvedValueOnce({ timedOut: false, exitCode: 0, stdout: "" }); + const executeFile = promisify(execFile); + const execute = vi.fn(async (request: { + command: string; args?: string[]; cwd?: string; timeoutMs?: number; bypassSession?: boolean; + }) => { + // Match the normal confined provider: omitted cwd uses its owned root; + // an explicit foreign cwd is refused before executing the real shell. + const cwd = await realpath(request.cwd ?? remoteRoot); + if (cwd !== remoteRoot && !cwd.startsWith(remoteRoot + path.sep)) throw new Error("foreign_command_cwd"); + expect(request.timeoutMs).toBe(15_000); + expect(request.bypassSession).toBe(true); + try { + const result = await executeFile(request.command, request.args ?? [], { + cwd, timeout: request.timeoutMs, encoding: "utf8", + }); + return { timedOut: false, exitCode: 0, ...result }; + } catch (error) { + // Preserve ordinary nonzero shell results. Missing cwd/transport faults + // still throw; they are never turned into a fabricated cache miss. + if (error instanceof Error && "code" in error && typeof error.code === "number") { + return { timedOut: false, exitCode: error.code, stdout: "", stderr: "stamp command failed" }; + } + throw error; + } + }); await expect( resumeNativeWorkspaceSync({ @@ -366,6 +391,9 @@ describe("native workspace sync durable metadata", () => { ).resolves.toBe(true); expect(execute).toHaveBeenCalledTimes(2); + expect(execute.mock.calls.map(([request]) => request.cwd)).toEqual([undefined, undefined]); + const remoteStamp = JSON.parse(await readFile(path.join(remoteCwd, ".paperclip-runtime", "paperclip-runner", "workspace-sync-v1.json"), "utf8")); + expect(remoteStamp).toMatchObject({ hostSha256: finalHostSha256, finalizedRunId: descriptor.binding.runId }); expect(persistedLeaseMetadata).toMatchObject({ retained: true, nativeWorkspaceSync: { diff --git a/server/src/services/native-runtime/native-workspace-sync.ts b/server/src/services/native-runtime/native-workspace-sync.ts index 82f703e98ca..88d246d2057 100644 --- a/server/src/services/native-runtime/native-workspace-sync.ts +++ b/server/src/services/native-runtime/native-workspace-sync.ts @@ -707,7 +707,6 @@ async function writeRemoteStamp(input: { "-c", `umask 077; mkdir -p ${shellQuote(runtimeDir)} && printf %s ${shellQuote(encoded)} | base64 -d > ${shellQuote(tempPath)} && mv ${shellQuote(tempPath)} ${shellQuote(stampPath)}`, ], - cwd: "/", timeoutMs: 15_000, bypassSession: true, }); @@ -754,7 +753,6 @@ async function remoteStampMatches(input: { "-c", [...gitChecks, `test -f ${shellQuote(stampPath)}`, `cat ${shellQuote(stampPath)}`].join(" && "), ], - cwd: "/", timeoutMs: 15_000, bypassSession: true, });