mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
fix(runner): persist warm Daytona workspaces (#12901)
## Thinking Path > - Paperclip manages AI agent work and the execution state for each task. > - Remote agents run in sandbox environments such as Daytona. > - Daytona keeps files while a sandbox is stopped, but deletion removes those files. > - Runner Codex did not copy successful remote workspace changes back to the host workspace. > - A warm sandbox could therefore hide data loss until Daytona replaced or deleted the sandbox. > - This pull request makes the host workspace durable after every successful turn and keeps verified reusable sandboxes warm. > - The benefit is reliable multi-turn work across warm reuse, restart, stop, and sandbox replacement. ## Linked Issues or Issue Description **What happened?** A successful native Codex turn in Daytona could leave workspace changes only in the remote sandbox. A later warm turn appeared to work because it reused that filesystem. A replacement sandbox could start from stale host data and lose the successful changes. **Expected behavior** Paperclip must merge each successful remote turn into the authoritative host workspace before it completes the run. A verified warm lease may reuse its remote files. A replacement lease must reconstruct the exact durable workspace seed. **Steps to reproduce** 1. Run Codex in a reusable Daytona environment. 2. Write a file during one successful turn. 3. Replace the Daytona sandbox before the next turn. 4. Observe that the next turn can start without the prior file on the unpatched code. Related remote workspace foundation: #10070. ## What Changed - Added explicit `host_current`, `durable_seed`, and `adopt_remote` workspace preparation modes. - Added atomic, versioned native workspace descriptors and seed archives under `PAPERCLIP_HOME`. - Added real native sandbox export and three-way host merge before terminal result completion. - Added workspace-only recovery after a proposed result. Recovery does not submit another provider turn or consume the provider retry budget. - Added fail-closed handling when a sandbox with unexported changes is gone. - Kept healthy reusable Daytona sandboxes started for legacy Codex and Runner Codex. - Kept the Runner Codex process and provider session across verified warm turns. - Added the paid `daytona-warm-continuity` browser suite. It contains exactly the legacy Codex and Runner Codex cells. Each cell performs three measured turns. - Documented `pnpm test:e2e:runner -- --suite daytona-warm-continuity`. No package script was added. - Added no database migration. The metadata format is backward compatible and idempotent. ## Verification - `pnpm typecheck` - `pnpm test:e2e:runner:unit` — 114 passed - Native workspace, finalizer, session, and environment tests — 232 passed - Daytona provider tests — 150 passed - Workspace staging and merge tests — 98 passed - Runner transport tests — 63 passed - Legacy Codex restore tests — 5 passed - Rust format and compile checks pass through root typecheck - The paid Daytona suite was not run locally because the required Daytona, OpenAI, and immutable image credentials are not present. ## Risks - The main risk is an incorrect workspace identity or merge after a crash. Durable descriptors bind the run, workspace, lease, provider lease, local root, remote root, and baseline digest. Ambiguous evidence fails closed. - The host merge may conflict with concurrent host edits. The existing three-way merge and exclusion rules handle this case and surface failures. - A deleted sandbox cannot recover unexported bytes. Paperclip now blocks with `workspace_sync_out_unrecoverable` instead of reporting success or rerunning the provider. - There is no database migration. Descriptor writes and recovery are atomic and idempotent. ## Model Used OpenAI Codex with GPT-5. The run used agentic reasoning, repository inspection, code execution, test execution, Git, and GitHub CLI tools. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
be407f3456
commit
1dceee9a4e
47 files changed
+4296
-359
No files matched your search
@@ -12,11 +12,15 @@ import {
|
||||
type SandboxRemoteExecutionSpec,
|
||||
type SandboxSyncOperation,
|
||||
type SandboxSyncResult,
|
||||
type WorkspaceDurableSeedPaths,
|
||||
type WorkspaceInboundMode,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
import { preferredShellForSandbox, shellCommandArgs } from "./sandbox-shell.js";
|
||||
import type { RunProcessResult } from "./server-utils.js";
|
||||
import type { RuntimeProgressSink, RuntimeStatusSink } from "./runtime-progress.js";
|
||||
import type { RuntimeSpanRunner } from "./acpx-engine/startup-timing.js";
|
||||
import type { GitWorkspaceSnapshot } from "./git-workspace-sync.js";
|
||||
import type { DirectorySnapshot } from "./workspace-restore-merge.js";
|
||||
|
||||
/**
|
||||
* Input for a duplex channel open. The caller supplies only the command argument
|
||||
@@ -516,6 +520,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: string;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: CommandManagedRuntimeAsset[];
|
||||
@@ -577,6 +585,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: mergeRuntimeExcludes(input.workspaceExclude),
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
@@ -616,6 +628,10 @@ export async function prepareCommandManagedRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: mergeRuntimeExcludes(input.workspaceExclude),
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
|
||||
@@ -18,10 +18,12 @@ import {
|
||||
import type {
|
||||
AdditionalSourceStagingFailure,
|
||||
SandboxAdditionalSource,
|
||||
WorkspaceDurableSeedPaths,
|
||||
WorkspaceInboundMode,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
export {
|
||||
resolveReferencedSourceIgnore,
|
||||
} from "./sandbox-managed-runtime.js";
|
||||
import type { GitWorkspaceSnapshot } from "./git-workspace-sync.js";
|
||||
import type { DirectorySnapshot } from "./workspace-restore-merge.js";
|
||||
export { resolveReferencedSourceIgnore } from "./sandbox-managed-runtime.js";
|
||||
export type {
|
||||
AdditionalSourceStagingFailure,
|
||||
ReferencedSourceIgnoreResolution,
|
||||
@@ -249,6 +251,10 @@ export interface PreparedAdapterExecutionTargetRuntime {
|
||||
* stage referenced projects, or when every requested project staged.
|
||||
*/
|
||||
additionalSourceFailures: AdditionalSourceStagingFailure[];
|
||||
workspaceSyncSnapshot: {
|
||||
baseline: DirectorySnapshot;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
} | null;
|
||||
restoreWorkspace(onProgress?: RuntimeProgressSink): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1374,6 +1380,10 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
timeoutSec?: number;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: AdapterManagedRuntimeAsset[];
|
||||
@@ -1403,6 +1413,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
assetDirs: {},
|
||||
additionalSourceDirs: {},
|
||||
additionalSourceFailures: [],
|
||||
workspaceSyncSnapshot: null,
|
||||
restoreWorkspace: async () => {},
|
||||
};
|
||||
}
|
||||
@@ -1428,6 +1439,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
// The SSH transport does not stage referenced projects (it is out of scope), so it never
|
||||
// reports a per-project staging failure.
|
||||
additionalSourceFailures: [],
|
||||
workspaceSyncSnapshot: null,
|
||||
restoreWorkspace: prepared.restoreWorkspace,
|
||||
};
|
||||
}
|
||||
@@ -1448,6 +1460,10 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
workspaceLocalDir: input.workspaceLocalDir,
|
||||
workspaceRemoteDir: input.workspaceRemoteDir,
|
||||
syncWorkspace: input.syncWorkspace,
|
||||
workspaceInboundMode: input.workspaceInboundMode,
|
||||
workspaceDurableSeed: input.workspaceDurableSeed,
|
||||
workspaceBaseline: input.workspaceBaseline,
|
||||
workspaceGitSnapshot: input.workspaceGitSnapshot,
|
||||
workspaceExclude: input.workspaceExclude,
|
||||
preserveAbsentOnRestore: input.preserveAbsentOnRestore,
|
||||
assets: input.assets,
|
||||
@@ -1465,6 +1481,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {
|
||||
assetDirs: prepared.assetDirs,
|
||||
additionalSourceDirs: prepared.additionalSourceDirs,
|
||||
additionalSourceFailures: prepared.additionalSourceFailures,
|
||||
workspaceSyncSnapshot: prepared.workspaceSyncSnapshot,
|
||||
restoreWorkspace: prepared.restoreWorkspace,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -348,6 +348,129 @@ describe("sandbox managed runtime", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("adopts a warm remote workspace without inbound overwrite and still merges outbound changes", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-sandbox-adopt-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
const localWorkspaceDir = path.join(rootDir, "local-workspace");
|
||||
const remoteWorkspaceDir = path.join(rootDir, "remote-workspace");
|
||||
await mkdir(localWorkspaceDir, { recursive: true });
|
||||
await mkdir(remoteWorkspaceDir, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"host baseline\n",
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(
|
||||
path.join(remoteWorkspaceDir, "continuity.txt"),
|
||||
"remote retained\n",
|
||||
"utf8",
|
||||
);
|
||||
const client = makeFilesystemClient();
|
||||
const syncIn = vi.spyOn(client, "syncIn");
|
||||
|
||||
const prepared = await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-warm",
|
||||
remoteCwd: remoteWorkspaceDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client,
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "adopt_remote",
|
||||
});
|
||||
|
||||
expect(syncIn).not.toHaveBeenCalled();
|
||||
await expect(
|
||||
readFile(path.join(remoteWorkspaceDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("remote retained\n");
|
||||
expect(prepared.workspaceSyncSnapshot).not.toBeNull();
|
||||
|
||||
await writeFile(
|
||||
path.join(remoteWorkspaceDir, "continuity.txt"),
|
||||
"remote finalized\n",
|
||||
"utf8",
|
||||
);
|
||||
await prepared.restoreWorkspace();
|
||||
await expect(
|
||||
readFile(path.join(localWorkspaceDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("remote finalized\n");
|
||||
});
|
||||
|
||||
it("reconstructs a replacement workspace from the exact durable pre-turn seed", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-sandbox-durable-seed-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
const localWorkspaceDir = path.join(rootDir, "local-workspace");
|
||||
const firstRemoteDir = path.join(rootDir, "first-remote");
|
||||
const replacementRemoteDir = path.join(rootDir, "replacement-remote");
|
||||
const durableSeed = {
|
||||
workspaceArchivePath: path.join(rootDir, "state", "workspace.tar"),
|
||||
gitArchivePath: path.join(rootDir, "state", "git.tar"),
|
||||
};
|
||||
await mkdir(localWorkspaceDir, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"durable pre-turn bytes\n",
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const first = await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-first",
|
||||
remoteCwd: firstRemoteDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client: makeFilesystemClient(),
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "host_current",
|
||||
workspaceDurableSeed: durableSeed,
|
||||
});
|
||||
expect(first.workspaceSyncSnapshot).not.toBeNull();
|
||||
await expect(stat(durableSeed.workspaceArchivePath)).resolves.toMatchObject(
|
||||
{
|
||||
mode: expect.any(Number),
|
||||
},
|
||||
);
|
||||
|
||||
await writeFile(
|
||||
path.join(localWorkspaceDir, "continuity.txt"),
|
||||
"concurrent host edit must not enter replacement\n",
|
||||
"utf8",
|
||||
);
|
||||
await prepareSandboxManagedRuntime({
|
||||
spec: {
|
||||
transport: "sandbox",
|
||||
provider: "test",
|
||||
sandboxId: "sandbox-replacement",
|
||||
remoteCwd: replacementRemoteDir,
|
||||
timeoutMs: 30_000,
|
||||
apiKey: null,
|
||||
},
|
||||
adapterKey: "test-adapter",
|
||||
client: makeFilesystemClient(),
|
||||
workspaceLocalDir: localWorkspaceDir,
|
||||
workspaceInboundMode: "durable_seed",
|
||||
workspaceDurableSeed: durableSeed,
|
||||
workspaceBaseline: first.workspaceSyncSnapshot!.baseline,
|
||||
workspaceGitSnapshot: first.workspaceSyncSnapshot!.gitSnapshot,
|
||||
});
|
||||
|
||||
await expect(
|
||||
readFile(path.join(replacementRemoteDir, "continuity.txt"), "utf8"),
|
||||
).resolves.toBe("durable pre-turn bytes\n");
|
||||
});
|
||||
|
||||
it("preserves excluded local workspace artifacts during restore mirroring", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-sandbox-restore-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
constants as fsConstants,
|
||||
createReadStream,
|
||||
promises as fs,
|
||||
} from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
@@ -12,6 +16,7 @@ import {
|
||||
deleteLocalGitRef,
|
||||
fetchGitBundleIntoLocalRef,
|
||||
GIT_ARCHIVE_EXCLUDES,
|
||||
type GitWorkspaceSnapshot,
|
||||
integrateImportedGitHead,
|
||||
readGitWorkspaceSnapshot,
|
||||
ReferencedSourceIgnoreScanLimitExceededError,
|
||||
@@ -20,7 +25,11 @@ import {
|
||||
withShallowGitWorkspaceClone,
|
||||
WORKSPACE_GIT_SCAN_SATURATED_CODE,
|
||||
} from "./git-workspace-sync.js";
|
||||
import { captureDirectorySnapshot, mergeDirectoryWithBaseline } from "./workspace-restore-merge.js";
|
||||
import {
|
||||
captureDirectorySnapshot,
|
||||
mergeDirectoryWithBaseline,
|
||||
type DirectorySnapshot,
|
||||
} from "./workspace-restore-merge.js";
|
||||
import {
|
||||
createRuntimeProgressReporter,
|
||||
type RuntimeProgressDirection,
|
||||
@@ -553,9 +562,29 @@ export interface PreparedSandboxManagedRuntime {
|
||||
* staged, or when no additional sources were requested.
|
||||
*/
|
||||
additionalSourceFailures: AdditionalSourceStagingFailure[];
|
||||
/** Durable merge inputs used to resume an outbound restore after host restart. */
|
||||
workspaceSyncSnapshot: {
|
||||
baseline: DirectorySnapshot;
|
||||
gitSnapshot: GitWorkspaceSnapshot | null;
|
||||
} | null;
|
||||
restoreWorkspace(onProgress?: RuntimeProgressSink): Promise<void>;
|
||||
}
|
||||
|
||||
export type WorkspaceInboundMode =
|
||||
"host_current" | "durable_seed" | "adopt_remote";
|
||||
|
||||
/**
|
||||
* Controller-owned archives for replaying the exact pre-turn workspace into a
|
||||
* replacement sandbox. Paths are never sent to the provider as credentials or
|
||||
* persisted in database metadata.
|
||||
*/
|
||||
export interface WorkspaceDurableSeedPaths {
|
||||
workspaceArchivePath: string;
|
||||
workspaceArchiveSha256?: string;
|
||||
gitArchivePath?: string | null;
|
||||
gitArchiveSha256?: string | null;
|
||||
}
|
||||
|
||||
/** One additional (referenced) project that failed to stage into the sandbox. */
|
||||
export interface AdditionalSourceStagingFailure {
|
||||
projectId: string;
|
||||
@@ -719,6 +748,57 @@ async function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>):
|
||||
}
|
||||
}
|
||||
|
||||
async function sha256File(filePath: string): Promise<string> {
|
||||
return await new Promise((resolveDigest, rejectDigest) => {
|
||||
const digest = createHash("sha256");
|
||||
const stream = createReadStream(filePath);
|
||||
stream.on("data", (chunk) => digest.update(chunk));
|
||||
stream.on("error", rejectDigest);
|
||||
stream.on("end", () => resolveDigest(digest.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
async function copyDurableSeedArchive(input: {
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
expectedSha256?: string | null;
|
||||
}): Promise<void> {
|
||||
const source = await fs.lstat(input.sourcePath);
|
||||
if (source.isSymbolicLink() || !source.isFile()) {
|
||||
throw new Error("workspace_durable_seed_invalid");
|
||||
}
|
||||
if (
|
||||
input.expectedSha256 &&
|
||||
(await sha256File(input.sourcePath)) !== input.expectedSha256
|
||||
) {
|
||||
throw new Error("workspace_durable_seed_digest_mismatch");
|
||||
}
|
||||
await fs.copyFile(input.sourcePath, input.targetPath);
|
||||
}
|
||||
|
||||
async function persistDurableSeedArchive(input: {
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
}): Promise<void> {
|
||||
const parent = path.dirname(input.targetPath);
|
||||
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
const parentStat = await fs.lstat(parent);
|
||||
if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) {
|
||||
throw new Error("workspace_durable_seed_root_invalid");
|
||||
}
|
||||
const temporary = path.join(
|
||||
parent,
|
||||
`.${path.basename(input.targetPath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
try {
|
||||
await fs.copyFile(input.sourcePath, temporary);
|
||||
await fs.chmod(temporary, 0o600);
|
||||
await fs.rename(temporary, input.targetPath);
|
||||
} finally {
|
||||
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function execTar(args: string[]): Promise<void> {
|
||||
await execFile("tar", args, {
|
||||
env: {
|
||||
@@ -976,6 +1056,12 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
workspaceLocalDir: string;
|
||||
workspaceRemoteDir?: string;
|
||||
syncWorkspace?: boolean;
|
||||
/** Selects authoritative host staging, exact durable-seed replay, or no-overwrite adoption. */
|
||||
workspaceInboundMode?: WorkspaceInboundMode;
|
||||
workspaceDurableSeed?: WorkspaceDurableSeedPaths;
|
||||
/** Durable snapshots supplied when reconstructing an interrupted restore. */
|
||||
workspaceBaseline?: DirectorySnapshot;
|
||||
workspaceGitSnapshot?: GitWorkspaceSnapshot | null;
|
||||
workspaceExclude?: string[];
|
||||
preserveAbsentOnRestore?: string[];
|
||||
assets?: SandboxManagedRuntimeAsset[];
|
||||
@@ -999,6 +1085,16 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;
|
||||
const runtimeRootDir = path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);
|
||||
const syncWorkspace = input.syncWorkspace !== false;
|
||||
const workspaceInboundMode = input.workspaceInboundMode ?? "host_current";
|
||||
const stageWorkspace =
|
||||
syncWorkspace && workspaceInboundMode !== "adopt_remote";
|
||||
const prepareWorkspaceSeed =
|
||||
syncWorkspace &&
|
||||
workspaceInboundMode === "adopt_remote" &&
|
||||
input.workspaceDurableSeed !== undefined;
|
||||
if (workspaceInboundMode === "durable_seed" && !input.workspaceDurableSeed) {
|
||||
throw new Error("workspace_durable_seed_missing");
|
||||
}
|
||||
|
||||
// Reject any unsafe asset key before an archive path or an asset directory is
|
||||
// built from it. This runs before the git snapshot work so a bad key fails fast.
|
||||
@@ -1025,7 +1121,11 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// It reads git's own bookkeeping to decide what to include/exclude, so it is
|
||||
// usually fast, but on a large working tree the `--ignored` walk is not free.
|
||||
const gitSnapshot = syncWorkspace
|
||||
? await runStepSpan("snapshot.git", () => readGitWorkspaceSnapshot(input.workspaceLocalDir))
|
||||
? input.workspaceGitSnapshot !== undefined
|
||||
? input.workspaceGitSnapshot
|
||||
: await runStepSpan("snapshot.git", () =>
|
||||
readGitWorkspaceSnapshot(input.workspaceLocalDir),
|
||||
)
|
||||
: null;
|
||||
const gitIgnoredExcludes = gitSnapshot?.ignoredPaths;
|
||||
const workspaceArchiveExclude = mergeExcludes(
|
||||
@@ -1047,9 +1147,12 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// dominant cost in the pre-`pack` window — it reads the content of every
|
||||
// non-excluded file, serially — so it earns its own span.
|
||||
const baselineSnapshot = syncWorkspace
|
||||
? await runStepSpan("snapshot.baseline", () =>
|
||||
captureDirectorySnapshot(input.workspaceLocalDir, { exclude: restoreExclude }),
|
||||
)
|
||||
? (input.workspaceBaseline ??
|
||||
(await runStepSpan("snapshot.baseline", () =>
|
||||
captureDirectorySnapshot(input.workspaceLocalDir, {
|
||||
exclude: restoreExclude,
|
||||
}),
|
||||
)))
|
||||
: null;
|
||||
|
||||
// Every inbound staging step delegates to the provider through `client.syncIn`:
|
||||
@@ -1172,7 +1275,7 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// records its own failure and never rejects.
|
||||
const inboundTaskIsRequired: boolean[] = [];
|
||||
|
||||
if (syncWorkspace) {
|
||||
if (stageWorkspace || prepareWorkspaceSeed) {
|
||||
inboundTaskIsRequired.push(true);
|
||||
inboundTasks.push(() =>
|
||||
runStepSpan("stage.workspace", async () => {
|
||||
@@ -1203,18 +1306,49 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
if (gitSnapshot) {
|
||||
await emitRuntimeStatus(input.onRuntimeProgress, "git_sync", "Syncing git history to environment");
|
||||
const gitTarPath = path.join(tempDir, "git-workspace.tar");
|
||||
const remoteGitTar = path.posix.join(runtimeRootDir, "git-workspace-upload.tar");
|
||||
await withShallowGitWorkspaceClone({
|
||||
localDir: input.workspaceLocalDir,
|
||||
snapshot: gitSnapshot,
|
||||
}, async (cloneDir) => {
|
||||
await createTarballFromDirectory({
|
||||
localDir: cloneDir,
|
||||
archivePath: gitTarPath,
|
||||
exclude: [".paperclip-runtime"],
|
||||
const remoteGitTar = path.posix.join(
|
||||
runtimeRootDir,
|
||||
"git-workspace-upload.tar",
|
||||
);
|
||||
if (workspaceInboundMode === "durable_seed") {
|
||||
const durableGitArchive =
|
||||
input.workspaceDurableSeed?.gitArchivePath;
|
||||
if (!durableGitArchive) {
|
||||
throw new Error("workspace_durable_seed_git_missing");
|
||||
}
|
||||
await copyDurableSeedArchive({
|
||||
sourcePath: durableGitArchive,
|
||||
targetPath: gitTarPath,
|
||||
expectedSha256: input.workspaceDurableSeed?.gitArchiveSha256,
|
||||
});
|
||||
} else {
|
||||
await withShallowGitWorkspaceClone(
|
||||
{
|
||||
localDir: input.workspaceLocalDir,
|
||||
snapshot: gitSnapshot,
|
||||
},
|
||||
async (cloneDir) => {
|
||||
await createTarballFromDirectory({
|
||||
localDir: cloneDir,
|
||||
archivePath: gitTarPath,
|
||||
exclude: [".paperclip-runtime"],
|
||||
});
|
||||
},
|
||||
);
|
||||
if (input.workspaceDurableSeed?.gitArchivePath) {
|
||||
await persistDurableSeedArchive({
|
||||
sourcePath: gitTarPath,
|
||||
targetPath: input.workspaceDurableSeed.gitArchivePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
workspaceFiles.push({
|
||||
sourcePath: gitTarPath,
|
||||
targetPath: remoteGitTar,
|
||||
kind: "file",
|
||||
access: "rw",
|
||||
writablePath: workspaceRemoteDir,
|
||||
});
|
||||
workspaceFiles.push({ sourcePath: gitTarPath, targetPath: remoteGitTar, kind: "file", access: "rw", writablePath: workspaceRemoteDir });
|
||||
workspacePostUploadCommands.push({
|
||||
command: buildWorkspaceTarExtractCommand({
|
||||
workspaceRemoteDir,
|
||||
@@ -1230,22 +1364,48 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
// the preserved names first. The extract runs AFTER the git extract.
|
||||
await emitRuntimeStatus(input.onRuntimeProgress, "config_sync", "Syncing workspace to environment");
|
||||
const workspaceTarPath = path.join(tempDir, "workspace.tar");
|
||||
const workspaceArchiveDir = gitSnapshot ? path.join(tempDir, "workspace-overlay") : input.workspaceLocalDir;
|
||||
if (gitSnapshot) {
|
||||
await copySelectedWorkspaceEntries({
|
||||
sourceDir: input.workspaceLocalDir,
|
||||
targetDir: workspaceArchiveDir,
|
||||
relativePaths: gitSnapshot.overlayPaths,
|
||||
exclude: workspaceArchiveExclude,
|
||||
if (workspaceInboundMode === "durable_seed") {
|
||||
await copyDurableSeedArchive({
|
||||
sourcePath: input.workspaceDurableSeed!.workspaceArchivePath,
|
||||
targetPath: workspaceTarPath,
|
||||
expectedSha256:
|
||||
input.workspaceDurableSeed!.workspaceArchiveSha256,
|
||||
});
|
||||
} else {
|
||||
const workspaceArchiveDir = gitSnapshot
|
||||
? path.join(tempDir, "workspace-overlay")
|
||||
: input.workspaceLocalDir;
|
||||
if (gitSnapshot) {
|
||||
await copySelectedWorkspaceEntries({
|
||||
sourceDir: input.workspaceLocalDir,
|
||||
targetDir: workspaceArchiveDir,
|
||||
relativePaths: gitSnapshot.overlayPaths,
|
||||
exclude: workspaceArchiveExclude,
|
||||
});
|
||||
}
|
||||
await createTarballFromDirectory({
|
||||
localDir: workspaceArchiveDir,
|
||||
archivePath: workspaceTarPath,
|
||||
exclude: gitSnapshot ? undefined : workspaceArchiveExclude,
|
||||
});
|
||||
if (input.workspaceDurableSeed) {
|
||||
await persistDurableSeedArchive({
|
||||
sourcePath: workspaceTarPath,
|
||||
targetPath: input.workspaceDurableSeed.workspaceArchivePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
await createTarballFromDirectory({
|
||||
localDir: workspaceArchiveDir,
|
||||
archivePath: workspaceTarPath,
|
||||
exclude: gitSnapshot ? undefined : workspaceArchiveExclude,
|
||||
const remoteWorkspaceTar = path.posix.join(
|
||||
runtimeRootDir,
|
||||
"workspace-upload.tar",
|
||||
);
|
||||
workspaceFiles.push({
|
||||
sourcePath: workspaceTarPath,
|
||||
targetPath: remoteWorkspaceTar,
|
||||
kind: "file",
|
||||
access: "rw",
|
||||
writablePath: workspaceRemoteDir,
|
||||
});
|
||||
const remoteWorkspaceTar = path.posix.join(runtimeRootDir, "workspace-upload.tar");
|
||||
workspaceFiles.push({ sourcePath: workspaceTarPath, targetPath: remoteWorkspaceTar, kind: "file", access: "rw", writablePath: workspaceRemoteDir });
|
||||
workspacePostUploadCommands.push({
|
||||
command: buildWorkspaceTarExtractCommand({
|
||||
workspaceRemoteDir,
|
||||
@@ -1265,6 +1425,8 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
workspaceUploadBytes += (await fs.stat(workspaceTarPath)).size;
|
||||
});
|
||||
|
||||
if (!stageWorkspace) return;
|
||||
|
||||
// One confined `syncIn` for the whole merged workspace file set. The confine
|
||||
// guard covers every mapping BEFORE any bytes upload (fail-closed): a source
|
||||
// or target escape in EITHER tar mapping stops the upload of both.
|
||||
@@ -1457,6 +1619,10 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
assetDirs,
|
||||
additionalSourceDirs,
|
||||
additionalSourceFailures,
|
||||
workspaceSyncSnapshot:
|
||||
syncWorkspace && baselineSnapshot
|
||||
? { baseline: baselineSnapshot, gitSnapshot }
|
||||
: null,
|
||||
restoreWorkspace: async (onProgress?: RuntimeProgressSink) => {
|
||||
const restoreSink = onProgress ?? input.onProgress;
|
||||
|
||||
|
||||
@@ -9,9 +9,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { resolvePaperclipInstanceRootForAdapter } from "./server-utils.js";
|
||||
import {
|
||||
captureDirectorySnapshot,
|
||||
directorySnapshotSha256,
|
||||
classifyWorkspaceRestoreFailure,
|
||||
describeWorkspaceRestoreFailure,
|
||||
mergeDirectoryWithBaseline,
|
||||
parseDirectorySnapshot,
|
||||
serializeDirectorySnapshot,
|
||||
withDirectoryMergeLock,
|
||||
WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE,
|
||||
} from "./workspace-restore-merge.js";
|
||||
@@ -27,6 +30,36 @@ describe("workspace restore merge", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips a deterministic durable snapshot and rejects traversal", async () => {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-snapshot-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
await mkdir(path.join(rootDir, "nested"), { recursive: true });
|
||||
await writeFile(path.join(rootDir, "b.txt"), "bravo\n", "utf8");
|
||||
await writeFile(path.join(rootDir, "nested", "a.txt"), "alpha\n", "utf8");
|
||||
|
||||
const snapshot = await captureDirectorySnapshot(rootDir, { exclude: [] });
|
||||
const serialized = serializeDirectorySnapshot(snapshot);
|
||||
const restored = parseDirectorySnapshot(serialized);
|
||||
|
||||
expect(serialized.entries.map(([relativePath]) => relativePath)).toEqual([
|
||||
"b.txt",
|
||||
"nested",
|
||||
"nested/a.txt",
|
||||
]);
|
||||
expect(restored).not.toBeNull();
|
||||
expect(directorySnapshotSha256(restored!)).toBe(
|
||||
directorySnapshotSha256(snapshot),
|
||||
);
|
||||
expect(
|
||||
parseDirectorySnapshot({
|
||||
...serialized,
|
||||
entries: [["../escape", serialized.entries[0]![1]]],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves sibling files when sequential stale-baseline restores create the same nested directory tree", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import { shouldExcludePath } from "./exclude-patterns.js";
|
||||
import { resolvePaperclipInstanceRootForAdapter } from "./server-utils.js";
|
||||
|
||||
type SnapshotEntry =
|
||||
export type SnapshotEntry =
|
||||
| { kind: "dir" }
|
||||
| { kind: "file"; mode: number; hash: string }
|
||||
| { kind: "symlink"; target: string };
|
||||
@@ -15,6 +15,87 @@ export interface DirectorySnapshot {
|
||||
entries: Map<string, SnapshotEntry>;
|
||||
}
|
||||
|
||||
export interface SerializedDirectorySnapshot {
|
||||
version: 1;
|
||||
exclude: string[];
|
||||
entries: Array<[string, SnapshotEntry]>;
|
||||
}
|
||||
|
||||
function isSafeSnapshotRelativePath(value: string): boolean {
|
||||
if (!value || path.posix.isAbsolute(value) || path.win32.isAbsolute(value)) {
|
||||
return false;
|
||||
}
|
||||
return !value.split(/[\\/]/).some((segment) => segment === "..");
|
||||
}
|
||||
|
||||
function parseSnapshotEntry(value: unknown): SnapshotEntry | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (candidate.kind === "dir") return { kind: "dir" };
|
||||
if (candidate.kind === "symlink" && typeof candidate.target === "string") {
|
||||
return { kind: "symlink", target: candidate.target };
|
||||
}
|
||||
if (
|
||||
candidate.kind === "file" &&
|
||||
typeof candidate.mode === "number" &&
|
||||
Number.isInteger(candidate.mode) &&
|
||||
candidate.mode >= 0 &&
|
||||
typeof candidate.hash === "string" &&
|
||||
/^[0-9a-f]{64}$/.test(candidate.hash)
|
||||
) {
|
||||
return { kind: "file", mode: candidate.mode, hash: candidate.hash };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function serializeDirectorySnapshot(
|
||||
snapshot: DirectorySnapshot,
|
||||
): SerializedDirectorySnapshot {
|
||||
return {
|
||||
version: 1,
|
||||
exclude: [...snapshot.exclude],
|
||||
entries: [...snapshot.entries.entries()].sort(([left], [right]) =>
|
||||
left.localeCompare(right),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseDirectorySnapshot(
|
||||
value: unknown,
|
||||
): DirectorySnapshot | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (
|
||||
candidate.version !== 1 ||
|
||||
!Array.isArray(candidate.exclude) ||
|
||||
!candidate.exclude.every((entry) => typeof entry === "string") ||
|
||||
!Array.isArray(candidate.entries)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const entries = new Map<string, SnapshotEntry>();
|
||||
for (const rawEntry of candidate.entries) {
|
||||
if (!Array.isArray(rawEntry) || rawEntry.length !== 2) return null;
|
||||
const [relative, rawSnapshotEntry] = rawEntry;
|
||||
if (typeof relative !== "string" || !isSafeSnapshotRelativePath(relative)) {
|
||||
return null;
|
||||
}
|
||||
const entry = parseSnapshotEntry(rawSnapshotEntry);
|
||||
if (!entry || entries.has(relative)) return null;
|
||||
entries.set(relative, entry);
|
||||
}
|
||||
return {
|
||||
exclude: [...new Set(candidate.exclude as string[])],
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
export function directorySnapshotSha256(snapshot: DirectorySnapshot): string {
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify(serializeDirectorySnapshot(snapshot)))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
async function hashFile(filePath: string): Promise<string> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const hash = createHash("sha256");
|
||||
|
||||
@@ -117,11 +117,10 @@ describe("codex execute — outbound auth copy-back restore contribution", () =>
|
||||
);
|
||||
}
|
||||
|
||||
async function runTeardown(input: {
|
||||
sandboxAuth: string;
|
||||
hostAuth: string;
|
||||
}): Promise<{ finalHostAuth: string; finalHostMode: number }> {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-codex-copyback-e2e-"));
|
||||
async function runTeardown(input: { sandboxAuth: string; hostAuth: string }) {
|
||||
const rootDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), "paperclip-codex-copyback-e2e-"),
|
||||
);
|
||||
cleanupDirs.push(rootDir);
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
// The shared host home is what `resolveSharedCodexHomeDir` returns
|
||||
@@ -137,7 +136,7 @@ describe("codex execute — outbound auth copy-back restore contribution", () =>
|
||||
process.env.CODEX_HOME = sharedHostHome;
|
||||
sandboxAuthFixture.bytes = Buffer.from(input.sandboxAuth, "utf8");
|
||||
|
||||
await execute({
|
||||
const executionResult = await execute({
|
||||
runId: "run-copyback-e2e",
|
||||
agent: {
|
||||
id: "agent-1",
|
||||
@@ -178,6 +177,7 @@ describe("codex execute — outbound auth copy-back restore contribution", () =>
|
||||
return {
|
||||
finalHostAuth: await readFile(hostAuthPath, "utf8"),
|
||||
finalHostMode: (await lstat(hostAuthPath)).mode & 0o777,
|
||||
executionResult,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -231,4 +231,50 @@ describe("codex execute — outbound auth copy-back restore contribution", () =>
|
||||
expect(result.finalHostMode, entry.name).toBe(0o600);
|
||||
}
|
||||
});
|
||||
|
||||
it("surfaces workspace restore failure after successful provider execution", async () => {
|
||||
prepareAdapterExecutionTargetRuntime.mockResolvedValueOnce({
|
||||
target: { kind: "remote", transport: "ssh" },
|
||||
workspaceRemoteDir: "/remote/workspace",
|
||||
runtimeRootDir: REMOTE_RUNTIME_ROOT,
|
||||
assetDirs: { home: `${REMOTE_RUNTIME_ROOT}/home` },
|
||||
restoreWorkspace: async () => {
|
||||
throw new Error("workspace copy-back failed");
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
runTeardown({
|
||||
sandboxAuth: subscriptionAuth({ accountId: "acct", marker: "sandbox" }),
|
||||
hostAuth: subscriptionAuth({ accountId: "acct", marker: "host" }),
|
||||
}),
|
||||
).rejects.toThrow("workspace copy-back failed");
|
||||
});
|
||||
|
||||
it("preserves a provider failure when workspace restore also fails", async () => {
|
||||
runChildProcess.mockResolvedValueOnce({
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
stdout: "",
|
||||
stderr: "provider failed first",
|
||||
pid: 321,
|
||||
startedAt: new Date().toISOString(),
|
||||
});
|
||||
prepareAdapterExecutionTargetRuntime.mockResolvedValueOnce({
|
||||
target: { kind: "remote", transport: "ssh" },
|
||||
workspaceRemoteDir: "/remote/workspace",
|
||||
runtimeRootDir: REMOTE_RUNTIME_ROOT,
|
||||
assetDirs: { home: `${REMOTE_RUNTIME_ROOT}/home` },
|
||||
restoreWorkspace: async () => {
|
||||
throw new Error("workspace copy-back failed second");
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runTeardown({
|
||||
sandboxAuth: subscriptionAuth({ accountId: "acct", marker: "sandbox" }),
|
||||
hostAuth: subscriptionAuth({ accountId: "acct", marker: "host" }),
|
||||
});
|
||||
expect(result.executionResult.errorMessage).toBe("provider failed first");
|
||||
});
|
||||
});
|
||||
@@ -1526,6 +1526,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
};
|
||||
};
|
||||
|
||||
let executionError: unknown = null;
|
||||
try {
|
||||
const initial = await runAttempt(sessionId);
|
||||
if (
|
||||
@@ -1539,22 +1540,26 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
`[paperclip] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
|
||||
);
|
||||
const retry = await runAttempt(null);
|
||||
return toResult(retry, true, true);
|
||||
const retryResult = toResult(retry, true, true);
|
||||
if (retryResult.errorMessage) {
|
||||
executionError = new Error(retryResult.errorMessage);
|
||||
}
|
||||
return retryResult;
|
||||
}
|
||||
|
||||
return toResult(initial, false, false);
|
||||
const result = toResult(initial, false, false);
|
||||
if (result.errorMessage) {
|
||||
executionError = new Error(result.errorMessage);
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
executionError = error;
|
||||
throw error;
|
||||
} finally {
|
||||
if (paperclipBridge) {
|
||||
await paperclipBridge.stop();
|
||||
}
|
||||
if (restoreRemoteWorkspace) {
|
||||
// This teardown runs in a `finally`, so a throw here replaces the
|
||||
// already-computed run result (`return toResult(...)`) and turns a
|
||||
// successful Codex run into a failure. The workspace restore — and the
|
||||
// host credential copy-back inside it — is a best-effort teardown step.
|
||||
// Keep it rejection-safe: log a fault loudly and keep the pending
|
||||
// result. The host copy-back installs the credential on disk before any
|
||||
// diagnostic log runs, so it is already durable when this block returns.
|
||||
try {
|
||||
await onLog(
|
||||
"stdout",
|
||||
@@ -1570,6 +1575,10 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
)}: ${error instanceof Error ? error.message : String(error)}\n`,
|
||||
),
|
||||
).catch(() => undefined);
|
||||
// A provider failure remains the primary outcome. When provider work
|
||||
// succeeded, however, silently accepting a failed copy-back can lose
|
||||
// the only workspace edits before a replacement sandbox starts.
|
||||
if (executionError === null) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1345,6 +1345,13 @@ impl CommandExecutor for AcpxCommandExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_authority(&mut self, config: &DurableRunnerConfig) {
|
||||
self.context.run_id = config.run_id.clone();
|
||||
self.context.normalized_session_id = config.normalized_session_id.clone();
|
||||
self.context.turn_id = config.turn_id.clone();
|
||||
self.context.item_id = config.item_id.clone();
|
||||
}
|
||||
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.restore()?;
|
||||
if self
|
||||
|
||||
@@ -54,7 +54,7 @@ pub(crate) const MAX_SETTLED_PROVIDER_TURN_IDS: usize = 4_096;
|
||||
type QuestionOptionLabels = BTreeMap<String, BTreeMap<String, String>>;
|
||||
type QuestionSetMapping = (String, Value, QuestionOptionLabels);
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct ProviderCompletionContract {
|
||||
revision: String,
|
||||
criterion_ids: Vec<String>,
|
||||
@@ -807,6 +807,46 @@ impl CodexProvider {
|
||||
self.durable_tool_call_replays = true;
|
||||
}
|
||||
|
||||
pub(crate) fn attach_run_in_place(
|
||||
&mut self,
|
||||
authorized_tools: impl IntoIterator<Item = AuthorizedTool>,
|
||||
completion_contract: Option<(&str, &[String])>,
|
||||
) -> Result<bool, LocalRunnerError> {
|
||||
let authorized_tools = authorized_tools.into_iter().collect::<Vec<_>>();
|
||||
let completion_contract =
|
||||
completion_contract.map(|(revision, criterion_ids)| ProviderCompletionContract {
|
||||
revision: revision.to_owned(),
|
||||
criterion_ids: criterion_ids.to_vec(),
|
||||
});
|
||||
if authorized_tools != self.authorized_tools
|
||||
|| completion_contract != self.completion_contract
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
if self.process.try_wait()?.is_some()
|
||||
|| self.quarantined
|
||||
|| self.active_provider_turn_id.is_some()
|
||||
|| self.ambiguous_turn_start_pending
|
||||
|| !self.pending_messages.is_empty()
|
||||
|| !self.deferred_ambiguous_messages.is_empty()
|
||||
|| !self.pending_tool_requests.is_empty()
|
||||
|| !self.pending_runtime_requests.is_empty()
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"Codex warm run attachment requires an idle live provider with no pending work",
|
||||
));
|
||||
}
|
||||
// The provider process and its thread remain authoritative. Exact
|
||||
// settled-turn identities stay in memory so delayed output from an
|
||||
// earlier run cannot be accepted as the next turn. A changed semantic
|
||||
// tool or completion contract returns false so the caller can preserve
|
||||
// the existing cold-resume behavior for that incompatible boundary.
|
||||
self.completed_turn_authority = None;
|
||||
self.completion_reconciliation_pending = false;
|
||||
self.expected_shutdown = false;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_completed_turn_authority(
|
||||
&mut self,
|
||||
authoritative: bool,
|
||||
|
||||
@@ -116,9 +116,121 @@ impl CommandLifecycle {
|
||||
}
|
||||
}
|
||||
|
||||
fn next_authority_config(
|
||||
command: &Command,
|
||||
current: &DurableRunnerConfig,
|
||||
) -> Result<Option<DurableRunnerConfig>, DurableRunnerError> {
|
||||
if command.command_type != "run.attach" {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(boundary) = command.payload.get("paperclipNextAuthority") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let identity = boundary
|
||||
.get("identity")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| DurableRunnerError::invalid("run.attach authority identity is required"))?;
|
||||
let read_identity = |key: &str| {
|
||||
identity
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| {
|
||||
DurableRunnerError::invalid(format!(
|
||||
"run.attach authority identity field {key} is required"
|
||||
))
|
||||
})
|
||||
};
|
||||
let connection = boundary
|
||||
.get("connection")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| {
|
||||
DurableRunnerError::invalid("run.attach authority connection is required")
|
||||
})?;
|
||||
let connect_url = match connection.get("mode").and_then(Value::as_str) {
|
||||
Some("connect") => connection
|
||||
.get("connectUrl")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| DurableRunnerError::invalid("run.attach connect URL is required"))?,
|
||||
Some("listen") => {
|
||||
let address = connection
|
||||
.get("listenAddress")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| {
|
||||
DurableRunnerError::invalid("run.attach listen address is required")
|
||||
})?;
|
||||
let port = connection
|
||||
.get("listenPort")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| DurableRunnerError::invalid("run.attach listen port is required"))?;
|
||||
let path = connection
|
||||
.get("listenPath")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| DurableRunnerError::invalid("run.attach listen path is required"))?;
|
||||
format!("listen://{address}:{port}{path}")
|
||||
}
|
||||
_ => {
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"run.attach authority connection mode is invalid",
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut next = current.clone();
|
||||
next.connect_url = connect_url;
|
||||
next.ca_bundle_path = connection
|
||||
.get("caBundlePath")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(Into::into);
|
||||
next.runner_instance_id = read_identity("runnerInstanceId")?;
|
||||
next.environment_lease_id = read_identity("environmentLeaseId")?;
|
||||
next.run_id = read_identity("runId")?;
|
||||
next.normalized_session_id = read_identity("normalizedSessionId")?;
|
||||
next.turn_id = read_identity("turnId")?;
|
||||
next.item_id = read_identity("itemId")?;
|
||||
next.validate()?;
|
||||
if next.runner_instance_id != current.runner_instance_id
|
||||
|| next.environment_lease_id != current.environment_lease_id
|
||||
|| next.normalized_session_id != current.normalized_session_id
|
||||
|| next.run_id == current.run_id
|
||||
{
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"run.attach authority changed an immutable session binding",
|
||||
));
|
||||
}
|
||||
Ok(Some(next))
|
||||
}
|
||||
|
||||
fn apply_authority_rotation(
|
||||
state: &mut DurableState,
|
||||
store: &DurableStateStore,
|
||||
config: &mut DurableRunnerConfig,
|
||||
endpoint: &mut RunnerTransportEndpoint,
|
||||
next: DurableRunnerConfig,
|
||||
) -> Result<(), DurableRunnerError> {
|
||||
let reconnect_count = state.reconnect_count.saturating_add(1);
|
||||
let mut diagnostics = std::mem::take(&mut state.diagnostics);
|
||||
*endpoint = RunnerTransportEndpoint::new(&next.connect_url, &next.run_id)?;
|
||||
*config = next;
|
||||
let mut rotated = DurableState::new(config);
|
||||
rotated.reconnect_count = reconnect_count;
|
||||
rotated.diagnostics.append(&mut diagnostics);
|
||||
rotated.record_diagnostic("runner advanced to a new warm run authority");
|
||||
*state = rotated;
|
||||
store.save(state)
|
||||
}
|
||||
|
||||
pub trait CommandExecutor {
|
||||
fn execute(&mut self, command: &Command) -> Result<CommandExecution, DurableRunnerError>;
|
||||
|
||||
/// Advances provider-side event correlation after a durable `run.attach`
|
||||
/// has moved runnerd to the next run-bound authority. The runner validates
|
||||
/// and persists the new authority before invoking this infallible hook.
|
||||
fn rotate_authority(&mut self, _config: &DurableRunnerConfig) {}
|
||||
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
@@ -136,7 +248,7 @@ pub trait CommandExecutor {
|
||||
}
|
||||
|
||||
pub fn run_durable_runner<E: CommandExecutor>(
|
||||
config: DurableRunnerConfig,
|
||||
mut config: DurableRunnerConfig,
|
||||
bootstrap_ticket: BootstrapTicket,
|
||||
mut executor: E,
|
||||
) -> Result<(), DurableRunnerError> {
|
||||
@@ -162,7 +274,7 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
// Bind listener mode or resolve dial mode before processing commands. Dial
|
||||
// reconnects retain the same validated addresses so DNS cannot redirect a
|
||||
// retry after the trust decision.
|
||||
let endpoint = RunnerTransportEndpoint::new(&config.connect_url, &config.run_id)?;
|
||||
let mut endpoint = RunnerTransportEndpoint::new(&config.connect_url, &config.run_id)?;
|
||||
let started = Instant::now();
|
||||
let mut bootstrap_ticket = Some(bootstrap_ticket);
|
||||
let mut lease: Option<LeaseCredential> = None;
|
||||
@@ -287,8 +399,10 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
let mut sent_source_seq = state.acked_source_seq;
|
||||
|
||||
let mut lifecycle_after_reply = CommandLifecycle::Continue;
|
||||
let mut authority_rotation = None;
|
||||
let mut disconnected = false;
|
||||
for command in welcome.pending_commands {
|
||||
let next_authority = next_authority_config(&command, &config)?;
|
||||
let (result, lifecycle) =
|
||||
process_command(&mut state, &store, &config, &mut executor, &command)?;
|
||||
if let Some(durable_lifecycle) = lifecycle.durable_state() {
|
||||
@@ -333,6 +447,16 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
// then release the executor without observing later commands.
|
||||
break;
|
||||
}
|
||||
if next_authority.is_some() {
|
||||
authority_rotation = next_authority;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(next) = authority_rotation {
|
||||
apply_authority_rotation(&mut state, &store, &mut config, &mut endpoint, next)?;
|
||||
executor.rotate_authority(&config);
|
||||
disconnected_since = Some(Instant::now());
|
||||
continue;
|
||||
}
|
||||
if !disconnected {
|
||||
if let Err(error) = send_outbox(&mut transport, &state, &mut sent_source_seq) {
|
||||
@@ -425,6 +549,7 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
.map_err(|error| {
|
||||
DurableRunnerError::invalid(format!("command is malformed: {error}"))
|
||||
})?;
|
||||
let next_authority = next_authority_config(&command, &config)?;
|
||||
let (result, lifecycle) =
|
||||
process_command(&mut state, &store, &config, &mut executor, &command)?;
|
||||
if let Some(durable_lifecycle) = lifecycle.durable_state() {
|
||||
@@ -468,6 +593,18 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(next) = next_authority {
|
||||
apply_authority_rotation(
|
||||
&mut state,
|
||||
&store,
|
||||
&mut config,
|
||||
&mut endpoint,
|
||||
next,
|
||||
)?;
|
||||
executor.rotate_authority(&config);
|
||||
disconnected_since = Some(Instant::now());
|
||||
break;
|
||||
}
|
||||
if let Err(error) = send_outbox(&mut transport, &state, &mut sent_source_seq) {
|
||||
state.record_diagnostic(
|
||||
"outbox delivery failed; unacknowledged suffix remains durable",
|
||||
@@ -1018,6 +1155,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_run_attachment_rotates_only_the_run_authority() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"paperclip-runner-warm-authority-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&directory);
|
||||
let mut current = config(directory.clone());
|
||||
current.runner_digest = format!("sha256:{}", "a".repeat(64));
|
||||
let mut attach = command("run.attach");
|
||||
attach.payload = json!({
|
||||
"paperclipNextAuthority": {
|
||||
"identity": {
|
||||
"runnerInstanceId": current.runner_instance_id,
|
||||
"environmentLeaseId": current.environment_lease_id,
|
||||
"runId": "run_2",
|
||||
"normalizedSessionId": current.normalized_session_id,
|
||||
"turnId": "turn_2",
|
||||
"itemId": "item_2"
|
||||
},
|
||||
"connection": {
|
||||
"mode": "connect",
|
||||
"connectUrl": "ws://127.0.0.1:3001/path"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let next = next_authority_config(&attach, ¤t)
|
||||
.unwrap()
|
||||
.expect("attachment should carry a new authority");
|
||||
assert_eq!(next.run_id, "run_2");
|
||||
assert_eq!(next.connect_url, "ws://127.0.0.1:3001/path");
|
||||
|
||||
let store = DurableStateStore::new(&directory).unwrap();
|
||||
let (mut state, _) = store.load_or_create(¤t).unwrap();
|
||||
state.outbox.push(crate::durable::state::StoredOutboxEvent {
|
||||
source_seq: 1,
|
||||
priority: 0,
|
||||
event_type: "run.attached".to_owned(),
|
||||
byte_size: 1,
|
||||
envelope: json!({}),
|
||||
});
|
||||
let mut endpoint =
|
||||
RunnerTransportEndpoint::new(¤t.connect_url, ¤t.run_id).unwrap();
|
||||
apply_authority_rotation(&mut state, &store, &mut current, &mut endpoint, next).unwrap();
|
||||
|
||||
assert_eq!(state.run_id, "run_2");
|
||||
assert_eq!(state.next_source_seq, 1);
|
||||
assert!(state.outbox.is_empty());
|
||||
assert_eq!(current.run_id, "run_2");
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_lifecycle_is_durable_before_fallible_cleanup() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
|
||||
@@ -1670,6 +1670,10 @@ impl CommandExecutor for ManagedProviderCommandExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_authority(&mut self, config: &DurableRunnerConfig) {
|
||||
self.config = config.clone();
|
||||
}
|
||||
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.poll_provider()?;
|
||||
Ok(self
|
||||
|
||||
@@ -35,6 +35,14 @@ impl CommandExecutor for SelectedExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_authority(&mut self, config: &DurableRunnerConfig) {
|
||||
match self {
|
||||
Self::LocalFacade(executor) => executor.rotate_authority(config),
|
||||
Self::Acpx(executor) => executor.rotate_authority(config),
|
||||
Self::Managed(executor) => executor.rotate_authority(config),
|
||||
}
|
||||
}
|
||||
|
||||
fn acknowledge_events(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
match self {
|
||||
Self::LocalFacade(executor) => executor.acknowledge_events(count),
|
||||
@@ -163,6 +171,13 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
.map_or_else(|| Ok(Vec::new()), CommandExecutor::poll_events)
|
||||
}
|
||||
|
||||
fn rotate_authority(&mut self, config: &DurableRunnerConfig) {
|
||||
self.config = config.clone();
|
||||
if let Some(executor) = self.selected.as_mut() {
|
||||
executor.rotate_authority(config);
|
||||
}
|
||||
}
|
||||
|
||||
fn acknowledge_events(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
self.select_recovery()?;
|
||||
if let Some(executor) = self.selected.as_mut() {
|
||||
|
||||
@@ -1675,19 +1675,40 @@ impl CodexCommandExecutor {
|
||||
next_state.active_provider_result_fingerprint = None;
|
||||
next_state.active_provider_result_disposition = None;
|
||||
next_state.last_agent_message = None;
|
||||
if let Some(provider) = self.provider.as_mut() {
|
||||
let provider = self.provider.as_mut().ok_or_else(|| {
|
||||
DurableRunnerError::invalid("run.attach requires the restored Codex provider process")
|
||||
})?;
|
||||
let retained_provider = provider
|
||||
.attach_run_in_place(
|
||||
next_state.tool_bridge.authorized_tools().cloned(),
|
||||
next_state.completion_contract.as_ref().map(|contract| {
|
||||
(
|
||||
contract.revision.as_str(),
|
||||
contract.criterion_ids.as_slice(),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.map_err(|error| {
|
||||
DurableRunnerError::invalid(format!(
|
||||
"failed to retain Codex for warm run attachment: {error}"
|
||||
))
|
||||
})?;
|
||||
if !retained_provider {
|
||||
provider.shutdown().map_err(|error| {
|
||||
DurableRunnerError::invalid(format!(
|
||||
"failed to checkpoint Codex before attaching a new run: {error}"
|
||||
))
|
||||
})?;
|
||||
self.provider = None;
|
||||
}
|
||||
self.provider = None;
|
||||
next_state.pending_events.clear();
|
||||
// Persist the checkpoint as not-open before open_session resumes it for
|
||||
// the new authority. Otherwise recovery emits a second session.resumed
|
||||
// notice into the provider queue in addition to the command event.
|
||||
next_state.lifecycle = "prepared".to_owned();
|
||||
next_state.lifecycle = if retained_provider {
|
||||
"session_open".to_owned()
|
||||
} else {
|
||||
// The next provider command restores the same checkpointed session
|
||||
// with the rotated tool/completion authority.
|
||||
"prepared".to_owned()
|
||||
};
|
||||
self.persist_state(&next_state)?;
|
||||
self.state = Some(next_state);
|
||||
Ok(())
|
||||
@@ -3009,6 +3030,10 @@ impl CommandExecutor for CodexCommandExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_authority(&mut self, config: &DurableRunnerConfig) {
|
||||
self.event_identity = Some(ProviderEventIdentity::from_config(config));
|
||||
}
|
||||
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.poll_provider()?;
|
||||
Ok(self
|
||||
|
||||
@@ -939,7 +939,7 @@ class AuthorityConnection {
|
||||
|
||||
/** Authenticated, replay-safe PRP transport authority. Business operations are caller supplied. */
|
||||
export class DurablePrpControlPlane {
|
||||
readonly #identity: DurableRecoveryIdentity;
|
||||
#identity: DurableRecoveryIdentity;
|
||||
readonly #store: DurableCoreStore;
|
||||
#expectedRunnerVersion: string;
|
||||
#expectedRunnerDigest: string;
|
||||
@@ -1041,6 +1041,36 @@ export class DurablePrpControlPlane {
|
||||
).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically advances a settled reusable runner to a new run authority while
|
||||
* retaining its existing connection lease secret. The runner performs the
|
||||
* matching state transition only after acknowledging `run.attach`.
|
||||
*/
|
||||
rotateRunIdentity(identity: DurableRecoveryIdentity): void {
|
||||
if (
|
||||
!Object.values(identity).every(
|
||||
(value) => typeof value === "string" && stableIdPattern.test(value),
|
||||
) ||
|
||||
identity.runnerInstanceId !== this.#identity.runnerInstanceId ||
|
||||
identity.environmentLeaseId !== this.#identity.environmentLeaseId ||
|
||||
identity.normalizedSessionId !== this.#identity.normalizedSessionId ||
|
||||
identity.runId === this.#identity.runId ||
|
||||
this.#store.state.commands.some((command) => command.status === "pending")
|
||||
) {
|
||||
throw new Error("Durable PRP run identity rotation is invalid.");
|
||||
}
|
||||
this.disconnectActiveRunner();
|
||||
const leases = Object.fromEntries(
|
||||
Object.entries(this.#store.state.leases).map(([key, lease]) => [
|
||||
key,
|
||||
{ ...lease, identity: structuredClone(identity) },
|
||||
]),
|
||||
);
|
||||
Object.assign(this.#store.state, initialCoreState(identity), { leases });
|
||||
this.#identity = structuredClone(identity);
|
||||
this.#store.save();
|
||||
}
|
||||
|
||||
issueBootstrapTicket(ttlMs = 5_000): string {
|
||||
if (!Number.isInteger(ttlMs) || ttlMs < 1_000 || ttlMs > 60_000) {
|
||||
throw new Error("Durable PRP bootstrap TTL is invalid.");
|
||||
|
||||
@@ -1965,7 +1965,7 @@ it("steers the active provider turn through the durable PRP command path", async
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it("does not expose cross-run attachment before PRP authority can rotate atomically", async () => {
|
||||
it("rotates PRP authority in place for a warm cross-run attachment", async () => {
|
||||
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-warm-attach-"));
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
@@ -1978,22 +1978,36 @@ it("does not expose cross-run attachment before PRP authority can rotate atomica
|
||||
success: true,
|
||||
contentItems: [],
|
||||
}));
|
||||
const within = async <T>(label: string, promise: Promise<T>) =>
|
||||
await Promise.race([
|
||||
promise,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error(`${label} timeout`)), 5_000),
|
||||
),
|
||||
]);
|
||||
try {
|
||||
await bundle.transport.request("initialize", {});
|
||||
await bundle.transport.request("thread/start", {
|
||||
cwd: tmpdir(),
|
||||
dynamicTools: [
|
||||
{
|
||||
name: "get_task_context",
|
||||
description: "Read the active task.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
additionalProperties: false,
|
||||
await within("initialize", bundle.transport.request("initialize", {}));
|
||||
await within(
|
||||
"thread start",
|
||||
bundle.transport.request("thread/start", {
|
||||
cwd: tmpdir(),
|
||||
dynamicTools: [
|
||||
{
|
||||
name: "get_task_context",
|
||||
description: "Read the active task.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionContract: {
|
||||
revision: "sha256:warm-three-turn-contract",
|
||||
criterionIds: ["objective"],
|
||||
},
|
||||
],
|
||||
});
|
||||
}),
|
||||
);
|
||||
const runnerPid = bundle.evidence().runnerPid;
|
||||
const providerPid = bundle.evidence().codexPid;
|
||||
const notifications = bundle.transport
|
||||
@@ -2015,12 +2029,45 @@ it("does not expose cross-run attachment before PRP authority can rotate atomica
|
||||
}
|
||||
throw new Error(`${label} completion timeout`);
|
||||
};
|
||||
await bundle.transport.request("turn/start", {
|
||||
input: [{ type: "text", text: "first run" }],
|
||||
});
|
||||
await within(
|
||||
"first turn start",
|
||||
bundle.transport.request("turn/start", {
|
||||
input: [{ type: "text", text: "first run" }],
|
||||
}),
|
||||
);
|
||||
await waitForCompletion("first run");
|
||||
|
||||
expect(bundle.transport.attachRun).toBeUndefined();
|
||||
await within(
|
||||
"warm attach",
|
||||
bundle.transport.attachRun!({
|
||||
runId: "run-warm-second",
|
||||
turnId: "turn-warm-second",
|
||||
itemId: "item-warm-second",
|
||||
}),
|
||||
);
|
||||
await within(
|
||||
"second turn start",
|
||||
bundle.transport.request("turn/start", {
|
||||
input: [{ type: "text", text: "second run" }],
|
||||
}),
|
||||
);
|
||||
await waitForCompletion("second run");
|
||||
|
||||
await within(
|
||||
"second warm attach",
|
||||
bundle.transport.attachRun!({
|
||||
runId: "run-warm-third",
|
||||
turnId: "turn-warm-third",
|
||||
itemId: "item-warm-third",
|
||||
}),
|
||||
);
|
||||
await within(
|
||||
"third turn start",
|
||||
bundle.transport.request("turn/start", {
|
||||
input: [{ type: "text", text: "third run" }],
|
||||
}),
|
||||
);
|
||||
await waitForCompletion("third run");
|
||||
|
||||
expect(bundle.evidence()).toMatchObject({
|
||||
runnerPid,
|
||||
@@ -2033,6 +2080,99 @@ it("does not expose cross-run attachment before PRP authority can rotate atomica
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it("releases both PRP authorities when warm rotation activation fails", async () => {
|
||||
const stateDirectory = await mkdtemp(
|
||||
join(tmpdir(), "runnerd-warm-attach-activation-failure-"),
|
||||
);
|
||||
const server = createServer();
|
||||
const authorities = new Map<string, DurablePrpControlPlane>();
|
||||
const released: string[] = [];
|
||||
server.on("upgrade", (request, socket, head) => {
|
||||
const route = request.url ?? "";
|
||||
const authority = authorities.get(route);
|
||||
if (!authority) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
authority.handleUpgrade(request, socket, route, head);
|
||||
});
|
||||
await new Promise<void>((resolveListen) =>
|
||||
server.listen(0, "127.0.0.1", resolveListen),
|
||||
);
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
throw new Error("Expected warm activation failure test listener");
|
||||
}
|
||||
let registrationCount = 0;
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: fakeCodex,
|
||||
codexArgs: fakeCodexArgs(stateDirectory),
|
||||
stateDirectory,
|
||||
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 },
|
||||
controlPlaneRegistration: async (authority) => {
|
||||
registrationCount += 1;
|
||||
const route = `/runner-${registrationCount}`;
|
||||
authorities.set(route, authority);
|
||||
return {
|
||||
connectUrl: `ws://127.0.0.1:${address.port}${route}`,
|
||||
...(registrationCount === 1
|
||||
? {}
|
||||
: {
|
||||
activate: () => {
|
||||
throw new Error("rotation activation failed");
|
||||
},
|
||||
}),
|
||||
release: () => {
|
||||
released.push(route);
|
||||
if (authorities.get(route) === authority) authorities.delete(route);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
bundle.transport.setServerRequestHandler(async () => ({
|
||||
success: true,
|
||||
contentItems: [],
|
||||
}));
|
||||
let runnerPid: number | null = null;
|
||||
try {
|
||||
await bundle.transport.request("thread/start", {
|
||||
cwd: tmpdir(),
|
||||
dynamicTools: codexSemanticToolSpecs(),
|
||||
});
|
||||
runnerPid = bundle.evidence().runnerPid;
|
||||
|
||||
await expect(
|
||||
bundle.transport.attachRun!({
|
||||
runId: "run-warm-activation-failure",
|
||||
turnId: "turn-warm-activation-failure",
|
||||
itemId: "item-warm-activation-failure",
|
||||
}),
|
||||
).rejects.toThrow("rotation activation failed");
|
||||
expect(new Set(released)).toEqual(new Set(["/runner-1", "/runner-2"]));
|
||||
expect(authorities.size).toBe(0);
|
||||
await expect(bundle.transport.request("thread/read", {})).rejects.toThrow(
|
||||
"rotation activation failed",
|
||||
);
|
||||
} finally {
|
||||
await bundle.transport.close().catch(() => undefined);
|
||||
if (runnerPid) {
|
||||
try {
|
||||
process.kill(-runnerPid, "SIGKILL");
|
||||
} catch {
|
||||
// A successful durable close already stopped the runner process group.
|
||||
}
|
||||
}
|
||||
server.closeAllConnections();
|
||||
if (server.listening) {
|
||||
await new Promise<void>((resolveClose) =>
|
||||
server.close(() => resolveClose()),
|
||||
);
|
||||
}
|
||||
await rm(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it.each([
|
||||
{
|
||||
binding: "runner instance",
|
||||
|
||||
@@ -400,7 +400,7 @@ async function rotateExternalAuthorityEpoch(
|
||||
}
|
||||
|
||||
function rotatedRunAttachPayload(
|
||||
state: Record<string, unknown>,
|
||||
state: { commands?: unknown },
|
||||
desired: DurableRecoveryIdentity,
|
||||
authorizedTools: Record<string, unknown> | null,
|
||||
completionContract:
|
||||
@@ -418,7 +418,22 @@ function rotatedRunAttachPayload(
|
||||
);
|
||||
if (!seed)
|
||||
throw new Error("native_runner_authority_rotation_seed_unavailable");
|
||||
const payload = structuredClone(record(seed.payload));
|
||||
return retargetRunAttachPayload(
|
||||
record(seed.payload),
|
||||
desired,
|
||||
authorizedTools,
|
||||
completionContract,
|
||||
);
|
||||
}
|
||||
|
||||
function retargetRunAttachPayload(
|
||||
seedPayload: Record<string, unknown>,
|
||||
desired: DurableRecoveryIdentity,
|
||||
authorizedTools: Record<string, unknown> | null,
|
||||
completionContract:
|
||||
{ revision: string; criterionIds: readonly string[] } | undefined,
|
||||
): Record<string, unknown> {
|
||||
const payload = structuredClone(seedPayload);
|
||||
const provider = record(payload.provider);
|
||||
if (provider.kind === "acpx" || provider.provider === "acpx") {
|
||||
provider.runId = desired.runId;
|
||||
@@ -958,7 +973,10 @@ export interface CapabilityRunnerdCodexTransportOptions {
|
||||
itemId: string;
|
||||
};
|
||||
/** Registers the run-bound PRP authority on Paperclip's shared HTTP server. */
|
||||
controlPlaneRegistration?: (authority: DurablePrpControlPlane) => Promise<{
|
||||
controlPlaneRegistration?: (
|
||||
authority: DurablePrpControlPlane,
|
||||
identity?: DurableRecoveryIdentity,
|
||||
) => Promise<{
|
||||
connectUrl?: string;
|
||||
connection?: RunnerProcessConnection;
|
||||
activate?: () => Promise<void> | void;
|
||||
@@ -1942,6 +1960,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
#expectedProviderTurnId: string | null = null;
|
||||
#durableTurnId = "";
|
||||
#authorizedTools: Record<string, unknown> | null = null;
|
||||
#runAttachTemplate: Record<string, unknown> | null = null;
|
||||
#closed = false;
|
||||
#closePromise: Promise<void> | null = null;
|
||||
#failure: Error | null = null;
|
||||
@@ -2216,6 +2235,94 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
this.#handler = handler;
|
||||
}
|
||||
|
||||
async attachRun(input: {
|
||||
runId: string;
|
||||
turnId: string;
|
||||
itemId: string;
|
||||
}): Promise<void> {
|
||||
const core = this.#core;
|
||||
if (!core || !this.#startupComplete) {
|
||||
throw new Error("native_runner_prp_run_rotation_unavailable");
|
||||
}
|
||||
const prior = core.store.state.identity;
|
||||
const desired: DurableRecoveryIdentity = {
|
||||
...prior,
|
||||
runId: input.runId,
|
||||
turnId: input.turnId,
|
||||
itemId: input.itemId,
|
||||
};
|
||||
const registration = this.options.controlPlaneRegistration
|
||||
? await this.options.controlPlaneRegistration(core, desired)
|
||||
: null;
|
||||
const connection: RunnerProcessConnection =
|
||||
registration?.connection ??
|
||||
(registration?.connectUrl
|
||||
? { mode: "connect", connectUrl: registration.connectUrl }
|
||||
: { mode: "connect", connectUrl: core.connectUrl });
|
||||
const commandId = `command_attach_${createHash("sha256")
|
||||
.update(`${prior.runId}:${desired.runId}:${desired.turnId}`)
|
||||
.digest("hex")
|
||||
.slice(0, 32)}`;
|
||||
const runAttachTemplate = this.#runAttachTemplate
|
||||
? retargetRunAttachPayload(
|
||||
this.#runAttachTemplate,
|
||||
desired,
|
||||
this.#authorizedTools,
|
||||
this.options.resumeCompletionContract,
|
||||
)
|
||||
: rotatedRunAttachPayload(
|
||||
core.store.state,
|
||||
desired,
|
||||
this.#authorizedTools,
|
||||
this.options.resumeCompletionContract,
|
||||
);
|
||||
this.#runAttachTemplate = structuredClone(runAttachTemplate);
|
||||
const payload = {
|
||||
...runAttachTemplate,
|
||||
paperclipNextAuthority: { identity: desired, connection },
|
||||
};
|
||||
core.queueCommand("run.attach", payload, commandId, true);
|
||||
await this.#waitCommand("run.attach", commandId);
|
||||
const attached = core.store.state.commands.find(
|
||||
(command) => command.commandId === commandId,
|
||||
);
|
||||
if (attached?.status !== "completed") {
|
||||
await Promise.resolve(registration?.release()).catch(() => undefined);
|
||||
throw new Error("native_runner_prp_run_rotation_failed");
|
||||
}
|
||||
|
||||
const previousRelease = this.#controlPlaneRelease;
|
||||
core.rotateRunIdentity(desired);
|
||||
this.#eventIndex = 0;
|
||||
this.#durableTurnId = desired.turnId;
|
||||
this.#controlPlaneRelease = registration?.release ?? null;
|
||||
let previousReleased = false;
|
||||
try {
|
||||
await registration?.activate?.();
|
||||
if (registration?.failure) {
|
||||
void registration.failure.catch((error: unknown) => {
|
||||
this.#failTransport(
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
});
|
||||
}
|
||||
await previousRelease?.();
|
||||
previousReleased = true;
|
||||
await this.#awaitRegistrationReady(registration?.ready);
|
||||
} catch (error) {
|
||||
const failure = error instanceof Error ? error : new Error(String(error));
|
||||
this.#controlPlaneRelease = null;
|
||||
await Promise.allSettled([
|
||||
Promise.resolve().then(() => registration?.release()),
|
||||
...(previousReleased
|
||||
? []
|
||||
: [Promise.resolve().then(() => previousRelease?.())]),
|
||||
]);
|
||||
this.#failTransport(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveRuntimeRequest(input: {
|
||||
requestId: string;
|
||||
turnId: string;
|
||||
@@ -3298,15 +3405,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
});
|
||||
this.#core = core;
|
||||
if (rotatedAuthority) {
|
||||
core.queueCommand(
|
||||
"run.attach",
|
||||
rotatedRunAttachPayload(
|
||||
controlPlaneState,
|
||||
desiredIdentity,
|
||||
this.#authorizedTools,
|
||||
this.options.resumeCompletionContract,
|
||||
),
|
||||
const runAttachTemplate = rotatedRunAttachPayload(
|
||||
controlPlaneState,
|
||||
desiredIdentity,
|
||||
this.#authorizedTools,
|
||||
this.options.resumeCompletionContract,
|
||||
);
|
||||
this.#runAttachTemplate = structuredClone(runAttachTemplate);
|
||||
core.queueCommand("run.attach", runAttachTemplate);
|
||||
}
|
||||
const committedEvents = core.store.state.committedEvents;
|
||||
const runAttachment = recoveredRunAttachment(core.store.state);
|
||||
|
||||
@@ -1240,6 +1240,8 @@ describe("Daytona sandbox provider plugin", () => {
|
||||
providerLeaseId: "sandbox-reuse",
|
||||
metadata: {
|
||||
resumedLease: true,
|
||||
resumedFromState: "stopped",
|
||||
sandboxState: "started",
|
||||
workspaceSentinel: {
|
||||
result: "matched",
|
||||
token: "sentinel-token",
|
||||
@@ -4060,6 +4062,35 @@ describe("daytona native file-sync hooks", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a deleted sandbox during syncOut with a stable unrecoverable code", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
mockGet.mockRejectedValue(
|
||||
new MockDaytonaNotFoundError("provider detail must not escape"),
|
||||
);
|
||||
|
||||
await expect(
|
||||
plugin.definition.onEnvironmentSyncOut?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: true },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: "sync-op-missing-sandbox",
|
||||
files: [
|
||||
{
|
||||
sourcePath: `${REMOTE_DIR}/out/result.txt`,
|
||||
targetPath: path.join(hostDir, "result.txt"),
|
||||
kind: "file",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow("daytona_sandbox_not_found");
|
||||
});
|
||||
|
||||
it("syncOut snapshot guard re-checks the resolved source is a non-symlink regular file immediately before copying (validation→copy TOCTOU)", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const sandbox = createMockSandbox();
|
||||
|
||||
@@ -619,6 +619,8 @@ function leaseMetadata(input: {
|
||||
shellCommand: "bash" | "sh";
|
||||
remoteCwd: string;
|
||||
resumedLease: boolean;
|
||||
resumedFromState?: string | null;
|
||||
sandboxState?: string | null;
|
||||
workspaceSentinel?: WorkspaceSentinelResult;
|
||||
}) {
|
||||
return {
|
||||
@@ -626,7 +628,7 @@ function leaseMetadata(input: {
|
||||
shellCommand: input.shellCommand,
|
||||
sandboxId: input.sandbox.id,
|
||||
sandboxName: input.sandbox.name,
|
||||
sandboxState: input.sandbox.state ?? null,
|
||||
sandboxState: input.sandboxState ?? input.sandbox.state ?? null,
|
||||
image: input.config.image,
|
||||
snapshot: input.config.snapshot,
|
||||
target: input.sandbox.target,
|
||||
@@ -637,6 +639,9 @@ function leaseMetadata(input: {
|
||||
...(input.config.archiveOnRelease ? { archiveOnRelease: true } : {}),
|
||||
remoteCwd: input.remoteCwd,
|
||||
resumedLease: input.resumedLease,
|
||||
...(input.resumedLease
|
||||
? { resumedFromState: input.resumedFromState ?? null }
|
||||
: {}),
|
||||
// Record the resources Paperclip attempted to request so future diagnosis
|
||||
// can compare requested allocation against what Daytona provisioned.
|
||||
...(input.config.cpu != null ? { cpu: input.config.cpu } : {}),
|
||||
@@ -2187,61 +2192,72 @@ const plugin = definePlugin({
|
||||
return { providerLeaseId: null, metadata: { expired: true } };
|
||||
}
|
||||
|
||||
// A stopped sandbox loses its session shell, so the stored session id is
|
||||
// stale after a real restart. Clear the id only when the sandbox is not
|
||||
// already running, and clear it before the restart. A stopped sandbox has
|
||||
// no live session, so the clear drops a dead id and a later command opens
|
||||
// a fresh session. A running sandbox keeps its live session, so the resume
|
||||
// leaves the id in place; a concurrent command still finds it and teardown
|
||||
// deletes one session. An unconditional clear would drop the id of a live
|
||||
// session and leak its shell until sandbox reaping.
|
||||
if (sandbox.state !== "started") {
|
||||
sandboxHandleSessionStore.clear(scope);
|
||||
// A stopped sandbox loses its pseudo-terminals, so a stored duplex channel
|
||||
// is dead after a real restart. Close and drop every channel on this lease
|
||||
// before the restart, so no stale channel id survives the resume.
|
||||
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
||||
}
|
||||
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
try {
|
||||
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
||||
// C3: a resumed lease must clear the workspace sentinel before it is
|
||||
// trusted, even when the handle came from the cache. On any non-match we
|
||||
// evict the cached handle and expire the lease so a stale/foreign sandbox
|
||||
// is never reused on the subsequent (sentinel-skipping) exec path.
|
||||
const workspaceSentinel = await verifyWorkspaceSentinel({
|
||||
sandbox,
|
||||
remoteCwd,
|
||||
leaseMetadata: params.leaseMetadata,
|
||||
timeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
||||
});
|
||||
if (workspaceSentinel.result !== "matched") {
|
||||
evictSandboxHandle(scope);
|
||||
return { providerLeaseId: null, metadata: { expired: true, workspaceSentinel } };
|
||||
}
|
||||
const shellCommand = await detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
sandboxHandleLeaseAdmissionStates.open(scope);
|
||||
return {
|
||||
providerLeaseId: sandbox.id,
|
||||
metadata: leaseMetadata({
|
||||
config,
|
||||
sandbox,
|
||||
shellCommand,
|
||||
remoteCwd,
|
||||
resumedLease: true,
|
||||
workspaceSentinel,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
evictSandboxHandle(scope);
|
||||
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
|
||||
// lost. Preserve the exact resource and let the host retry its recorded
|
||||
// lease; replacement is permitted only after an explicit not-found or
|
||||
// an immutable workspace identity mismatch.
|
||||
throw error;
|
||||
}
|
||||
}, { allowClosed: true });
|
||||
// A stopped sandbox loses its session shell, so the stored session id is
|
||||
// stale after a real restart. Clear the id only when the sandbox is not
|
||||
// already running, and clear it before the restart. A stopped sandbox has
|
||||
// no live session, so the clear drops a dead id and a later command opens
|
||||
// a fresh session. A running sandbox keeps its live session, so the resume
|
||||
// leaves the id in place; a concurrent command still finds it and teardown
|
||||
// deletes one session. An unconditional clear would drop the id of a live
|
||||
// session and leak its shell until sandbox reaping.
|
||||
if (sandbox.state !== "started") {
|
||||
sandboxHandleSessionStore.clear(scope);
|
||||
// A stopped sandbox loses its pseudo-terminals, so a stored duplex channel
|
||||
// is dead after a real restart. Close and drop every channel on this lease
|
||||
// before the restart, so no stale channel id survives the resume.
|
||||
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
||||
}
|
||||
const resumedFromState = sandbox.state ?? null;
|
||||
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
try {
|
||||
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
||||
// C3: a resumed lease must clear the workspace sentinel before it is
|
||||
// trusted, even when the handle came from the cache. On any non-match we
|
||||
// evict the cached handle and expire the lease so a stale/foreign sandbox
|
||||
// is never reused on the subsequent (sentinel-skipping) exec path.
|
||||
const workspaceSentinel = await verifyWorkspaceSentinel({
|
||||
sandbox,
|
||||
remoteCwd,
|
||||
leaseMetadata: params.leaseMetadata,
|
||||
timeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
||||
});
|
||||
if (workspaceSentinel.result !== "matched") {
|
||||
evictSandboxHandle(scope);
|
||||
return {
|
||||
providerLeaseId: null,
|
||||
metadata: { expired: true, workspaceSentinel },
|
||||
};
|
||||
}
|
||||
const shellCommand = await detectSandboxShellCommand(
|
||||
sandbox,
|
||||
toTimeoutSeconds(config.timeoutMs),
|
||||
);
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
sandboxHandleLeaseAdmissionStates.open(scope);
|
||||
return {
|
||||
providerLeaseId: sandbox.id,
|
||||
metadata: leaseMetadata({
|
||||
config,
|
||||
sandbox,
|
||||
shellCommand,
|
||||
remoteCwd,
|
||||
resumedLease: true,
|
||||
resumedFromState,
|
||||
sandboxState: "started",
|
||||
workspaceSentinel,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
evictSandboxHandle(scope);
|
||||
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
|
||||
// lost. Preserve the exact resource and let the host retry its recorded
|
||||
// lease; replacement is permitted only after an explicit not-found or
|
||||
// an immutable workspace identity mismatch.
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
{ allowClosed: true },
|
||||
);
|
||||
},
|
||||
|
||||
async onEnvironmentReleaseLease(
|
||||
@@ -2828,18 +2844,28 @@ const plugin = definePlugin({
|
||||
providerLeaseId: params.lease.providerLeaseId,
|
||||
config,
|
||||
};
|
||||
return await withSandboxActivityGate(scope, async () => {
|
||||
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
||||
await ensureSandboxStarted(sandbox, timeoutSeconds);
|
||||
const result = await performSyncOut({
|
||||
sandbox,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutSeconds,
|
||||
try {
|
||||
return await withSandboxActivityGate(scope, async () => {
|
||||
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
||||
await ensureSandboxStarted(sandbox, timeoutSeconds);
|
||||
const result = await performSyncOut({
|
||||
sandbox,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutSeconds,
|
||||
});
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
return result;
|
||||
});
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
return result;
|
||||
});
|
||||
} catch (error) {
|
||||
// A deleted Daytona sandbox is the one provider failure that proves its
|
||||
// unexported workspace bytes no longer exist. Convert the SDK class to a
|
||||
// stable cross-worker message; every other error remains retryable.
|
||||
if (error instanceof DaytonaNotFoundError) {
|
||||
throw new Error("daytona_sandbox_not_found");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
// Open one live login pseudo-terminal. Resolve the cached sandbox by the
|
||||
|
||||
Reference in new issue
Block a user