Multiplayer agent harness for work.
Confirm ownership mutations and fence automatic compensation (#1472)
Regan Bell73f73c5445e9
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.tsindex bc0115c44..5367aa0f0 100644--- a/cli/src/backends/aws.ts+++ b/cli/src/backends/aws.ts@@ -3484,12 +3484,13 @@ export async function awsSetBackgroundWork(configDir: string,enabled: boolean,candidatePath?: string,-): Promise<void> {+ expectedOwnership?: Pick<BackgroundWorkStatus, "generation" | "lastRequestId">,+): Promise<BackgroundWorkStatus | undefined> {const { aws, workloads } = awsTopology(config, configDir);if (!workloads.includes("core")) throw new CliError("background work requires the core workload");const candidate = candidatePath ? releaseCandidate(config, candidatePath) : undefined;assertAwsCallerAccount(aws);- await withAwsLease(aws, async () => {+ const confirmed = await withAwsLease(aws, async () => {const current = currentDeploymentManifest(aws);if (!current) throw new CliError("background work requires a recorded deployment");const states = describedServices(config, workloads);@@ -3532,26 +3533,35 @@ export async function awsSetBackgroundWork(const cohort = await awsBackgroundCohort(config, configDir, candidatePath);const transport = awsBackgroundWorkTransport(config);let status = await readBackgroundWork(transport, cohort.deploymentId);+ if (+ expectedOwnership &&+ (status.generation !== expectedOwnership.generation || status.lastRequestId !== expectedOwnership.lastRequestId)+ )+ throw new CliError("background ownership changed since promotion; refusing automatic compensation");if (!status.enabled)throw new CliError("explicitly bootstrap all background ownership cohorts before changing ownership");if (!enabled && status.desiredDeploymentId !== null && status.desiredDeploymentId !== cohort.deploymentId)throw new CliError("cannot disable background work on a different deployment's current owner");const desiredDeploymentId = enabled ? cohort.deploymentId : null;if (status.desiredDeploymentId !== desiredDeploymentId) {- status = await mutateBackgroundWork(- transport,- cohort.deploymentId,- backgroundWorkMutation(status.generation, desiredDeploymentId),- );+ status = await mutateBackgroundWork(transport, cohort.deploymentId, {+ ...backgroundWorkMutation(status.generation, desiredDeploymentId),+ ...(expectedOwnership ? { expectedLastRequestId: expectedOwnership.lastRequestId } : {}),+ });}- await awaitBackgroundWork(+ return awaitBackgroundWork(transport,cohort.deploymentId,- { generation: status.generation, desiredDeploymentId, taskArns: enabled ? cohort.taskArns : [] },+ {+ generation: status.generation,+ desiredDeploymentId,+ taskArns: enabled ? cohort.taskArns : [],+ lastRequestId: status.lastRequestId,+ },{ timeoutMs: envNum("QM_AWS_ROLLOUT_DEADLINE_MS", 30 * 60_000), pollMs: 1000 },);- return;}+ if (expectedOwnership) throw new CliError("ownership preconditions require controlled background work");if (current.backgroundDeploymentId)throw new CliError("controlled background work cannot fall back to task replacement");const desired = taskDefinitionForBackgroundWork(coreTask!, enabled);@@ -3614,6 +3624,7 @@ export async function awsSetBackgroundWork(}});ok(`background work ${enabled ? "enabled" : "disabled"}`);+ return confirmed;}function envValues(configDir: string, path: string | undefined): Map<string, string> {diff --git a/cli/src/background-work.ts b/cli/src/background-work.tsindex 1d7e50508..c65ec6edc 100644--- a/cli/src/background-work.ts+++ b/cli/src/background-work.ts@@ -32,7 +32,7 @@ export type BackgroundWorkMutation = {expectedGeneration: number;requestId: string;} & (- | { desiredDeploymentId: string | null; bootstrapTaskArns?: string[] }+ | { desiredDeploymentId: string | null; bootstrapTaskArns?: string[]; expectedLastRequestId?: string | null }| { terminatedMembers: Array<Pick<BackgroundWorkMember, "instanceId" | "taskArn" | "generation">> });@@ -136,25 +136,33 @@ export async function mutateBackgroundWork(): Promise<BackgroundWorkStatus> {const body = JSON.stringify(mutation);let response: { status: number; body: string } | undefined;- try {- response = await transport("POST", body);- } catch {- response = undefined;- }- if (response?.status === 200) {+ for (let attempt = 0; attempt < 3; attempt++) {try {- const state = parseBackgroundWorkStatus(response.body, deploymentId);- if (mutationCommitted(state, mutation)) return state;+ response = await transport("POST", body);} catch {response = undefined;}+ if (response?.status === 200) {+ try {+ const state = parseBackgroundWorkStatus(response.body, deploymentId);+ if (mutationCommitted(state, mutation)) return state;+ } catch {+ response = undefined;+ }+ }+ let observed: BackgroundWorkStatus | undefined;+ try {+ observed = await readBackgroundWork(transport, deploymentId);+ } catch {+ observed = undefined;+ }+ if (observed && mutationCommitted(observed, mutation)) return observed;+ if (observed && observed.generation !== mutation.expectedGeneration)+ throw new CliError("background ownership changed concurrently; refusing to replace another ownership generation");+ if (response && response.status >= 400 && response.status < 500 && response.status !== 429) break;}- const observed = await readBackgroundWork(transport, deploymentId);- if (mutationCommitted(observed, mutation)) return observed;- if (observed.generation !== mutation.expectedGeneration)- throw new CliError("background ownership changed concurrently; refusing to replace another ownership generation");throw new CliError(- `background ownership mutation is unconfirmed${response ? ` (HTTP ${response.status})` : ""}; retry the same request ID ${mutation.requestId} after reading ownership`,+ `background ownership mutation is unconfirmed${response ? ` (HTTP ${response.status})` : ""}; retry the same request ID ${mutation.requestId} after reading ownership; automatic compensation is unsafe`,);}@@ -168,7 +176,12 @@ export function backgroundWorkMutation(export async function awaitBackgroundWork(transport: BackgroundWorkTransport,deploymentId: string,- expected: { generation: number; desiredDeploymentId: string | null; taskArns: string[] },+ expected: {+ generation: number;+ desiredDeploymentId: string | null;+ taskArns: string[];+ lastRequestId?: string | null;+ },options: { timeoutMs: number; pollMs: number },): Promise<BackgroundWorkStatus> {const deadline = Date.now() + options.timeoutMs;@@ -177,7 +190,8 @@ export async function awaitBackgroundWork(if (!state.enabled ||state.generation !== expected.generation ||- state.desiredDeploymentId !== expected.desiredDeploymentId+ state.desiredDeploymentId !== expected.desiredDeploymentId ||+ (expected.lastRequestId !== undefined && state.lastRequestId !== expected.lastRequestId)) {throw new CliError("background ownership changed while awaiting acknowledgment");}diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.tsindex 2fa4875fa..306f71d72 100644--- a/cli/test/aws.test.ts+++ b/cli/test/aws.test.ts@@ -6040,8 +6040,20 @@ test("controlled AWS cohorts bind immutable identities and hand over without ECSawait assert.rejects(awsSetBackgroundWork(single, dir, false), /different deployment/);assert.equal(mutations.length, beforeWrongPause);ownership.desiredDeploymentId = manifest.backgroundDeploymentId;- await awsSetBackgroundWork(single, dir, false);- await awsSetBackgroundWork(single, dir, true);+ const beforeCompensation = mutations.length;+ for (const expected of [+ { generation: ownership.generation - 1, lastRequestId: ownership.lastRequestId },+ { generation: ownership.generation, lastRequestId: "different-request" },+ ]) {+ await assert.rejects(awsSetBackgroundWork(single, dir, false, undefined, expected), /changed since promotion/);+ }+ assert.equal(mutations.length, beforeCompensation);+ await awsSetBackgroundWork(single, dir, false, undefined, {+ generation: ownership.generation,+ lastRequestId: ownership.lastRequestId,+ });+ const confirmed = await awsSetBackgroundWork(single, dir, true);+ assert.equal(confirmed?.generation, 3);assert.equal(ownership.generation, 3);assert.equal(mutations.length, 4);assert.doesNotMatch(readFileSync(fake.log, "utf8"), /ecs update-service|register-task-definition|run-task/);diff --git a/cli/test/background-work.test.ts b/cli/test/background-work.test.tsindex ee34d5438..bdc5674f7 100644--- a/cli/test/background-work.test.ts+++ b/cli/test/background-work.test.ts@@ -133,3 +133,60 @@ test("pause never infers unacknowledged owners dead and refuses concurrent gener/changed while awaiting/,);});++for (const mode of ["late-commit", "unavailable-read", "never-commits", "competitor", "rejected"] as const) {+ test(`mutation confirmation handles ${mode} without changing its request`, async () => {+ const mutation = { expectedGeneration: 1, desiredDeploymentId: "new-cohort", requestId: "our-request" };+ let posts = 0;+ let reads = 0;+ const old = {+ ...state(),+ generation: 1,+ desiredDeploymentId: "old-cohort",+ lastRequestId: "previous",+ members: state().members.map((member) => ({ ...member, generation: 1 })),+ };+ const transport: BackgroundWorkTransport = async (method, body) => {+ if (method === "POST") {+ posts++;+ assert.equal(body, JSON.stringify(mutation));+ if (mode === "rejected") return { status: 403, body: "denied" };+ if (posts > 1 && (mode === "late-commit" || mode === "unavailable-read")) return response(state());+ throw new Error("response timed out before commit");+ }+ reads++;+ if (mode === "unavailable-read") throw new Error("temporarily unavailable");+ if (mode === "competitor") return response({ ...state(), lastRequestId: "competitor" });+ return response(old);+ };+ if (mode === "late-commit" || mode === "unavailable-read") {+ assert.equal((await mutateBackgroundWork(transport, "new-cohort", mutation)).generation, 2);+ assert.equal(posts, 2);+ assert.equal(reads, 1);+ } else {+ await assert.rejects(+ mutateBackgroundWork(transport, "new-cohort", mutation),+ mode === "competitor" ? /changed concurrently/ : /unconfirmed.*automatic compensation is unsafe/,+ );+ assert.equal(posts, mode === "never-commits" ? 3 : 1);+ }+ });+}++test("readiness cannot replace the confirmed mutation identity with a same-generation retirement", async () => {+ const observed = { ...state(), lastRequestId: "operator-retirement" };+ await assert.rejects(+ awaitBackgroundWork(+ async () => response(observed),+ "new-cohort",+ {+ generation: 2,+ desiredDeploymentId: "new-cohort",+ taskArns: ["new-task"],+ lastRequestId: "our-request",+ },+ { timeoutMs: 0, pollMs: 1 },+ ),+ /changed while awaiting/,+ );+});diff --git a/src/api/routes/background-work.ts b/src/api/routes/background-work.tsindex 81ea72f67..7d4a8dbaf 100644--- a/src/api/routes/background-work.ts+++ b/src/api/routes/background-work.ts@@ -94,8 +94,19 @@ async function backgroundWork(ctx: ApiCtx): Promise<void> {);}if (- !keys(body, ["expectedGeneration", "requestId", "desiredDeploymentId", "bootstrapTaskArns"]) ||+ !keys(body, [+ "expectedGeneration",+ "requestId",+ "desiredDeploymentId",+ "bootstrapTaskArns",+ "expectedLastRequestId",+ ]) ||!(body.desiredDeploymentId === null || identity(body.desiredDeploymentId)) ||+ !(+ body.expectedLastRequestId === undefined ||+ body.expectedLastRequestId === null ||+ identity(body.expectedLastRequestId)+ ) ||(body.bootstrapTaskArns !== undefined &&(!Array.isArray(body.bootstrapTaskArns) ||body.bootstrapTaskArns.length < 1 ||@@ -110,6 +121,7 @@ async function backgroundWork(ctx: ApiCtx): Promise<void> {expectedGeneration: body.expectedGeneration,requestId: body.requestId,desiredDeploymentId: body.desiredDeploymentId,+ ...(body.expectedLastRequestId !== undefined ? { expectedLastRequestId: body.expectedLastRequestId } : {}),...(body.bootstrapTaskArns ? { bootstrapTaskArns: body.bootstrapTaskArns as string[] } : {}),}),);diff --git a/src/runs/background-ownership.ts b/src/runs/background-ownership.tsindex 0dedd5ba9..80f487aae 100644--- a/src/runs/background-ownership.ts+++ b/src/runs/background-ownership.ts@@ -23,6 +23,7 @@ export interface BackgroundTransition {expectedGeneration: number;requestId: string;desiredDeploymentId: string | null;+ expectedLastRequestId?: string | null;bootstrapTaskArns?: string[];}@@ -92,6 +93,7 @@ export function createBackgroundOwnershipStore(map: DurableMap<BackgroundOwnershrequest.expectedGeneration,request.desiredDeploymentId,request.bootstrapTaskArns?.slice().sort() ?? null,+ ...(request.expectedLastRequestId !== undefined ? [request.expectedLastRequestId] : []),]);return update((state) => {if (state.lastRequestId === request.requestId) {@@ -104,6 +106,8 @@ export function createBackgroundOwnershipStore(map: DurableMap<BackgroundOwnershreturn;}expectGeneration(state, request.expectedGeneration);+ if (request.expectedLastRequestId !== undefined && state.lastRequestId !== request.expectedLastRequestId)+ throw new BackgroundOwnershipConflict("Background ownership request changed");if (!state.enabled) {const expected = request.bootstrapTaskArns;if (!expected?.length || new Set(expected).size !== expected.length)diff --git a/test/background-ownership.test.ts b/test/background-ownership.test.tsindex f1e6879bc..2bd1a26cd 100644--- a/test/background-ownership.test.ts+++ b/test/background-ownership.test.ts@@ -97,3 +97,26 @@ test("pause has no successor and failed admissions never mutate ownership", asyn}assert.ok((await store.get()).members.every((member) => member.state === "drained"));});++test("compensation fences a same-generation retirement and replays only the exact precondition", async () => {+ const { store, bootstrap } = await fixture();+ await store.transition(bootstrap);+ const observed = await store.get();+ const compensation = {+ expectedGeneration: observed.generation,+ expectedLastRequestId: observed.lastRequestId,+ requestId: "compensation",+ desiredDeploymentId: "b",+ };+ await store.retire({+ expectedGeneration: observed.generation,+ requestId: "operator-retirement",+ terminatedMembers: [{ instanceId: "a2", taskArn: "task:a2", generation: 0 }],+ });+ await assert.rejects(store.transition(compensation), /request changed/);+ assert.equal((await store.get()).generation, 1);+ const current = { ...compensation, expectedLastRequestId: "operator-retirement" };+ assert.equal((await store.transition(current)).generation, 2);+ assert.equal((await store.transition(current)).generation, 2);+ await assert.rejects(store.transition(compensation), /identity reused/);+});diff --git a/test/background-work-routes.test.ts b/test/background-work-routes.test.tsindex d785b3d4f..78658cab2 100644--- a/test/background-work-routes.test.ts+++ b/test/background-work-routes.test.ts@@ -158,3 +158,31 @@ test("malformed or mixed mutations cannot change ownership", async () => {await srv.close();}});++test("compensation request preconditions are enforced atomically through the authenticated route", async () => {+ const srv = await fixture();+ try {+ const promotion = transition();+ assert.equal((await srv.request("POST", promotion)).status, 200);+ const compensation = {+ expectedGeneration: 1,+ expectedLastRequestId: promotion.requestId,+ requestId: randomUUID(),+ desiredDeploymentId: null,+ };+ const retirement = {+ expectedGeneration: 1,+ requestId: randomUUID(),+ terminatedMembers: [{ instanceId: "instance-a", taskArn: "task-a", generation: 0 }],+ };+ assert.equal((await srv.request("POST", retirement)).status, 200);+ assert.equal((await srv.request("POST", compensation)).status, 409);+ assert.equal((await srv.request("POST", { ...compensation, expectedLastRequestId: 123 })).status, 400);+ const current = { ...compensation, expectedLastRequestId: retirement.requestId };+ assert.equal((await srv.request("POST", current)).status, 200);+ assert.equal((await srv.request("POST", current)).status, 200);+ assert.equal((await srv.store.get()).generation, 2);+ } finally {+ await srv.close();+ }+});diff --git a/test/postgres-background-ownership.test.ts b/test/postgres-background-ownership.test.tsindex 130f7a4bc..de43d4d9b 100644--- a/test/postgres-background-ownership.test.ts+++ b/test/postgres-background-ownership.test.ts@@ -91,3 +91,79 @@ test(}},);++test(+ "delayed ownership commit after an old read is confirmed by replaying the same mutation",+ { skip: !databaseUrl, timeout: 20_000 },+ async () => {+ const { mutateBackgroundWork } = await import("../cli/src/background-work.ts");+ const table = `background_test_${randomUUID().replaceAll("-", "")}`;+ const factory = createPostgresMapFactory(databaseUrl!);+ const store = createBackgroundOwnershipStore(factory.map<BackgroundOwnership>(table));+ const pool = await factory.pool.pool();+ const blocker = await pool.connect();+ let first: Promise<BackgroundOwnership> | undefined;+ try {+ await store.register({ instanceId: "a", deploymentId: "a", taskArn: "task:a" });+ await store.transition({+ expectedGeneration: 0,+ requestId: randomUUID(),+ desiredDeploymentId: "a",+ bootstrapTaskArns: ["task:a"],+ });+ await blocker.query("BEGIN");+ await blocker.query("SELECT * FROM durable_map_versions WHERE tbl = $1 FOR UPDATE", [table]);+ const mutation = { expectedGeneration: 1, requestId: randomUUID(), desiredDeploymentId: "a" };+ let posts = 0;+ let oldReads = 0;+ const result = await mutateBackgroundWork(+ async (method, body) => {+ if (method === "POST") {+ posts++;+ assert.equal(body, JSON.stringify(mutation));+ if (posts === 1) {+ first = store.transition(mutation);+ throw new Error("client timeout while server transaction is pending");+ }+ await blocker.query("COMMIT");+ await first;+ const committed = await store.transition(mutation);+ return {+ status: 200,+ body: JSON.stringify({ ...committed, protocol: 1, deploymentId: "a", instanceId: "a" }),+ };+ }+ const old = await store.get();+ assert.equal(old.generation, 1);+ oldReads++;+ return { status: 200, body: JSON.stringify({ ...old, protocol: 1, deploymentId: "a", instanceId: "a" }) };+ },+ "a",+ mutation,+ );+ assert.equal(result.generation, 2);+ assert.equal(posts, 2);+ assert.equal(oldReads, 1);+ assert.equal((await store.get()).generation, 2);+ const precondition = {+ expectedGeneration: 2,+ expectedLastRequestId: mutation.requestId,+ requestId: randomUUID(),+ desiredDeploymentId: null,+ };+ await store.retire({+ expectedGeneration: 2,+ requestId: randomUUID(),+ terminatedMembers: [{ instanceId: "a", taskArn: "task:a", generation: 0 }],+ });+ await assert.rejects(store.transition(precondition), /request changed/);+ assert.equal((await store.get()).generation, 2);+ } finally {+ await blocker.query("ROLLBACK");+ blocker.release();+ await first?.catch(() => {});+ await pool.query(`DROP TABLE IF EXISTS ${table}`);+ await factory.pool.close();+ }+ },+);