Multiplayer agent harness for work.
Decide Docker, Fly, Porter and RDS-drill outcomes from state, not error text (#2443)
Regan Bellf7d8f8a02f0b
diff --git a/scripts/aws/rds-restore-drill.ts b/scripts/aws/rds-restore-drill.tsindex b726f2e55..0b009186d 100644--- a/scripts/aws/rds-restore-drill.ts+++ b/scripts/aws/rds-restore-drill.ts@@ -75,7 +75,7 @@ export function verifyScript(host: string): string {validateEndpoint(host);return ["set -eu",- `RESTORE_URL=$(printf %s "$DATABASE_URL" | sed -E "s#^((postgres|postgresql)://[^@]+@)[^/:?]+#\\1$RESTORE_HOST#; s/sslmode=no-verify/sslmode=require/")`,+ 'RESTORE_URL="${DATABASE_URL%%\\?*}?host=$RESTORE_HOST&sslmode=require"',`pg_isready --dbname="$RESTORE_URL"`,`test "$(psql "$RESTORE_URL" -Atc 'SELECT COUNT(*) FROM sessions')" -gt 0`,`test "$(psql "$RESTORE_URL" -Atc "SELECT COUNT(*) FROM qm_schema_migrations")" -gt 0`,@@ -228,10 +228,10 @@ async function verify(config: QmConfig, host: string): Promise<void> {});}-function deleteDrill(config: QmConfig, identifier: string): void {+export function deleteDrill(config: QmConfig, identifier: string): void {const described = awsJson<{DBInstances?: Array<{ DBInstanceIdentifier?: string }>;- }>(config, ["rds", "describe-db-instances", "--db-instance-identifier", identifier]);+ }>(config, ["rds", "describe-db-instances", "--filters", `Name=db-instance-id,Values=${identifier}`]);if (!described.DBInstances?.length) return;awsText(config, ["rds",@@ -255,12 +255,7 @@ async function main(argv = process.argv.slice(2)): Promise<void> {} else if (args.command === "verify") {await verify(config, args.host!);} else {- try {- deleteDrill(config, identifier);- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- if (!/DBInstanceNotFound/.test(message)) throw error;- }+ deleteDrill(config, identifier);}}diff --git a/src/deploy/docker-deploy-provider.ts b/src/deploy/docker-deploy-provider.tsindex 96f5a4bc0..eb14bae7a 100644--- a/src/deploy/docker-deploy-provider.ts+++ b/src/deploy/docker-deploy-provider.ts@@ -1,6 +1,11 @@import type { Deployment, DeploymentVersion } from "./deploy-store.ts";import type { DeployEndpoint, DeployProvider } from "./deploy-provider.ts";-import { spawnDockerExec, type DockerExec } from "../sandbox/docker-exec.ts";+import {+ dockerContainerNetworks,+ ensureDockerNetwork,+ spawnDockerExec,+ type DockerExec,+} from "../sandbox/docker-exec.ts";import { errMessage } from "../util/errors.ts";import {appBoot,@@ -16,7 +21,6 @@ import {const APP_PORT = 8080;const APP_READY_WINDOW_SEC = 60;const RUN_TIMEOUT_MS = 300_000;-const LEGACY_NETWORK = "agent-deploynet";const DAEMON_PROBE_TIMEOUT_MS = 10_000;export interface DockerDeployProviderOptions {@@ -75,54 +79,13 @@ export function createDockerDeployProvider(opts: DockerDeployProviderOptions = {dexec(["exec", name(d), "sh", "-c", script], timeoutSec * 1000);const checked = recentAppChecks();const network = (d: Deployment) => `${name(d)}-net`;- const ensureNetwork = async (net: string): Promise<string> => {- if ((await dexec(["network", "inspect", net])).code !== 0) {- const r = await dexec(["network", "create", net]);- if (r.code !== 0 && !/already exists/i.test(r.stderr)) {- throw new Error(`docker network create ${net} failed: ${r.stderr.trim()}`);- }- }- return net;- };-- const migrateContainer = async (container: string): Promise<boolean> => {- const inspected = await dexec(["inspect", "--format", "{{json .NetworkSettings.Networks}}", container]);- if (inspected.code !== 0) {- if (/no such (?:object|container)|not found/i.test(inspected.stderr)) return false;- throw new Error(`docker inspect ${container} failed: ${inspected.stderr.trim()}`);- }- let attached: Record<string, unknown>;- try {- attached = JSON.parse(inspected.stdout) as Record<string, unknown>;- } catch {- throw new Error(`docker inspect ${container} returned invalid network state`);- }- const target = `${container}-net`;- await ensureNetwork(target);- if (!(target in attached)) {- const connected = await dexec(["network", "connect", target, container]);- if (connected.code !== 0) throw new Error(`docker network connect ${target} failed: ${connected.stderr.trim()}`);- }- if (LEGACY_NETWORK in attached) {- const disconnected = await dexec(["network", "disconnect", LEGACY_NETWORK, container]);- if (disconnected.code !== 0)- throw new Error(`docker network disconnect ${LEGACY_NETWORK} failed: ${disconnected.stderr.trim()}`);- }- return true;- };- const migrateTarget = async (container: string): Promise<boolean> => {- try {- return await migrateContainer(container);- } catch {- return migrateContainer(container);- }- };+ const exists = async (d: Deployment): Promise<boolean> => (await dockerContainerNetworks(dexec, name(d))) !== null;return {profile: { managedScaleToZero: false },async apply(d: Deployment, version: DeploymentVersion): Promise<DeployEndpoint> {- const net = await ensureNetwork(network(d));+ const net = await ensureDockerNetwork(dexec, network(d));await dexec(["rm", "-f", name(d)]);const hostPort = allocPort(name(d));const envArgs = Object.entries(version.env ?? {}).flatMap(([k, v]) => ["-e", `${k}=${v}`]);@@ -175,7 +138,7 @@ export function createDockerDeployProvider(opts: DockerDeployProviderOptions = {},async logs(d: Deployment, opts: { tailLines: number }): Promise<string | null> {- if (!(await migrateTarget(name(d)))) return null;+ if (!(await exists(d))) return null;return appLogs(execIn(d), opts.tailLines);},@@ -187,7 +150,7 @@ export function createDockerDeployProvider(opts: DockerDeployProviderOptions = {async resolveEndpoint(d, version): Promise<DeployEndpoint | null> {if (checked.has(d.id)) return d.endpoint;- if (!(await migrateTarget(name(d)))) return null;+ if (!(await exists(d))) return null;const report = appReporter(opts.onError, d, version.env);if (await appGone(execIn(d), { appPort: APP_PORT, report })) return null;checked.set(d.id, true);diff --git a/src/deploy/fly-deploy-provider.ts b/src/deploy/fly-deploy-provider.tsindex 201bf4128..29699130f 100644--- a/src/deploy/fly-deploy-provider.ts+++ b/src/deploy/fly-deploy-provider.ts@@ -31,7 +31,6 @@ const MACHINE_START_TIMEOUT_MS = 90_000;const APP_READY_TIMEOUT_MS = 90_000;const POLL_INTERVAL_MS = 1_000;const API_TIMEOUT_MS = 30_000;-const APP_ALREADY_TAKEN = /already\s+(exists|been\s+taken)|name\s+is\s+taken/i;interface FlyApp {name: string;@@ -208,10 +207,9 @@ function createFlyMachinesApi(opts: { token: string; fetchImpl?: typeof fetch })}const r = await request("POST", "/apps", { app_name: appName, org_slug: orgSlug, network: appName });if (r.ok) return;- if (r.status !== 409 && r.status !== 422 && !APP_ALREADY_TAKEN.test(r.text)) {- throw failure(`create app ${appName}`, r);- }- const found = await getApp(appName);+ const found = await getApp(appName).catch((e: unknown) => {+ throw new Error(failure(`create app ${appName}`, r).message, { cause: e });+ });if (!found) throw failure(`create app ${appName}`, r);assertOwned(appName, orgSlug, found);},diff --git a/src/deploy/porter-deploy-provider.ts b/src/deploy/porter-deploy-provider.tsindex 7581868c8..d5a0752f3 100644--- a/src/deploy/porter-deploy-provider.ts+++ b/src/deploy/porter-deploy-provider.ts@@ -32,7 +32,7 @@ import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts"import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";import { createKeyedQueue } from "../util/async.ts";import { shq } from "../util/shell.ts";-import { errMessage, execFailure, swallow, swallowAs } from "../util/errors.ts";+import { execFailure, swallow, swallowAs } from "../util/errors.ts";const APP_DIR = "/app";const HOME_DIR = "/root";@@ -209,29 +209,19 @@ export function createPorterDeployProvider(opts: PorterDeployProviderOptions): Dawait retireBodies(d, true);await store.delete(d.id).catch((e) => swallow("porter-deploy: clear stale pointer", e));const name = `${baseName(d)}-${randomUUID().slice(0, 5)}`;- const sb = await client.sandboxes- .create({- image,- name,- command: ["sleep", "infinity"],- tags: { [KIND_TAG]: "app", [DEPLOY_TAG]: d.id },- env: appEnv(version),- volume_mounts: { [DATA_DIR]: volumeId },- networking:- visibility === "internal"- ? [{ port: appPort, internal: true }]- : [{ port: appPort, ...(domainOf(d) ? { domains: [{ domain: domainOf(d), visibility }] } : {}) }],- ...(opts.ttlSec ? { ttl_seconds: opts.ttlSec } : {}),- })- .catch((e) => {- if (visibility !== "internal" && errMessage(e).includes("sandbox ingress")) {- throw new Error(- `porter deploy ${d.id}: the cluster refused the app's ${visibility} domain because sandbox ingress is not enabled — turn it on for this cluster (docs/porter.md), then point PORTER_DEPLOY_APPS_DOMAIN's wildcard DNS record at it (${errMessage(e)})`,- { cause: e },- );- }- throw e;- });+ const sb = await client.sandboxes.create({+ image,+ name,+ command: ["sleep", "infinity"],+ tags: { [KIND_TAG]: "app", [DEPLOY_TAG]: d.id },+ env: appEnv(version),+ volume_mounts: { [DATA_DIR]: volumeId },+ networking:+ visibility === "internal"+ ? [{ port: appPort, internal: true }]+ : [{ port: appPort, ...(domainOf(d) ? { domains: [{ domain: domainOf(d), visibility }] } : {}) }],+ ...(opts.ttlSec ? { ttl_seconds: opts.ttlSec } : {}),+ });try {await waitPorterRunning(name, sb);const address = await addressOf(d, sb);diff --git a/src/sandbox/docker-exec.ts b/src/sandbox/docker-exec.tsindex 37d09eed1..3110f03dd 100644--- a/src/sandbox/docker-exec.ts+++ b/src/sandbox/docker-exec.ts@@ -24,3 +24,22 @@ export function spawnDockerExec(dockerBin: string): DockerExec {child.on("close", (code) => done({ code: code ?? -1, stdout, stderr }));});}++export async function ensureDockerNetwork(dexec: DockerExec, net: string): Promise<string> {+ if ((await dexec(["network", "inspect", net])).code === 0) return net;+ const created = await dexec(["network", "create", net]);+ if (created.code !== 0 && (await dexec(["network", "inspect", net])).code !== 0) {+ throw new Error(`docker network create ${net} failed: ${created.stderr.trim()}`);+ }+ return net;+}++export async function dockerContainerNetworks(dexec: DockerExec, container: string): Promise<string[] | null> {+ const listed = await dexec(["ps", "-a", "--filter", `name=${container}`, "--format", "{{.Names}}\t{{.Networks}}"]);+ if (listed.code !== 0) throw new Error(`docker ps ${container} failed: ${listed.stderr.trim()}`);+ const row = listed.stdout+ .split("\n")+ .map((line) => line.split("\t"))+ .find(([name]) => name === container);+ return row ? (row[1] ?? "").split(",").filter(Boolean) : null;+}diff --git a/src/sandbox/local-sandbox.ts b/src/sandbox/local-sandbox.tsindex 2cc044a1b..1abb003d6 100644--- a/src/sandbox/local-sandbox.ts+++ b/src/sandbox/local-sandbox.ts@@ -13,7 +13,7 @@ import { nonInteractiveShellPrefix } from "./sandbox-env.ts";import { createExecProcessSessions, type ExecProcessIo } from "./exec-process-session.ts";import { materializeRoLayers } from "./ro-layers.ts";import { createExecExport, createExecFileOps, posixJoin } from "./exec-file-ops.ts";-import { spawnDockerExec, type DockerExec } from "./docker-exec.ts";+import { dockerContainerNetworks, ensureDockerNetwork, spawnDockerExec, type DockerExec } from "./docker-exec.ts";import { ephemeralCredLinkScript } from "../credentials/resident-paths.ts";import { ephemeralCredLinkPaths } from "../credentials/resident-paths.ts";import { shortHash } from "../util/crypto.ts";@@ -235,20 +235,13 @@ export function createLocalSandbox(workspace: WorkspaceStore, opts: LocalSandbox}async function ensureNetwork(name: string): Promise<string> {- const net = localNetworkName(name);- if ((await dexec(["network", "inspect", net])).code !== 0) {- const r = await dexec(["network", "create", net]);- if (r.code !== 0 && !/already exists/i.test(r.stderr)) {- throw new Error(`docker network create ${net} failed: ${r.stderr.trim()}`);- }- }- return net;+ return ensureDockerNetwork(dexec, localNetworkName(name));}async function connectCore(net: string): Promise<void> {if (!opts.coreContainer) return;const r = await dexec(["network", "connect", net, opts.coreContainer]);- if (r.code !== 0 && !/already (?:exists|connected)/i.test(r.stderr)) {+ if (r.code !== 0 && !(await dockerContainerNetworks(dexec, opts.coreContainer))?.includes(net)) {throw new Error(`docker network connect ${net} ${opts.coreContainer} failed: ${r.stderr.trim()}`);}}@@ -483,23 +476,16 @@ export function createLocalSandbox(workspace: WorkspaceStore, opts: LocalSandboxconst network = localNetworkName(name);const remove = async (args: string[]) => {const result = await dexec(args);- if (- result.code !== 0 &&- !/no such (container|object|network|volume)|network .* not found/i.test(result.stderr)- )- throw new Error(`docker ${args.join(" ")}: ${result.stderr.trim()}`);+ if (result.code !== 0) throw new Error(`docker ${args.join(" ")}: ${result.stderr.trim()}`);};await remove(["rm", "-f", name]);if (opts.coreContainer) {const result = await dexec(["network", "disconnect", "-f", network, opts.coreContainer]);- if (- result.code !== 0 &&- !/no such (network|container|object)|is not connected|network .* not found/i.test(result.stderr)- )+ if (result.code !== 0 && (await dockerContainerNetworks(dexec, opts.coreContainer))?.includes(network))throw new Error(`docker network disconnect ${network}: ${result.stderr.trim()}`);}- await remove(["network", "rm", network]);- await remove(["volume", "rm", localVolumeName(scopeId)]);+ await remove(["network", "rm", "-f", network]);+ await remove(["volume", "rm", "-f", localVolumeName(scopeId)]);activeByContainer.delete(name);scopeByContainer.delete(name);portByName.delete(name);diff --git a/test/aws-recovery-drills.test.ts b/test/aws-recovery-drills.test.tsindex 1b46b37ed..e40ed331d 100644--- a/test/aws-recovery-drills.test.ts+++ b/test/aws-recovery-drills.test.ts@@ -1,7 +1,12 @@import { test } from "node:test";import assert from "node:assert/strict";import { brokenTaskDefinition } from "../scripts/aws/ecs-blue-green-drill.ts";-import { validateDrillIdentifier, verifyScript } from "../scripts/aws/rds-restore-drill.ts";+import { execFileSync } from "node:child_process";+import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { QmConfig } from "../cli/src/config.ts";+import { deleteDrill, validateDrillIdentifier, verifyScript } from "../scripts/aws/rds-restore-drill.ts";test("restore drills accept only scoped temporary database identifiers", () => {assert.equal(@@ -18,15 +23,68 @@ test("restore drills accept only scoped temporary database identifiers", () => {}});-test("restore verification uses the task secret but replaces only its private host", () => {- const script = verifyScript("restore.abc.us-west-2.rds.amazonaws.com");- assert.match(script, /RESTORE_URL=.*DATABASE_URL/);- assert.match(script, /RESTORE_HOST/);- assert.match(script, /pg_isready/);- assert.match(script, /SELECT COUNT\(\*\) FROM sessions/);- assert.match(script, /qm_schema_migrations/);+function fakeBin(dir: string, name: string, body: string): void {+ writeFileSync(join(dir, name), `#!/bin/sh\n${body}\n`);+ chmodSync(join(dir, name), 0o755);+}++test("restore verification points the task's database URL at the restored host and requires TLS", () => {+ const host = "restore.abc.us-west-2.rds.amazonaws.com";+ const script = verifyScript(host);assert.doesNotMatch(script, /restore\.abc/);assert.throws(() => verifyScript("restore; echo compromised"));+ for (const [databaseUrl, restoreUrl] of [+ [+ "postgres://qm:p%[email protected]:5432/qm?sslmode=no-verify",+ `postgres://qm:p%[email protected]:5432/qm?host=${host}&sslmode=require`,+ ],+ [+ "postgresql://qm:[email protected]/qm",+ `postgresql://qm:[email protected]/qm?host=${host}&sslmode=require`,+ ],+ ]) {+ const bin = mkdtempSync(join(tmpdir(), "rds-verify-"));+ fakeBin(bin, "pg_isready", `printf '%s\\n' "$1" > "${bin}/pg_isready.args"`);+ fakeBin(bin, "psql", `printf '%s\\n' "$1" >> "${bin}/psql.args"; echo 3`);+ const out = execFileSync("sh", ["-c", script], {+ encoding: "utf8",+ env: { PATH: `${bin}:${process.env.PATH}`, DATABASE_URL: databaseUrl, RESTORE_HOST: host },+ });+ assert.equal(out.trim(), "RDS_RESTORE_DRILL_OK");+ assert.equal(readFileSync(join(bin, "pg_isready.args"), "utf8"), `--dbname=${restoreUrl}\n`);+ assert.equal(readFileSync(join(bin, "psql.args"), "utf8"), `${restoreUrl}\n${restoreUrl}\n`);+ }+});++test("deleting a drill database that does not exist is a no-op, and an existing one is deleted", () => {+ const bin = mkdtempSync(join(tmpdir(), "rds-delete-"));+ const config = { target: "aws", aws: { region: "us-west-2" } } as unknown as QmConfig;+ const identifier = "acme-qm-core-restore-drill-1";+ const previous = process.env.AWS_BIN;+ process.env.AWS_BIN = join(bin, "aws");+ try {+ for (const instances of ["[]", `[{"DBInstanceIdentifier":"${identifier}"}]`]) {+ fakeBin(+ bin,+ "aws",+ `echo "$*" >> "${bin}/aws.calls"; [ "$2" = describe-db-instances ] && echo '{"DBInstances":${instances}}'; true`,+ );+ writeFileSync(join(bin, "aws.calls"), "");+ deleteDrill(config, identifier);+ const calls = readFileSync(join(bin, "aws.calls"), "utf8").trim().split("\n");+ assert.match(+ calls[0]!,+ new RegExp(`^rds describe-db-instances --filters Name=db-instance-id,Values=${identifier} `),+ );+ assert.equal(+ calls.some((call) => call.startsWith(`rds delete-db-instance --db-instance-identifier ${identifier} `)),+ instances !== "[]",+ );+ }+ } finally {+ if (previous === undefined) delete process.env.AWS_BIN;+ else process.env.AWS_BIN = previous;+ }});test("blue/green drill preserves the deployed task contract and breaks only core health", () => {diff --git a/test/docker-deploy-provider.test.ts b/test/docker-deploy-provider.test.tsindex c78dbc61f..e2b37ce94 100644--- a/test/docker-deploy-provider.test.ts+++ b/test/docker-deploy-provider.test.ts@@ -43,92 +43,51 @@ test("Docker deployments use isolated networks and remove them on destroy", asynassert.ok(calls.some((args) => args.join(" ") === `network rm ${firstName}-net`));});-test("Docker provider migrates running deployments off the legacy shared network", async () => {- const calls: string[][] = [];- let containerName = "";- let connectAttempts = 0;- let targetAttached = false;- let legacyAttached = true;- const dockerExec: DockerExec = async (args) => {- calls.push(args);- if (args.join(" ") === "network inspect --format {{range .Containers}}{{println .Name}}{{end}} agent-deploynet") {- return { code: 0, stdout: legacyAttached ? `${containerName}\n` : "", stderr: "" };- }- if (args[0] === "network" && args[1] === "inspect") return { code: 1, stdout: "", stderr: "missing" };- if (args[0] === "network" && args[1] === "connect" && ++connectAttempts === 1) {- return { code: 1, stdout: "", stderr: "transient" };- }- if (args[0] === "network" && args[1] === "connect") targetAttached = true;- if (args[0] === "network" && args[1] === "disconnect") legacyAttached = false;- if (args[0] === "inspect") {- return {- code: 0,- stdout: JSON.stringify({- ...(legacyAttached ? { "agent-deploynet": {} } : {}),- ...(targetAttached ? { [`${containerName}-net`]: {} } : {}),- }),- stderr: "",- };- }- return { code: 0, stdout: "", stderr: "" };- };+test("a transient docker failure does not report the deployment missing", async () => {+ const dockerExec: DockerExec = async () => ({ code: 1, stdout: "", stderr: "daemon unavailable" });const store = createDeployStore();const deployment = await store.create({ownerScopeId: scopeId("personal", "U1"),createdBy: "U1",entrypoint: "node server.js",- snapshotDir: "/snap/legacy",+ snapshotDir: "/snap/running",});- containerName = `agent-deploy-${deployment.id.slice(0, 12)}`;await store.setEndpoint(deployment.id, { host: "127.0.0.1", port: 9200 });const running = (await store.get(deployment.id))!;const provider = createDockerDeployProvider({ dockerExec });- assert.deepEqual(await provider.resolveEndpoint!(running, running.versions[0]!), running.endpoint);- assert.equal(connectAttempts, 2);- assert.ok(calls.some((args) => args.join(" ") === `network connect ${containerName}-net ${containerName}`));- assert.ok(calls.some((args) => args.join(" ") === `network disconnect agent-deploynet ${containerName}`));-});--test("constructing a Docker provider does not inspect or migrate unrelated deployments", async () => {- const calls: string[][] = [];- const dockerExec: DockerExec = async (args) => {- calls.push(args);- return { code: 0, stdout: "", stderr: "" };- };-- createDockerDeployProvider({ dockerExec });- await new Promise((resolve) => setImmediate(resolve));- assert.deepEqual(calls, []);+ await assert.rejects(provider.resolveEndpoint!(running, running.versions[0]!), /daemon unavailable/);});-test("an unrelated legacy migration failure does not block a new deployment", async () => {+test("a deployment is missing unless docker lists a container with exactly its name", async () => {const dockerExec: DockerExec = async (args) => {- if (args.join(" ") === "network inspect --format {{range .Containers}}{{println .Name}}{{end}} agent-deploynet") {- return { code: 0, stdout: "agent-deploy-broken\n", stderr: "" };- }- if (args[0] === "inspect") return { code: 1, stdout: "", stderr: "daemon unavailable" };- if (args[0] === "network" && args[1] === "inspect") return { code: 1, stdout: "", stderr: "missing" };- return { code: 0, stdout: "", stderr: "" };+ if (args[0] === "ps") return { code: 0, stdout: "agent-deploy-other\tbridge\n", stderr: "" };+ return { code: 1, stdout: "", stderr: "daemon unavailable" };};const store = createDeployStore();const deployment = await store.create({ownerScopeId: scopeId("personal", "U1"),createdBy: "U1",entrypoint: "node server.js",- snapshotDir: "/snap/new",+ snapshotDir: "/snap/gone",});+ await store.setEndpoint(deployment.id, { host: "127.0.0.1", port: 9200 });+ const running = (await store.get(deployment.id))!;const provider = createDockerDeployProvider({ dockerExec });- await assert.doesNotReject(provider.apply(deployment, deployment.versions[0]!));+ assert.equal(await provider.resolveEndpoint!(running, running.versions[0]!), null);+ assert.equal(await provider.logs!(running, { tailLines: 10 }), null);});-test("a transient target inspection failure does not report the deployment missing", async () => {+test("a deployment network created concurrently is reused, and a create that leaves none fails", async () => {+ let networkExists = false;+ let createLeavesNetwork = true;const dockerExec: DockerExec = async (args) => {- if (args.join(" ") === "network inspect --format {{range .Containers}}{{println .Name}}{{end}} agent-deploynet") {- return { code: 1, stdout: "", stderr: "No such network" };+ if (args[0] === "network" && args[1] === "inspect") return { code: networkExists ? 0 : 1, stdout: "", stderr: "" };+ if (args[0] === "network" && args[1] === "create") {+ networkExists = createLeavesNetwork;+ return { code: 1, stdout: "", stderr: "network with name x already exists" };}- if (args[0] === "inspect") return { code: 1, stdout: "", stderr: "daemon unavailable" };return { code: 0, stdout: "", stderr: "" };};const store = createDeployStore();@@ -136,13 +95,17 @@ test("a transient target inspection failure does not report the deployment missiownerScopeId: scopeId("personal", "U1"),createdBy: "U1",entrypoint: "node server.js",- snapshotDir: "/snap/running",+ snapshotDir: "/snap/race",});- await store.setEndpoint(deployment.id, { host: "127.0.0.1", port: 9200 });- const running = (await store.get(deployment.id))!;const provider = createDockerDeployProvider({ dockerExec });- await assert.rejects(provider.resolveEndpoint!(running, running.versions[0]!), /daemon unavailable/);+ await assert.doesNotReject(provider.apply(deployment, deployment.versions[0]!));+ networkExists = false;+ createLeavesNetwork = false;+ await assert.rejects(+ provider.apply(deployment, deployment.versions[0]!),+ /network create .* failed: .*already exists/,+ );});test("the daemon probe reports nothing when Docker answers", async () => {diff --git a/test/fly-deploy-provider.test.ts b/test/fly-deploy-provider.test.tsindex b1484cdec..efc308f13 100644--- a/test/fly-deploy-provider.test.ts+++ b/test/fly-deploy-provider.test.ts@@ -38,6 +38,8 @@ interface FakeFlyOptions {createAppStatus?: number;createAppBody?: string;existingApp?: { name: string; network: string; organization: { slug: string } };+ racingApp?: { name: string; network: string; organization: { slug: string } };+ rereadAppStatus?: number;ips?: string[];ingressNetwork?: string;networkPolicies?: unknown[];@@ -67,6 +69,7 @@ function fakeFly(opts: FakeFlyOptions = {}) {const cordoned = new Set<string>();let app = opts.existingApp;let created = 0;+ let reread: number | undefined;const fetchImpl = (async (input: string | URL, init: RequestInit = {}): Promise<Response> => {const url = new URL(String(input));const method = init.method ?? "GET";@@ -85,8 +88,11 @@ function fakeFly(opts: FakeFlyOptions = {}) {if ((opts.createAppStatus ?? 201) < 300) {app = { name: body.app_name, network: body.network, organization: { slug: body.org_slug } };}+ if (opts.racingApp) app = opts.racingApp;+ reread = opts.rereadAppStatus;return new Response(opts.createAppBody ?? "{}", { status: opts.createAppStatus ?? 201 });}+ if (method === "GET" && segments.length === 3 && reread) return json(reread, { error: "unavailable" });if (method === "GET" && segments.length === 3) return app ? json(200, app) : json(404, { error: "not found" });if (method === "DELETE" && segments.length === 3) {app = undefined;@@ -285,7 +291,7 @@ test("apply: keeps an always-on deployment running under Fly managed lifecycle",});test("apply: refuses a pre-existing public IP before creating a machine", async () => {- const unsafe = fakeFly({ createAppStatus: 422, existingApp: OWNED_APP, ips: ["2a09:8280:1::1"] });+ const unsafe = fakeFly({ existingApp: OWNED_APP, ips: ["2a09:8280:1::1"] });await assert.rejects(provider(unsafe.fetchImpl).apply(deployment(ID), version(snapshot({ "index.html": "hi" }))),/public IP assignment; refusing to expose/,@@ -293,23 +299,25 @@ test("apply: refuses a pre-existing public IP before creating a machine", asyncassert.ok(!unsafe.calls.some((c) => c.path.endsWith("/machines")), "an unsafe app never gets a machine");});-test("apply: an app that already exists is not an error", async () => {+test("apply: an app created concurrently is reused whatever the create failure says", async () => {for (const over of [- { createAppStatus: 409, existingApp: OWNED_APP },- { createAppStatus: 422, createAppBody: '{"error":"Name has already been taken"}', existingApp: OWNED_APP },+ { createAppStatus: 409 },+ { createAppStatus: 422, createAppBody: '{"error":"Name has already been taken"}' },+ { createAppStatus: 500, createAppBody: '{"error":"internal"}' },]) {- const { fetchImpl } = fakeFly(over);+ const { fetchImpl, calls } = fakeFly({ ...over, racingApp: OWNED_APP });const endpoint = await provider(fetchImpl).apply(deployment(ID), version(snapshot({ "index.html": "hi" })));assert.deepEqual(endpoint, { host: `${APP}.flycast`, port: 8080 });+ assert.ok(calls.some((c) => c.method === "POST" && c.path === "/v1/apps"));}});test("apply: a name conflict is reused only when its organization and isolated network match", async () => {- for (const existingApp of [+ for (const racingApp of [{ ...OWNED_APP, network: "default" },{ ...OWNED_APP, organization: { slug: "someone-else" } },]) {- const { fetchImpl, calls } = fakeFly({ createAppStatus: 422, existingApp });+ const { fetchImpl, calls } = fakeFly({ createAppStatus: 422, racingApp });await assert.rejects(provider(fetchImpl).apply(deployment(ID), version(snapshot({ "index.html": "hi" }))),/not the isolated app owned by this deployment/,@@ -319,10 +327,27 @@ test("apply: a name conflict is reused only when its organization and isolated n});test("apply: a rejected app creation still surfaces", async () => {- const { fetchImpl } = fakeFly({ createAppStatus: 401, createAppBody: '{"error":"unauthorized"}' });+ for (const [status, body] of [+ [401, '{"error":"unauthorized"}'],+ [422, '{"error":"Name has already been taken"}'],+ ] as const) {+ const { fetchImpl } = fakeFly({ createAppStatus: status, createAppBody: body });+ await assert.rejects(+ provider(fetchImpl).apply(deployment(ID), version(snapshot({ "index.html": "hi" }))),+ new RegExp(`create app .*http ${status}`),+ );+ }+});++test("apply: a failed create whose app cannot be re-read reports the create failure", async () => {+ const { fetchImpl } = fakeFly({ createAppStatus: 500, createAppBody: '{"error":"boom"}', rereadAppStatus: 503 });await assert.rejects(provider(fetchImpl).apply(deployment(ID), version(snapshot({ "index.html": "hi" }))),- /create app .*http 401.*unauthorized/,+ (e: Error) => {+ assert.match(e.message, /create app .*http 500.*boom/);+ assert.match(String((e.cause as Error).message), /read app .*http 503/);+ return true;+ },);});diff --git a/test/local-sandbox.test.ts b/test/local-sandbox.test.tsindex 96a8db85e..92bb43e0a 100644--- a/test/local-sandbox.test.ts+++ b/test/local-sandbox.test.ts@@ -314,3 +314,25 @@ test("containerized core joins each sandbox network and reaches the daemon by coawait sb.teardown(h, { destroy: true });assert.equal(fake.connections.has(`${localNetworkName(h.id)}|qm-test-core`), false);});++test("core attachment trusts the core's actual networks, not docker's connect error", async () => {+ const fake = installFakeDocker(daemonPort);+ const fetchImpl: typeof fetch = (input) => {+ const url = typeof input === "string" ? input : input.toString();+ if (url.endsWith("/health")) return Promise.resolve(new Response("", { status: 200 }));+ return Promise.resolve(new Response(JSON.stringify({ code: 0, stdout: "", stderr: "", timedOut: false })));+ };+ const layers = rw(scopeId("personal", "U42"));+ const sb = makeSandbox(fake, { coreContainer: "qm-test-core", fetchImpl });+ const first = await sb.provision(layers);+ const again = await sb.provision(layers);+ assert.equal(again.id, first.id);+ fake.connections.delete(`${localNetworkName(first.id)}|qm-test-core`);+ const refusing = makeSandbox(fake, {+ coreContainer: "qm-test-core",+ fetchImpl,+ dockerExec: async (args: string[]) =>+ args[1] === "connect" ? { code: 1, stdout: "", stderr: "endpoint already exists" } : fake.dockerExec(args),+ });+ await assert.rejects(refusing.provision(layers), /network connect .* failed: endpoint already exists/);+});diff --git a/test/porter-deploy-provider.test.ts b/test/porter-deploy-provider.test.tsindex 0defc251e..45d614ead 100644--- a/test/porter-deploy-provider.test.ts+++ b/test/porter-deploy-provider.test.ts@@ -450,3 +450,12 @@ test("deployment names become DNS labels and ids become sandbox-safe names", asyassert.match(body.name, /^qmt-app-dep-9-/);assert.deepEqual(fake.volumeNames(), ["qmt-app-dep-9-data"]);});++test("a refused sandbox create surfaces the cluster's own error unchanged", async () => {+ const refused = new Error("no private sandbox ingress is configured on this cluster");+ fake.client.sandboxes.create = () => Promise.reject(refused);+ await assert.rejects(+ provider.apply(deployment("refused"), version({ "server.js": SERVER }, "node server.js")),+ (error) => error === refused,+ );+});diff --git a/test/sandbox-destroy-scope.test.ts b/test/sandbox-destroy-scope.test.tsindex 0b6bc70e4..dbc11e43d 100644--- a/test/sandbox-destroy-scope.test.ts+++ b/test/sandbox-destroy-scope.test.ts@@ -18,6 +18,7 @@ import { sandboxScopeName } from "../src/sandbox/exec-sandbox-base.ts";import { installFakeSmolmachines } from "./support/fake-smolmachines.ts";import { installFakeSprites } from "./support/fake-sprites.ts";import { installFakeAgent37 } from "./support/fake-agent37.ts";+import { installFakeDocker } from "./support/fake-docker.ts";const workspace = () => createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "destroy-scope-")));@@ -27,20 +28,36 @@ test("Local scope deletion removes deterministic resources without provisioning,const sandbox = createLocalSandbox(workspace(), {dockerExec: async (args) => {calls.push(args);- return { code: 1, stdout: "", stderr: fail ? "daemon unavailable" : "No such object" };+ return fail ? { code: 1, stdout: "", stderr: "daemon unavailable" } : { code: 0, stdout: "", stderr: "" };},});await sandbox.destroyScope!("missing");assert.deepEqual(calls, [["rm", "-f", localContainerName("missing")],- ["network", "rm", localNetworkName(localContainerName("missing"))],- ["volume", "rm", localVolumeName("missing")],+ ["network", "rm", "-f", localNetworkName(localContainerName("missing"))],+ ["volume", "rm", "-f", localVolumeName("missing")],]);fail = true;await assert.rejects(sandbox.destroyScope!("missing"), /daemon unavailable/);assert.equal(calls.length, 4);});+test("Local scope deletion fails a refused core disconnect only while the core is still attached", async () => {+ const fake = installFakeDocker(0);+ const network = localNetworkName(localContainerName("scope"));+ const sandbox = createLocalSandbox(workspace(), {+ coreContainer: "qm-core",+ dockerExec: async (args) =>+ args[1] === "disconnect" ? { code: 1, stdout: "", stderr: "is not connected" } : fake.dockerExec(args),+ });+ fake.connections.add(`other-net|qm-core`);+ await sandbox.destroyScope!("scope");+ fake.networks.add(network);+ fake.connections.add(`${network}|qm-core`);+ await assert.rejects(sandbox.destroyScope!("scope"), /network disconnect .*: is not connected/);+ assert.equal(fake.networks.has(network), true);+});+test("Sprites scope deletion sends only DELETE, retries provider errors, and accepts missing bodies", async () => {const fake = installFakeSprites();try {diff --git a/test/support/fake-docker.ts b/test/support/fake-docker.tsindex d456a5be6..7549f94c8 100644--- a/test/support/fake-docker.ts+++ b/test/support/fake-docker.ts@@ -59,6 +59,14 @@ export function installFakeDocker(daemonPort: number): FakeDocker {return c;}+ const positional = (args: string[]) => args.filter((a) => !a.startsWith("-"));+ const networksOf = (container: string) =>+ [...connections].flatMap((key) => {+ const [net, attached] = key.split("|");+ return attached === container ? [net!] : [];+ });+ const exists = (container: string) => containers.has(container) || networksOf(container).length > 0;+function exec(args: string[]): { code: number; stdout: string; stderr: string } {const [cmd, ...rest] = args;if (self.daemonDown) return fail("Cannot connect to the Docker daemon");@@ -77,28 +85,36 @@ export function installFakeDocker(daemonPort: number): FakeDocker {if (!c) return fail(`Error: No such object: ${name}`);return ok(`${c.running} ${c.imageId}`);}+ case "ps": {+ const name = rest.find((a) => a.startsWith("name="))!.slice("name=".length);+ return ok(exists(name) ? `${name}\t${networksOf(name).join(",")}\n` : "");+ }case "network": {- const [sub, name] = rest as [string, string];- if (sub === "inspect") return networks.has(name) ? ok(name) : fail(`Error: No such network: ${name}`);+ const [sub, name, container] = positional(rest);+ if (sub === "inspect") return networks.has(name!) ? ok(name) : fail(`Error: No such network: ${name}`);if (sub === "create") {- if (networks.has(name)) return fail(`network with name ${name} already exists`);- networks.add(name);+ if (networks.has(name!)) return fail(`network with name ${name} already exists`);+ networks.add(name!);return ok(name);}- if (sub === "rm") return networks.delete(name) ? ok(name) : fail(`Error: No such network: ${name}`);+ if (sub === "rm") {+ if (networks.delete(name!) || rest.includes("-f")) return ok(name);+ return fail(`Error: No such network: ${name}`);+ }if (sub === "connect" || sub === "disconnect") {- const container = rest[2]!;const key = `${name}|${container}`;if (sub === "connect") {if (connections.has(key)) return fail("endpoint already exists");connections.add(key);- } else connections.delete(key);+ return ok(key);+ }+ if (!connections.delete(key)) return fail(`container ${container} is not connected to network ${name}`);return ok(key);}return fail(`unknown network subcommand ${sub}`);}case "volume": {- const [sub, name] = rest as [string, string];+ const [sub, name] = positional(rest) as [string, string];if (sub === "inspect") return volumes.has(name) ? ok(name) : fail(`Error: no such volume: ${name}`);if (sub === "create") {volumes.add(name);@@ -107,7 +123,7 @@ export function installFakeDocker(daemonPort: number): FakeDocker {if (sub === "rm") {const attached = [...containers.values()].some((c) => c.volume === name);if (attached) return fail(`volume is in use`);- return volumes.delete(name) ? ok(name) : fail(`Error: no such volume: ${name}`);+ return volumes.delete(name) || rest.includes("-f") ? ok(name) : fail(`Error: no such volume: ${name}`);}return fail(`unknown volume subcommand ${sub}`);}