mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 10:40:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native execution must retain its admitted model and execution authority during recovery. > - A sandbox provider can reject Runner endpoint acquisition before the Runner gets a credential. > - The old error path loses the structured HTTP status and leaves that startup failure ambiguous. > - A zero counter in an old checkpoint cannot prove that no credential was issued. > - This pull request adds a versioned producer proof and carries closed provider status through the existing RPC. > - A proved transient startup failure uses the existing retry budget. A terminal proved-unused run can settle its accounting. ## Linked Issues or Issue Description Refs #18018 and #18934. Those changes restore existing checkpoints and ready retained environments. This change covers endpoint acquisition before Runner dispatch. A search of related public PRs found no duplicate implementation. **What happened?** A provider HTTP 502 during Runner endpoint acquisition becomes an untyped worker error. Native recovery treats it as ambiguous and stops without retrying. The run's native usage receipt also stays pending after startup ends without model work. **Expected behavior** Retry a structured transient endpoint failure only when the complete current controller checkpoint proves that this exact run never issued a Runner credential. Preserve authentication, configuration, Stop, ownership and provider-progress gates. Settle zero usage only under the existing terminal accounting owner. **Steps to reproduce** 1. Use the controlled endpoint in the Daytona ingress integration test to return HTTP 502. 2. Register the actual native Runner driver and persist its bootstrap journal through the encrypted checkpoint writer. 3. Observe the old terminal ambiguous disposition instead of bounded startup recovery. **Paperclip version or commit** Reproduced on the pre-change master source. The original regression used the production native driver, a real HTTP fault, a real durable control plane and local Postgres. The new contract additionally tests the pinned Daytona SDK and real worker RPC. ## What Changed - The controller owns a v2 persisted state with retained origin and credential history. Current readers still accept v1. Older writers reject v2. Restore and checkpoint decoding do not add missing history. - The proof validates the complete bootstrap journal, all six identity fields and every delivery, credential and progress control. The server rechecks its fingerprint under the current controller claim before retry or accounting changes. - Daytona and the SDK carry a closed acquisition phase and HTTP status through the existing ingress RPC. Both public error wrappers omit response bodies and causes, including Pino cause serialization. - Only structured HTTP 429 or 5xx ingress failures can use the existing three-attempt startup budget. HTTP 401/403, configuration and unknown errors do not gain retry authority. - A terminal proved-unused run wakes existing accounting and records zero provider work. It does not create a semantic result, prove physical termination or release an unknown process/workspace hold. - The normal automatic second attempt rechecks its exact claim, frozen execution and matching complete local/encrypted journal before admitting absent remote Runner state. It keeps the original pending bootstrap command IDs. A proved unused Codex home can rematerialize sealed skills. Full raw local state is checked before streaming-event or policy projection. - Normal saved-state readers and the existing E2E journal evidence matcher accept the closed v1/v2 set. The separate legacy no-launch witness is unchanged. Technical docs describe the contracts. ## Verification Current head: `cd38f70409cdb8664e14bfbf4efa208f468a0419` (final delta adds only fixture artifact preparation). Production files are unchanged from the independently reviewed `93c8a33520` source. Full repository typecheck and build passed at `96417acb58`; the affected server typecheck also passes after the final two-line fixture delta. Focused protocol, raw-proof, real retry, SDK and RPC acceptance pass on this source. Earlier broad suite counts are listed with their limits below: - Durable Runner protocol: 187 tests. - Native executor, driver, startup/accounting and redaction: 1,211 tests, including real Postgres and encrypted checkpoint persistence. - Normal saved-state restore/projection compatibility: 21 focused cases. - SDK: 209 tests. - Standalone Daytona: 544 tests; 8 opt-in live tests skipped. - Explicit standalone `pnpm -C packages/plugins/sandbox-providers/daytona exec vitest run --config vitest.sdk-ingress.config.ts`: 6 cases with real pinned SDK 0.203.0 and worker RPC ingress acceptance. These include lookup 502/401/403/400, private-preview 502 after successful lookup/refresh, missing credentials and private-response exclusion. - E2E journal evidence: 4 cases across both supported formats, with wrong ownership, missing stimulus and unknown-schema controls. - The exact historical controller source rejects a new v2 checkpoint at decode and restore. A v1 control is accepted. This verifies the downgrade fence with the actual older parser. - Startup controls cover issued and pruned credentials, old/truncated journals, provider progress, exhausted retry accounting, and checkpoint/Stop/controller-claim races. Race cases retain the current execution and pending usage. - New exact admission controls: 19 cases through encrypted persistence and cold restore. They cover current/stale/expired claims, Stop, pause, model/trust/account changes, prior progress, issued/pruned credentials, adopted/old/truncated state, local/canonical fingerprint mismatch, hidden delivery, unsupported work and company scope. Two additional red/green cases prove that raw local stream progress and missing event policy are rejected before lossy checkpoint projection. No case mutates run, claim, result or accounting state. - Actual native executor, scheduler and Rust Runner retry: 2 cases. Codex uses its fake app server. OpenCode uses the real proxy and fake OpenCode HTTP server with the frozen DeepSeek model and allow permission configuration. Each path launches no Runner on attempt 1, starts one Runner and provider on attempt 2, reuses both original command IDs, commits one accepted result, validates the persisted local workspace, records nonzero synthetic native usage and settles accounting once. No zero-work accounting flag survives. The controlled SDK and protocol tests use local source, isolated PostgreSQL, a private HTTPS preview and fake provider servers on macOS arm64 with Node 24.22.2. They create no hosted sandbox and make no model call. The root workspace intentionally omits standalone provider dependencies; the explicit SDK target fails if its pinned dependency is absent and has no conditional skip. They do not qualify hosted rollout or repair an old unmarked checkpoint. The first full local typecheck found missing checkout SDK links from an install with scripts disabled; the repository link helper repaired that setup. Current-head Linux CI typecheck and build pass. Independent final review checked 12 source scopes and six raw-proof controls with no remaining finding. Fresh Greptile review is 5/5 with no unresolved thread. The full Runner CI suite found two older control-peer test doubles missing the new proof method. Both now return no proof, with all 27 permission, ordering and cancellation assertions retained and passing. The new Cargo-dependent native retry suite uses the existing Rust-cached CI lane. All 39 lane coverage controls pass and prove complete, duplicate-free suite coverage. The first full test run stopped at an admitted chat Retry polling failure. CI also found a stale retained-allocation fixture, now repaired on master by #18984, and a canceled runner job. A real SDK suite initially relied on a dependency absent from the root workspace; the explicit standalone target now owns that acceptance. The separate Product E2E support run had 12 failures in four untouched files. All 12 reproduce on the original clean base with independent dependencies, compiled base source and verified workspace resolution. These concern workflow expectations, cleanup timeout arguments, a profile snapshot and operating receipts. They are not passing acceptance. The later full local repository test command stopped at a 15-second timeout in the unchanged GitHub pre-allocation retry `controller` case. That exact case passed in isolation with unchanged assertions. The broad Runner run initially omitted `test:typescript:prep` and lacked debug fake-provider binaries. Required preparation then passed 370 + 44 package contract cases (11 skipped); the prepared full package run reported 4,932 passed, 9 failed and 13 skipped. All failed families then passed with unchanged assertions in isolation: 8 ACPX controller tests and 2 credential controls. The paired original-base ACPX control also passed. The full-run failures remain recorded; they are not passing full-suite evidence. The first Rust-cached native CI run found a missing generated OpenCode proxy in a fresh checkout. The fixture now runs the existing verified provider-entrypoint builder. Removing the generated proxy reproduces the exact ENOENT before the fix; both real retry cases pass after the fix from the same absent-artifact state. All current-head CI gates pass, including the aggregate verification check. Linux native CI passes all 10 suites: 177 tests pass and 14 opt-in cases skip. Both real provider retry cases pass. The full Runner package passes 297 suites and 4,950 tests, with 1 suite and 10 tests skipped. The CLI workspace groups pass 4,762 and 286 tests. The first CI attempt had Runner shutdowns in the Runner package, Canary and three general server jobs. One unchanged CLI shard also hit child-server startup and dense ZIP deadlines. Both CLI files passed unchanged in isolation: 18 tests. One bounded rerun of unsuccessful jobs and their dependents passed. The original failures remain recorded. ## Risks - Older controllers reject newly written v2 state on downgrade. Current controllers retain v1 restore support, but old or unmarked state cannot gain this new proof. - An older plugin that omits structured ingress evidence remains held. The server and provider must use the new producer contract for this recovery path. The Docker `cloud` target builds the SDK, server/Runner and standalone Daytona producer from one source tree. The default `production` target does not build the standalone producer. Hosted rollout must confirm the new image and active image-owned plugin worker; a registry version alone does not prove its source. An npm-installed producer needs an explicit matching artifact upgrade. - This prevents future proved startup failures. It does not release historical accounting based on an old checkpoint, change retry budgets, replace a model or weaken sandbox isolation. - Zero model usage is separate from process termination, saved files and resource release. Those owners keep their existing gates. ## Model Used OpenAI Codex with tool use and code execution. This runtime does not expose the exact backend model ID or context window to the agent. Read-only independent agents reviewed checkpoint compatibility and SDK/RPC error boundaries. ## 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 (affected suites; full local run limits are recorded above) - [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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
248 lines
14 KiB
TypeScript
248 lines
14 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
|
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
|
|
import pino from "pino";
|
|
import { environmentRunnerIngressErrorData, JsonRpcCallError, PluginEnvironmentRunnerIngressError } from "@paperclipai/plugin-sdk";
|
|
import { NativeRunnerIngressAcquisitionError, prepareNativeRemoteRunner, createNativeRunnerExecutionDriver } from "./native-runner-execution-driver.js";
|
|
|
|
const transport = vi.hoisted(() => ({
|
|
register: vi.fn(),
|
|
connect: vi.fn(),
|
|
checkpoint: vi.fn(),
|
|
checkpointRegistration: vi.fn(),
|
|
}));
|
|
vi.mock("../../realtime/runner-prp-ws.js", () => ({ registerRunnerPrpAuthority: transport.register }));
|
|
vi.mock("../../realtime/runner-prp-outbound.js", () => ({ connectRunnerPrpIngress: transport.connect }));
|
|
vi.mock("./native-runner-checkpoint.js", () => ({ nativeRunnerCheckpointRegistration: transport.checkpointRegistration }));
|
|
|
|
const binding = { companyId: "company", issueId: "issue", agentId: "agent", runId: "run-a" };
|
|
const authority = {} as Parameters<NonNullable<ReturnType<typeof createNativeRunnerExecutionDriver>["controlPlaneRegistration"]>>[0];
|
|
const ssh = { kind: "remote", transport: "ssh", remoteCwd: "/workspace", spec: {} } as AdapterExecutionTarget;
|
|
const sandbox = (ingress = true): AdapterExecutionTarget => ({
|
|
kind: "remote", transport: "sandbox", remoteCwd: "/workspace", leaseId: "lease",
|
|
effectiveCapabilities: { runnerWebSocketIngress: ingress },
|
|
} as AdapterExecutionTarget);
|
|
|
|
function endpoint(): RunnerIngressEndpoint {
|
|
return {
|
|
kind: "authenticated_websocket", websocketUrl: "wss://sandbox.example/runner",
|
|
secretHeaders: [{ name: "Authorization", value: "test-ingress-secret" }], generation: "1",
|
|
refresh: vi.fn(), close: vi.fn(async () => {}),
|
|
};
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
transport.register.mockResolvedValue({ connectUrl: "ws://127.0.0.1/core", release: vi.fn() });
|
|
transport.connect.mockReturnValue({ ready: Promise.resolve(), close: vi.fn(async () => {}) });
|
|
transport.checkpointRegistration.mockReturnValue(transport.checkpoint);
|
|
transport.checkpoint.mockResolvedValue(undefined);
|
|
});
|
|
|
|
describe("shared Runner execution driver", () => {
|
|
it.each(["ingress", "preparation", "unknown"])("limits ingress evidence and public error serialization at %s", async phase => {
|
|
const failure = { phase: "private_preview", httpStatus: 502 } as const;
|
|
const raw = new JsonRpcCallError({ code: -32000, message: "fixture-private-provider-response",
|
|
data: phase === "unknown" ? undefined : environmentRunnerIngressErrorData(new PluginEnvironmentRunnerIngressError(failure)) });
|
|
const acquire = vi.fn(async () => { throw raw; });
|
|
const driver = createNativeRunnerExecutionDriver({ binding, runnerIngressAuthorized: true,
|
|
target: { ...sandbox(), getRunnerIngressEndpoint: acquire } as AdapterExecutionTarget,
|
|
prepareRemote: async () => { if (phase === "preparation") throw raw; },
|
|
});
|
|
const error = await driver.controlPlaneRegistration!(authority).catch(error => error);
|
|
if (phase === "ingress") {
|
|
expect(error).toBeInstanceOf(NativeRunnerIngressAcquisitionError);
|
|
expect(error.failure).toEqual(failure);
|
|
expect(JSON.stringify(pino.stdSerializers.err(error))).not.toContain("fixture-private");
|
|
} else expect(error).toBe(raw);
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
});
|
|
it("installs both staged checkpoint writers under the business lease without acquiring endpoints", async () => {
|
|
const prepare = vi.fn();
|
|
const persistence = { db: {} as never, bootId: "boot-c", authorityRunId: "run-c" };
|
|
const driver = createNativeRunnerExecutionDriver({ target: sandbox(), binding: { ...binding, runId: "run-c" },
|
|
controllerPersistence: persistence, prepareRemote: prepare });
|
|
const sourceIdentity = { runnerInstanceId: "runner", environmentLeaseId: "lease", normalizedSessionId: "session",
|
|
runId: "run-a", turnId: "turn-a", itemId: "item-a" };
|
|
const targetIdentity = { ...sourceIdentity, runId: "run-c", turnId: "turn-c", itemId: "item-c" };
|
|
await driver.onStagedRunAttachment!(authority, { sourceIdentity, targetIdentity, templateDigest: `sha256:${"a".repeat(64)}` });
|
|
expect(transport.checkpointRegistration).toHaveBeenCalledExactlyOnceWith({ ...persistence,
|
|
binding: { companyId: binding.companyId, issueId: binding.issueId, runId: "run-c" } });
|
|
expect(transport.checkpoint.mock.calls).toEqual([[authority, sourceIdentity], [authority, targetIdentity]]);
|
|
expect(prepare).not.toHaveBeenCalled();
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("installs the target writer first when restoring an already persisted stage", async () => {
|
|
const sourceIdentity = { runnerInstanceId: "runner", environmentLeaseId: "lease", normalizedSessionId: "session",
|
|
runId: "run-a", turnId: "turn-a", itemId: "item-a" };
|
|
const targetIdentity = { ...sourceIdentity, runId: "run-c", turnId: "turn-c", itemId: "item-c" };
|
|
const restored = { store: { state: { stagedRunAttachment: { sourceIdentity, targetIdentity } } } } as unknown as typeof authority;
|
|
const driver = createNativeRunnerExecutionDriver({ target: sandbox(), binding: { ...binding, runId: "run-c" },
|
|
controllerPersistence: { db: {} as never, bootId: "boot-c", authorityRunId: "run-c" } });
|
|
await driver.onStagedRunAttachment!(restored, { sourceIdentity, targetIdentity, templateDigest: `sha256:${"a".repeat(64)}` });
|
|
expect(transport.checkpoint.mock.calls).toEqual([[restored, targetIdentity], [restored, sourceIdentity]]);
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps local execution on the registered loopback route", async () => {
|
|
const driver = createNativeRunnerExecutionDriver({ target: { kind: "local" }, binding });
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
expect(connection.connectUrl).toBe("ws://127.0.0.1/core");
|
|
expect(connection.startupFailureCode).toBe("runner_local_connect_failed");
|
|
expect(transport.register).toHaveBeenCalledWith({ ...binding, authority });
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([ssh, sandbox(false)])("prepares $transport before launching an outbound Runner", async target => {
|
|
const prepare = vi.fn(async () => {});
|
|
const launch = vi.fn();
|
|
const read = vi.fn();
|
|
const checkpoint = vi.fn();
|
|
const mapCaBundle = vi.fn(async () => "/remote/ca.pem");
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target, binding, runnerPublicUrl: "wss://core.example", prepareRemote: prepare,
|
|
process: { runnerProcessLauncher: launch, readRunnerState: read }, checkpoint, mapCaBundle,
|
|
});
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
expect(prepare).toHaveBeenCalledWith("dial_wss");
|
|
expect(connection.connection).toEqual({ mode: "connect", connectUrl: "wss://core.example/api/runner/v1/connect/run-a" });
|
|
expect(connection.checkpoint).toBe(checkpoint);
|
|
expect(driver.runnerProcessLauncher).toBe(launch);
|
|
expect(driver.readRunnerState).toBe(read);
|
|
expect(launch).not.toHaveBeenCalled();
|
|
expect(mapCaBundle).not.toHaveBeenCalled();
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
expect(prepare.mock.invocationCallOrder[0]).toBeLessThan(transport.register.mock.invocationCallOrder[0]);
|
|
});
|
|
|
|
it("rejects invalid outbound connectivity before staging resources", async () => {
|
|
const prepare = vi.fn();
|
|
const driver = createNativeRunnerExecutionDriver({ target: ssh, binding, prepareRemote: prepare });
|
|
await expect(driver.controlPlaneRegistration!(authority)).rejects.toThrow("runner_transport_ineligible");
|
|
expect(prepare).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a missing CA file before preparing the remote environment", async () => {
|
|
const prepare = vi.fn();
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: ssh, binding, prepareRemote: prepare, runnerPublicUrl: "wss://core.example",
|
|
runnerCaBundlePath: "/nonexistent/paperclip-runner-test-ca.pem",
|
|
});
|
|
await expect(driver.controlPlaneRegistration!(authority)).rejects.toThrow("runner_direct_wss_failed");
|
|
expect(prepare).not.toHaveBeenCalled();
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("binds an outbound CA to the process owner's filesystem", async () => {
|
|
const mapCaBundle = vi.fn(async () => "/remote/ca.pem");
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: ssh, binding, prepareRemote: async () => {}, runnerPublicUrl: "wss://core.example",
|
|
runnerCaBundlePath: process.execPath, mapCaBundle,
|
|
});
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
expect(mapCaBundle).toHaveBeenCalledWith(process.execPath);
|
|
expect(connection.connection).toEqual(expect.objectContaining({ caBundlePath: "/remote/ca.pem" }));
|
|
expect(mapCaBundle.mock.invocationCallOrder[0]).toBeLessThan(transport.register.mock.invocationCallOrder[0]);
|
|
});
|
|
|
|
it("does not register an authority route when CA staging fails", async () => {
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: ssh, binding, prepareRemote: async () => {}, runnerPublicUrl: "wss://core.example",
|
|
runnerCaBundlePath: process.execPath,
|
|
mapCaBundle: async () => { throw new Error("ca_copy_failed"); },
|
|
});
|
|
await expect(driver.controlPlaneRegistration!(authority)).rejects.toThrow("ca_copy_failed");
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("stages before acquiring ingress and waits for process dispatch before connecting", async () => {
|
|
const ingress = endpoint();
|
|
const acquire = vi.fn(async () => ingress);
|
|
const prepare = vi.fn(async () => {});
|
|
let started!: () => void;
|
|
const processStarted = new Promise<void>(resolve => { started = resolve; });
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: { ...sandbox(), getRunnerIngressEndpoint: acquire } as AdapterExecutionTarget,
|
|
binding, runnerIngressAuthorized: true, prepareRemote: prepare, processStarted,
|
|
});
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
expect(prepare).toHaveBeenCalledWith("listen_ws");
|
|
expect(prepare.mock.invocationCallOrder[0]).toBeLessThan(acquire.mock.invocationCallOrder[0]);
|
|
expect(connection.connection?.mode).toBe("listen");
|
|
await connection.activate!();
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
started();
|
|
await connection.ready!();
|
|
expect(transport.connect).toHaveBeenCalledWith(expect.objectContaining({ authority, endpoint: ingress }));
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
await connection.release();
|
|
expect(transport.connect.mock.results[0].value.close).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("does not fall back to outbound WSS when sandbox ingress is unauthorized", async () => {
|
|
const prepare = vi.fn();
|
|
const acquire = vi.fn();
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: { ...sandbox(), getRunnerIngressEndpoint: acquire } as AdapterExecutionTarget,
|
|
binding, runnerPublicUrl: "wss://core.example", prepareRemote: prepare,
|
|
});
|
|
await expect(driver.controlPlaneRegistration!(authority)).rejects.toThrow("runner_ingress_unavailable");
|
|
expect(prepare).not.toHaveBeenCalled();
|
|
expect(acquire).not.toHaveBeenCalled();
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("closes acquired ingress when setup ends before activation", async () => {
|
|
const ingress = endpoint();
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: { ...sandbox(), getRunnerIngressEndpoint: async () => ingress } as AdapterExecutionTarget,
|
|
binding, runnerIngressAuthorized: true, prepareRemote: async () => {}, processStarted: Promise.resolve(),
|
|
});
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
await connection.release();
|
|
expect(ingress.close).toHaveBeenCalledOnce();
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("uses the newly authorized run binding during warm registration", async () => {
|
|
const beforeConnect = vi.fn(async () => {});
|
|
const identity = { runId: "run-b" } as Parameters<NonNullable<ReturnType<typeof createNativeRunnerExecutionDriver>["controlPlaneRegistration"]>>[1];
|
|
const driver = createNativeRunnerExecutionDriver({ target: { kind: "local" }, binding, beforeConnect });
|
|
await driver.controlPlaneRegistration!(authority, identity);
|
|
expect(beforeConnect).toHaveBeenCalledWith(identity, authority);
|
|
expect(transport.register).toHaveBeenCalledWith({ ...binding, runId: "run-b", authority });
|
|
expect(beforeConnect.mock.invocationCallOrder[0]).toBeLessThan(transport.register.mock.invocationCallOrder[0]);
|
|
});
|
|
|
|
it("blocks registration if warm recovery authority is no longer valid", async () => {
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: { kind: "local" }, binding,
|
|
beforeConnect: async () => { throw new Error("recovery_denied"); },
|
|
});
|
|
await expect(driver.controlPlaneRegistration!(authority)).rejects.toThrow("recovery_denied");
|
|
expect(transport.register).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("requires exact process identity before admitting an external provider", async () => {
|
|
const driver = createNativeRunnerExecutionDriver({
|
|
target: ssh, binding, runnerPublicUrl: "wss://core.example", prepareRemote: async () => {},
|
|
processIdentityReady: Promise.reject(new Error("process_identity_invalid")),
|
|
});
|
|
const connection = await driver.controlPlaneRegistration!(authority);
|
|
await expect(connection.ready!()).rejects.toThrow("process_identity_invalid");
|
|
});
|
|
});
|
|
|
|
it("validates connectivity before resolving provider artifacts without acquiring an ingress endpoint", async () => {
|
|
const prepare = vi.fn(async () => {});
|
|
await expect(prepareNativeRemoteRunner({ target: ssh, runId: "run", prepareRemote: prepare })).rejects.toThrow("runner_transport_ineligible");
|
|
expect(prepare).not.toHaveBeenCalled();
|
|
await prepareNativeRemoteRunner({ target: sandbox(), runnerIngressAuthorized: true, runId: "run", prepareRemote: prepare });
|
|
expect(prepare).toHaveBeenCalledExactlyOnceWith("listen_ws");
|
|
expect(transport.connect).not.toHaveBeenCalled();
|
|
});
|