Multiplayer agent harness for work.
Bound one-off ECS task waits by the rollout deadline instead of the CLI waiter's 10 minutes (#2503)
Regan Bell1af1b36cdb03
diff --git a/cli/README.md b/cli/README.mdindex 36c1ff47c..5c2fa4abb 100644--- a/cli/README.md+++ b/cli/README.md@@ -93,7 +93,10 @@ default), and a turn cut off there resumes on the new tasks. Core images olderthan this release protect their task while a turn runs, so the first `qm up`that replaces them cannot finish before their longest in-flight turn ends(protection expires after 60 minutes at most); run that one deploy with a-longer deadline or when no long turn is in flight.+longer deadline or when no long turn is in flight. The candidate migration task+and the private live-session canary also wait up to `QM_AWS_ROLLOUT_DEADLINE_MS`+(default 30 minutes for them); a task still running then is left to finish, and a+migration that outlasts it fails `up` before any service changes.AWS deployments can opt into durable background ownership with`aws.backgroundWorkControl: true`. The CLI allocates a uniquediff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.tsindex 7108fa228..3aa405b87 100644--- a/cli/src/backends/aws.ts+++ b/cli/src/backends/aws.ts@@ -916,21 +916,7 @@ async function runAwsCandidateMigration(throw new CliError(`AWS could not start the migration task${failures ? ` (${failures})` : ""}`);}step(`migration task: ${taskArn}`);- awsText(aws, ["ecs", "wait", "tasks-stopped", "--cluster", aws.cluster, "--tasks", taskArn]);- const stopped = awsJson<{- tasks?: Array<{- stoppedReason?: string;- containers?: Array<{ name?: string; exitCode?: number; reason?: string }>;- }>;- failures?: Array<{ arn?: string; reason?: string }>;- }>(aws, ["ecs", "describe-tasks", "--cluster", aws.cluster, "--tasks", taskArn]);- const task = stopped.tasks?.[0];- const core = task?.containers?.find((container) => container.name === "core");- if (stopped.failures?.length || core?.exitCode !== 0) {- throw new CliError(- `AWS migration task failed (${core?.reason ?? task?.stoppedReason ?? `exit ${core?.exitCode ?? "unknown"}`})`,- );- }+ await awaitEcsTaskExit(aws, taskArn, "migration");ok(`candidate ${label} migrations applied`);} finally {if (taskDefinition && !existingTaskDefinition) {@@ -1180,7 +1166,7 @@ interface EcsServiceRevision {taskDefinition?: string;}-function awsLiveSession(config: QmConfig, core: EcsServiceState): void {+async function awsLiveSession(config: QmConfig, core: EcsServiceState): Promise<void> {const aws = requireAws(config);if (!core.taskDefinition) throw new Error("core service has no live task definition");if (!core.networkConfiguration?.awsvpcConfiguration) throw new Error("core service has no VPC network configuration");@@ -1253,19 +1239,41 @@ function awsLiveSession(config: QmConfig, core: EcsServiceState): void {`could not start canary task: ${failure?.reason ?? failure?.detail ?? failure?.arn ?? "no task returned"}`,);}- awsText(aws, ["ecs", "wait", "tasks-stopped", "--cluster", aws.cluster, "--tasks", taskArn]);- const stopped = awsJson<{- tasks?: Array<{- stoppedReason?: string;- containers?: Array<{ name?: string; exitCode?: number; reason?: string }>;- }>;- }>(aws, ["ecs", "describe-tasks", "--cluster", aws.cluster, "--tasks", taskArn]);- const task = stopped.tasks?.[0];- const coreContainer = task?.containers?.find((container) => container.name === "core");- if (coreContainer?.exitCode !== 0) {- throw new Error(- `canary task exited ${coreContainer?.exitCode ?? "without a code"}: ${coreContainer?.reason ?? task?.stoppedReason ?? "unknown reason"}`,- );+ await awaitEcsTaskExit(aws, taskArn, "canary");+}++async function awaitEcsTaskExit(aws: AwsConfig, taskArn: string, kind: string): Promise<void> {+ const pollMs = envNum("QM_AWS_ROLLOUT_POLL_MS", 5_000);+ const deadline = Date.now() + envNum("QM_AWS_ROLLOUT_DEADLINE_MS", 30 * 60_000);+ for (;;) {+ const described = awsJson<{+ tasks?: Array<{+ lastStatus?: string;+ stoppedReason?: string;+ containers?: Array<{ name?: string; exitCode?: number; reason?: string }>;+ }>;+ failures?: Array<{ arn?: string; reason?: string }>;+ }>(aws, ["ecs", "describe-tasks", "--cluster", aws.cluster, "--tasks", taskArn]);+ const task = described.tasks?.[0];+ const failures = (described.failures ?? []).map((failure) => failure.reason ?? "unknown");+ if (failures.some((reason) => reason !== "MISSING")) {+ throw new CliError(`AWS ${kind} task ${taskArn} failed (${failures.join(", ")})`);+ }+ if (task?.lastStatus === "STOPPED") {+ const core = task.containers?.find((container) => container.name === "core");+ if (core?.exitCode === 0) return;+ throw new CliError(+ `AWS ${kind} task ${taskArn} exited ${core?.exitCode ?? "without a code"}: ${[core?.reason, task.stoppedReason].filter(Boolean).join("; ") || "unknown reason"}`,+ );+ }+ if (Date.now() > deadline) {+ throw new CliError(+ task+ ? `timed out waiting for the AWS ${kind} task; ${taskArn} is still ${task.lastStatus ?? "unknown"} and was left running`+ : `timed out waiting for the AWS ${kind} task; ECS still does not list ${taskArn}`,+ );+ }+ await sleep(pollMs);}}@@ -4848,7 +4856,7 @@ async function checkLive(request: (body) => transport("POST", body),});} else {- awsLiveSession(config, states.get("core")!);+ await awsLiveSession(config, states.get("core")!);}if (opts.report ?? true) step("core: private live session smoke passed");} catch (error) {diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.tsindex eba76ce35..56d9ba4e8 100644--- a/cli/test/aws.test.ts+++ b/cli/test/aws.test.ts@@ -428,8 +428,9 @@ else if (a.includes("ecs list-tasks")) console.log(JSON.stringify({ taskArns: prelse if (a.includes("ecs describe-tasks") && a.includes("task/old-core-")) console.log(JSON.stringify({ tasks: [] }));else if (a.includes("ecs describe-tasks") && a.includes("task/live-core")) console.log(JSON.stringify({ tasks: [{ taskArn: "arn:aws:ecs:us-west-2:123456789012:task/live-core", taskDefinitionArn: process.env.AWS_FAKE_STALE_CORE ? "stale-task-definition" : s.services["acme-core"].taskDefinition, lastStatus: "RUNNING", healthStatus: "HEALTHY", containers: [{ name: "core", networkInterfaces: [{ privateIpv4Address: "10.0.1.8" }] }] }] }));else if (a.includes("ecs run-task")) console.log(JSON.stringify({ tasks: [{ taskArn: "arn:aws:ecs:us-west-2:123456789012:task/canary" }] }));-else if (a.includes("ecs wait tasks-stopped")) console.log("");-else if (a.includes("ecs describe-tasks")) { const exitCode = Number(process.env.AWS_FAKE_CANARY_EXIT || "0") || ${JSON.stringify(opts.migrationExitCode ?? 0)}; console.log(JSON.stringify({ tasks: [{ stoppedReason: "Essential container in task exited", containers: [{ name: "core", exitCode, reason: process.env.AWS_FAKE_CANARY_REASON ?? (exitCode && ${JSON.stringify(Boolean(opts.migrationExitCode ?? 0))} ? "migration failed" : undefined) }] }], failures: [] })); }+else if (a.includes("ecs describe-tasks") && s.missingPolls > 0) { s.missingPolls--; save(); console.log(JSON.stringify({ tasks: [], failures: [{ arn: "arn:aws:ecs:us-west-2:123456789012:task/canary", reason: s.failureReason || "MISSING" }] })); }+else if (a.includes("ecs describe-tasks") && s.runningPolls > 0) { s.runningPolls--; save(); console.log(JSON.stringify({ tasks: [{ lastStatus: "RUNNING", containers: [{ name: "core" }] }], failures: [] })); }+else if (a.includes("ecs describe-tasks")) { const exitCode = Number(process.env.AWS_FAKE_CANARY_EXIT || "0") || ${JSON.stringify(opts.migrationExitCode ?? 0)}; console.log(JSON.stringify({ tasks: [{ lastStatus: "STOPPED", stoppedReason: "Essential container in task exited", containers: [{ name: "core", exitCode, reason: process.env.AWS_FAKE_CANARY_REASON ?? (exitCode && ${JSON.stringify(Boolean(opts.migrationExitCode ?? 0))} ? "migration failed" : undefined) }] }], failures: [] })); }else if (a.includes("ecs describe-task-definition")) {const id = after("--task-definition");console.log(JSON.stringify({ taskDefinition: s.definitions[id] }));@@ -1283,7 +1284,7 @@ test("AWS up scales services to the configured desired count and live check flagprocess.env.AWS_FAKE_CANARY_EXIT = "1";await assert.rejects(() => awsCheckLive(scaled(), { report: false }),- /core: private live session smoke failed: canary task exited 1/,+ /core: private live session smoke failed: AWS canary task arn:aws:ecs:us-west-2:123456789012:task\/canary exited 1: Essential container in task exited/,);if (priorCanaryExit === undefined) delete process.env.AWS_FAKE_CANARY_EXIT;else process.env.AWS_FAKE_CANARY_EXIT = priorCanaryExit;@@ -2837,7 +2838,6 @@ test("AWS migration runs the exact candidate core image inside the service VPC",assert.match(calls, /ecs run-task .*--launch-type FARGATE/);assert.match(calls, /subnet-a/);assert.match(calls, /src\/migrate-main\.ts/);- assert.match(calls, /ecs wait tasks-stopped/);assert.match(calls, /ecs deregister-task-definition/);assert.ok(calls.indexOf("dynamodb put-item") < calls.indexOf("ecs run-task"));assert.ok(calls.indexOf("rds describe-db-instances") < calls.indexOf("ecs run-task"));@@ -2854,6 +2854,66 @@ test("AWS migration runs the exact candidate core image inside the service VPC",}});+test("AWS migration polls a long-running task to its deadline without stopping it", async () => {+ const dir = mkdtempSync(join(tmpdir(), "qm-aws-candidate-migrate-wait-"));+ const candidatePath = join(dir, "candidate.json");+ writeFileSync(+ candidatePath,+ JSON.stringify({+ contract: 1,+ accountId: "123456789012",+ region: "us-west-2",+ label: "candidate-deadbeef",+ images: { core: `123456789012.dkr.ecr.us-west-2.amazonaws.com/qm-core@sha256:${"a".repeat(64)}` },+ imageProvenance: { core: { kind: "source-build", source: "checkout" } },+ architectures: { core: "amd64" },+ }),+ );+ const single = oneServiceConfig();+ const fake = statefulAws(dir, single);+ const setState = (patch: Record<string, unknown>): void => {+ writeFileSync(fake.state, JSON.stringify({ ...JSON.parse(readFileSync(fake.state, "utf8")), ...patch }));+ writeFileSync(fake.log, "");+ };+ const priorDeadline = process.env.QM_AWS_ROLLOUT_DEADLINE_MS;+ try {+ setState({ missingPolls: 2, runningPolls: 3 });+ await awsMigrateCandidate(single, dir, candidatePath);+ assert.equal(readFileSync(fake.log, "utf8").match(/ecs describe-tasks/g)?.length, 6);++ setState({ runningPolls: 1e9 });+ process.env.QM_AWS_ROLLOUT_DEADLINE_MS = "50";+ await assert.rejects(+ () => awsMigrateCandidate(single, dir, candidatePath),+ /task\/canary is still RUNNING and was left running/,+ );+ let calls = readFileSync(fake.log, "utf8");+ assert.doesNotMatch(calls, /ecs stop-task/);+ assert.match(calls, /ecs deregister-task-definition/);+ assert.match(calls, /dynamodb delete-item/);++ setState({ runningPolls: 0, missingPolls: 1e9 });+ await assert.rejects(+ () => awsMigrateCandidate(single, dir, candidatePath),+ /ECS still does not list arn:aws:ecs:us-west-2:123456789012:task\/canary/,+ );++ setState({ missingPolls: 1, failureReason: "ACCESS_DENIED" });+ await assert.rejects(+ () => awsMigrateCandidate(single, dir, candidatePath),+ /migration task arn:aws:ecs:us-west-2:123456789012:task\/canary failed \(ACCESS_DENIED\)/,+ );+ calls = readFileSync(fake.log, "utf8");+ assert.equal(calls.match(/ecs describe-tasks/g)?.length, 1);+ assert.match(calls, /dynamodb delete-item/);+ } finally {+ if (priorDeadline === undefined) delete process.env.QM_AWS_ROLLOUT_DEADLINE_MS;+ else process.env.QM_AWS_ROLLOUT_DEADLINE_MS = priorDeadline;+ fake.restore();+ rmSync(dir, { recursive: true, force: true });+ }+});+test("AWS builds one immutable candidate manifest and deploys its exact digest without rebuilding", async () => {const dir = mkdtempSync(join(tmpdir(), "qm-aws-candidate-"));const candidatePath = join(dir, "candidate.json");@@ -3214,7 +3274,10 @@ test("AWS migration failure deregisters the candidate task and releases the depl);const fake = statefulAws(dir, oneServiceConfig(), {}, { migrationExitCode: 1 });try {- await assert.rejects(() => awsMigrateCandidate(oneServiceConfig(), dir, candidatePath), /migration task failed/);+ await assert.rejects(+ () => awsMigrateCandidate(oneServiceConfig(), dir, candidatePath),+ /migration task arn:aws:ecs:us-west-2:123456789012:task\/canary exited 1: migration failed; Essential container in task exited/,+ );const calls = readFileSync(fake.log, "utf8");assert.match(calls, /ecs deregister-task-definition/);assert.match(calls, /dynamodb delete-item/);@@ -3246,7 +3309,7 @@ test("AWS candidate deploy migration failure preserves the runtime and releasestry {await assert.rejects(() => awsUp(oneServiceConfig(), dir, { yes: true, candidate: candidatePath }),- /migration task failed/,+ /migration task arn:aws:ecs:us-west-2:123456789012:task\/canary exited 1: migration failed; Essential container in task exited/,);const calls = readFileSync(fake.log, "utf8");assert.doesNotMatch(calls, /ecs (?:deregister-task-definition|update-service)/);diff --git a/cli/test/cli-dispatch.test.ts b/cli/test/cli-dispatch.test.tsindex 50b3c256f..0e9ca4442 100644--- a/cli/test/cli-dispatch.test.ts+++ b/cli/test/cli-dispatch.test.ts@@ -311,7 +311,7 @@ else if (args.includes("describe-task-definition")) console.log(${JSON.stringifyelse if (args.includes("list-tasks")) console.log(JSON.stringify({ taskArns: ["live-core"] }));else if (args.includes("describe-tasks") && args.includes("live-core")) console.log(JSON.stringify({ tasks: [{ taskDefinitionArn: "task", lastStatus: "RUNNING", containers: [{ name: "core", networkInterfaces: [{ privateIpv4Address: "10.0.1.8" }] }] }] }));else if (args.includes("run-task")) console.log(JSON.stringify({ tasks: [{ taskArn: "canary" }] }));-else if (args.includes("describe-tasks")) console.log(JSON.stringify({ tasks: [{ containers: [{ name: "core", exitCode: 0 }] }] }));+else if (args.includes("describe-tasks")) console.log(JSON.stringify({ tasks: [{ lastStatus: "STOPPED", containers: [{ name: "core", exitCode: 0 }] }] }));else if (args.includes("dynamodb get-item") && args.includes("deployment/current")) console.log(JSON.stringify({ Item: { manifestId: { S: "manifest" } } }));else if (args.includes("dynamodb get-item") && args.includes("deployment/manifest/manifest")) console.log(JSON.stringify({ Item: { manifest: { S: ${JSON.stringify(JSON.stringify(manifest))} } } }));else if (args.includes("s3api get-object")) fs.writeFileSync(argv[argv.indexOf("--key") + 2], ${JSON.stringify(layerBody)});