iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / test / deploy-prd.mjsmain at aacbc74

// deploy-prd.mjs — the production deploy refuses a tree that is not a clean commit of origin/main,
// reads the live commit from a deployment's message, lists what a deploy releases, and uploads
// the approved commit over the approved live version alone, under its own lock (scripts/deploy-prd.mjs).
// It tells a partial rollout (the Worker of one commit, the Deployer's image of another) from a
// whole one, refuses to call it "already live", and repairs it on `--repair-image` alone. Each case is a
// real git repository in a temporary folder; no case calls Cloudflare, builds or uploads.
// Run: node test/deploy-prd.mjs
import assert from "node:assert/strict";
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { closeSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import {
  deploy,
  faultsOf,
  guardOf,
  imageOf,
  liveOf,
  releaseOf,
  releasedBetween,
  takeLock,
} from "../scripts/deploy-prd.mjs";

const script = fileURLToPath(new URL("../scripts/deploy-prd.mjs", import.meta.url));
/** macOS has no `flock`: the deploy needs it, and the cases that take a lock are skipped there. */
const noFlock = spawnSync("flock", ["--version"]).status !== 0;

/** When the fixtures' uploads happened, as Cloudflare writes a time. */
const DAY_BEFORE = "2026-11-26T17:40:00.123456Z";
const TODAY = "2026-11-27T07:09:30.654321Z";

/** A deployment that serves one version at 100%, as Cloudflare lists it. */
const upload = (version, commit, at = DAY_BEFORE) => ({
  id: `deployment-of-${version}`,
  versions: [{ version_id: version, percentage: 100 }],
  annotations: { "workers/message": `main ${commit}`, "workers/triggered_by": "upload" },
  created_on: at,
});
/** The digest that the fixtures' registry holds under the tag of the version `version`. */
const digestOf = (version) => `sha256:${Buffer.from(version).toString("hex").padEnd(64, "0")}`;
/** The Deployer's application as `api.image` answers it: it runs the image that the upload of
 *  the version `owner` pushed. The registry holds a tag for every version but those in `untagged`. */
const running = (owner, status = "completed", untagged = []) => ({
  application: {
    id: "app",
    version: 61,
    configuration: { image: `registry/deployer@${digestOf(owner)}` },
  },
  rollouts: [{ id: "rollout-1", status }],
  digests: new Proxy(
    {},
    { get: (_, version) => (untagged.includes(version) ? null : digestOf(version)) },
  ),
});
/** An image that the newest deployment's version pushed: in step with what is live. */
const NEWEST = (deployments) => running(deployments[0].versions[0].version_id);
/** A deployment that splits the traffic between two versions. */
const split = (first, second, commit) => ({
  id: `split-${first}-${second}`,
  versions: [
    { version_id: first, percentage: 90 },
    { version_id: second, percentage: 10 },
  ],
  annotations: { "workers/message": `main ${commit}`, "workers/triggered_by": "upload" },
});

/** A clone with one commit on main that its origin has, and `git` to run in it. */
function clone(t) {
  const root = mkdtempSync(join(tmpdir(), "deploy-prd-"));
  t.after(() => rmSync(root, { recursive: true, force: true }));
  const at = join(root, "clone");
  const git = (...args) =>
    execFileSync(
      "git",
      [
        "-c",
        "user.name=test",
        "-c",
        "user.email=test@example.com",
        "-c",
        "commit.gpgsign=false",
        ...args,
      ],
      { cwd: at, encoding: "utf8" },
    ).trim();
  execFileSync("git", [
    "init",
    "--quiet",
    "--bare",
    "--initial-branch=main",
    join(root, "origin.git"),
  ]);
  execFileSync("git", ["clone", "--quiet", join(root, "origin.git"), at], { stdio: "ignore" });
  const commit = (file, subject) => {
    writeFileSync(join(at, file), subject);
    git("add", file);
    git("commit", "--quiet", "--no-verify", "-m", subject);
    return git("rev-parse", "HEAD");
  };
  git("checkout", "--quiet", "-B", "main");
  const first = commit("a.txt", "first");
  git("push", "--quiet", "origin", "main");
  return { at, git, commit, first };
}

test("a clean commit of origin/main may be released", (t) => {
  const { at, first } = clone(t);
  assert.equal(releaseOf(at), first);
});

test("a commit that origin/main does not have is refused: an unmerged branch, and main ahead of its origin", (t) => {
  const { at, git, commit } = clone(t);
  git("checkout", "--quiet", "-b", "feature");
  commit("b.txt", "not merged");
  assert.throws(() => releaseOf(at), /REFUSED: [0-9a-f]{40} is not a commit of origin\/main/);
  git("checkout", "--quiet", "main");
  commit("c.txt", "not pushed");
  assert.throws(() => releaseOf(at), /is not a commit of origin\/main/);
});

test("a tree with a change that is not committed is refused", (t) => {
  const { at } = clone(t);
  writeFileSync(join(at, "a.txt"), "edited by hand");
  assert.throws(() => releaseOf(at), /REFUSED: the tree is not clean/);
});

test("an older commit of origin/main may be released: that is a way back", (t) => {
  const { at, git, commit, first } = clone(t);
  commit("b.txt", "second");
  git("push", "--quiet", "origin", "main");
  git("checkout", "--quiet", "--detach", first);
  assert.equal(releaseOf(at), first);
});

test("the live commit is the one of the upload that made the live version, also after a rollback and a secret's change", () => {
  const [a, b] = ["a".repeat(40), "b".repeat(40)];
  const secret = (version) => ({
    versions: [{ version_id: version, percentage: 100 }],
    annotations: { "workers/triggered_by": "secret" },
  });
  // B is live
  assert.deepEqual(liveOf([upload("vB", b), upload("vA", a)]), { version: "vB", commit: b });
  // a secret's change makes a new version of B's code, with no message
  assert.deepEqual(liveOf([secret("vS", b), upload("vB", b), upload("vA", a)]), {
    version: "vS",
    commit: b,
  });
  // a rollback from B to A deploys A's version again under its own message: A is live, and a
  // deploy of C then releases what lies between A and C, B's commits too
  const rollback = {
    versions: [{ version_id: "vA", percentage: 100 }],
    annotations: { "workers/message": "faults after the deploy" },
  };
  assert.deepEqual(liveOf([rollback, upload("vB", b), upload("vA", a)]), {
    version: "vA",
    commit: a,
  });
  assert.deepEqual(liveOf([secret("vS2"), rollback, upload("vB", b), upload("vA", a)]), {
    version: "vS2",
    commit: a,
  });
  // an upload that this script did not make names no commit
  assert.deepEqual(
    liveOf([
      {
        versions: [{ version_id: "v0", percentage: 100 }],
        annotations: { "workers/message": "Automatic deployment on upload." },
      },
    ]),
    { version: "v0", commit: null },
  );
});

test("a deploy says which commits it releases, or that it cannot know", (t) => {
  const { at, git, commit, first } = clone(t);
  const second = commit("b.txt", "second");
  assert.match(
    releasedBetween(at, first, second)[0],
    /releases 0 commits to the Worker's own code \(1 commits of main in all/,
  );
  assert.match(
    releasedBetween(at, null, second).join("\n"),
    /NOT KNOWN: which commits this deploy releases/,
  );
  assert.match(releasedBetween(at, "c".repeat(40), second)[0], /this clone does not have/);
  assert.match(releasedBetween(at, second, second)[0], /NOTHING TO RELEASE/);
  git("checkout", "--quiet", "--detach", first);
  assert.match(releasedBetween(at, second, first)[0], /THIS DEPLOY GOES BACK/);
});

test("the log check names an error line and a thrown invocation, and counts the invocations", async () => {
  const asked = [];
  const api = {
    count: async (from, to, filters) => {
      asked.push(filters.map((filter) => filter.key || "line"));
      const [first] = filters;
      if (first.key === "$metadata.type") return [[376]];
      if (first.key === "$metadata.level") return [['"undefined" is not valid JSON', 33]];
      return [["Outbox", "alarm", 33]];
    },
  };
  assert.deepEqual(await faultsOf(api, 1, 2), {
    invocations: 376,
    faults: ['33 × error: "undefined" is not valid JSON', "33 × threw: Outbox alarm"],
  });
  assert.deepEqual(asked, [["$metadata.type"], ["$metadata.level", "line"], ["$workers.outcome"]]);
});

test("a Worker that does not serve one version at 100% has no live version: a split is refused", () => {
  const [a, b] = ["a".repeat(40), "b".repeat(40)];
  const refused = /REFUSED: the Worker does not serve one version at 100%/;
  // the split's first version is B, and B is not what every request gets
  assert.throws(() => liveOf([split("vB", "vA", b), upload("vA", a)]), refused);
  assert.throws(() => liveOf([split("vB", "vA", b), upload("vA", a)]), /vB at 90%, vA at 10%/);
  // one version at less than 100%, a version with no percentage, and no version
  const one = (versions) => [{ id: "d", versions, annotations: {} }];
  assert.throws(() => liveOf(one([{ version_id: "vB", percentage: 50 }])), refused);
  assert.throws(() => liveOf(one([{ version_id: "vB" }])), refused);
  assert.throws(() => liveOf(one([])), /serves no version/);
  assert.throws(() => liveOf([]), /REFUSED: the Worker has no deployment/);
  // a secret's change over a split: the code under it is not one version
  const secret = {
    id: "s",
    versions: [{ version_id: "vS", percentage: 100 }],
    annotations: { "workers/triggered_by": "secret" },
  };
  assert.throws(() => liveOf([secret, split("vB", "vA", b), upload("vA", a)]), refused);
  // an older split is history: B is live at 100% now. A split is not the upload of one version,
  // so it does not name the commit of B, and the upload of B alone does
  assert.deepEqual(liveOf([upload("vB", b), split("vA", "vB", a), upload("vA", a)]), {
    version: "vB",
    commit: b,
  });
  const promoted = {
    id: "p",
    versions: [{ version_id: "vB", percentage: 100 }],
    annotations: { "workers/message": "to 100%" },
  };
  assert.deepEqual(liveOf([promoted, split("vA", "vB", b), upload("vA", a)]), {
    version: "vB",
    commit: null,
  });
});

test("the guard lets an upload go on over the approved version alone, when the live commit lies behind", (t) => {
  const { at, git, commit, first } = clone(t);
  const second = commit("b.txt", "second");
  const guard = (deployments, head, expected) => () => guardOf(at, deployments, head, expected);
  assert.equal(guardOf(at, [upload("vA", first)], second, "vA"), "behind");
  assert.equal(guardOf(at, [upload("vB", second), upload("vA", first)], second, "vB"), "same");
  // a missing guard
  assert.throws(
    guard([upload("vA", first)], second, undefined),
    /REFUSED: no approved live version/,
  );
  assert.throws(guard([upload("vA", first)], second, ""), /REFUSED: no approved live version/);
  // drift: another deploy since the plan, also one of this same commit
  assert.throws(
    guard([upload("vB", first), upload("vA", first)], second, "vA"),
    /REFUSED: the live version is vB, and this deploy was approved over vA/,
  );
  assert.throws(
    guard([upload("vB", second), upload("vA", first)], second, "vA"),
    /REFUSED: the live version is vB/,
  );
  // a split, also when its first version is the approved one
  assert.throws(
    guard([split("vA", "vB", first), upload("vA", first)], second, "vA"),
    /REFUSED: the Worker does not serve one version at 100%/,
  );
  // unknown ancestry: no commit named, a commit this clone does not have, a commit not behind
  const byHand = { ...upload("vA", first), annotations: { "workers/message": "by hand" } };
  assert.throws(
    guard([byHand], second, "vA"),
    /REFUSED: it is not known what this deploy releases.\n.*names no commit/,
  );
  assert.throws(
    guard([upload("vA", "c".repeat(40))], second, "vA"),
    /REFUSED: it is not known[^]*this clone does not have/,
  );
  assert.throws(
    guard([upload("vB", second)], first, "vB"),
    /REFUSED: it is not known[^]*THIS DEPLOY GOES BACK/,
  );
  git("checkout", "--quiet", "-b", "other", first);
  const aside = commit("c.txt", "aside");
  assert.throws(guard([upload("vB", second)], aside, "vB"), /THIS DEPLOY GOES BACK/);
});

/** A deploy in a clone whose main has a second commit, with each step written to `steps`.
 *  `reads` are the answers of the deployments' reads, in order (a missing answer is a read that
 *  fails). `approved` picks the approved commit: the second one unless a case says otherwise. */
function deployIn(
  t,
  {
    reads,
    expected,
    approved = (first, head) => head,
    build = () => {},
    upload = () => {},
    verify = async () => true,
    // the answers of the image's reads, in order; the last one is every later read's too. A
    // missing answer is a read that fails. Unless a case says otherwise the image is in step.
    images = () => [NEWEST],
    repair = false,
  },
) {
  const made = clone(t);
  const head = made.commit("b.txt", "second");
  made.git("push", "--quiet", "origin", "main");
  const steps = [];
  const answers = reads(made.first, head);
  const imageAnswers = images(made.first, head);
  let imageReads = 0;
  const done = deploy({
    repair,
    lock: "heavy.lock",
    settle: { tries: 3, pauseMs: 0 },
    api: {
      image: async (deployments) => {
        const answer = imageAnswers[Math.min(imageReads, imageAnswers.length - 1)];
        imageReads += 1;
        if (!answer) throw new Error("Cloudflare /containers/applications: 403");
        return typeof answer === "function" ? answer(deployments) : answer;
      },
      deployments: async () => {
        steps.push("read");
        // the read after the image settled answers as the read after the upload did, unless a
        // case gives a fourth answer
        const at = steps.filter((step) => step === "read").length - 1;
        const answer = answers[at] || (at === 3 && answers[2]);
        if (!answer) throw new Error("Cloudflare /deployments: 500");
        return answer;
      },
    },
    cwd: made.at,
    commit: approved(made.first, head),
    expected,
    build: (commit) => {
      steps.push(`build ${commit === head}`);
      build(made);
    },
    upload: (commit) => {
      steps.push(`upload ${commit === head}`);
      upload();
    },
    verify: (from, before) => {
      steps.push(`verify ${from <= Date.now()} ${before}`);
      return verify();
    },
  });
  return { done, steps, head, ...made };
}

/** What an error after the upload began says first: every error before it lacks these words. */
const NOT_VERIFIED = /^UPLOAD ATTEMPTED, LIVE STATE NOT VERIFIED: /;
/** Rejects with `refused`, and the words say that nothing was uploaded. */
async function refusedBeforeUpload(done, refused) {
  await assert.rejects(done, (error) => {
    assert.match(error.message, refused);
    assert.doesNotMatch(error.message, NOT_VERIFIED);
    return true;
  });
}

test("the approved path: the live version is read before the build, again right before the upload, and after it", async (t) => {
  const { done, steps } = deployIn(t, {
    expected: "vA",
    reads: (first, head) => [
      [upload("vA", first)],
      [upload("vA", first)],
      [upload("vB", head), upload("vA", first)],
    ],
  });
  assert.deepEqual(await done, { version: "vB", well: true });
  assert.deepEqual(steps, [
    "read",
    "build true",
    "read",
    "upload true",
    "read",
    "read",
    "verify true vA",
  ]);
});

test("after a good upload, a log that shows a fault is an answer, and a log that cannot be read is an upload not verified", async (t) => {
  const reads = (first, head) => [
    [upload("vA", first)],
    [upload("vA", first)],
    [upload("vB", head), upload("vA", first)],
  ];
  const fault = deployIn(t, { expected: "vA", reads, verify: async () => false });
  assert.deepEqual(await fault.done, { version: "vB", well: false });
  // Cloudflare answers the log query with 429, or the network fails: production has changed
  const unread = deployIn(t, {
    expected: "vA",
    reads,
    verify: async () => {
      throw new Error("Cloudflare /workers/observability/telemetry/query: 429");
    },
  });
  await assert.rejects(unread.done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(error.message, /telemetry\/query: 429/);
    return true;
  });
  assert.equal(unread.steps.at(-1), "verify true vA");
});

test("a commit that is live already at 100% is no deploy: nothing is built or uploaded", async (t) => {
  const { done, steps } = deployIn(t, {
    expected: "vB",
    reads: (first, head) => [[upload("vB", head), upload("vA", first)]],
  });
  assert.equal(await done, null);
  assert.deepEqual(steps, ["read"]);
});

test("the tree must be at the approved commit: a plan of one commit does not approve another", async (t) => {
  const reads = (first) => [[upload("vA", first)], [upload("vA", first)]];
  // the plan was made at the first commit, and the clean tree is now at the second, merged too
  const other = deployIn(t, { expected: "vA", reads, approved: (first) => first });
  await refusedBeforeUpload(
    other.done,
    /REFUSED: the tree is at [0-9a-f]{40}, and the approved commit is [0-9a-f]{40}/,
  );
  assert.deepEqual(other.steps, []);
  for (const approved of [() => undefined, () => "", (first, head) => head.slice(0, 12)]) {
    const none = deployIn(t, { expected: "vA", reads, approved });
    await refusedBeforeUpload(none.done, /REFUSED: no approved commit/);
    assert.deepEqual(none.steps, []);
  }
  // the tree moved to a newer merged commit during the build
  const moved = deployIn(t, {
    expected: "vA",
    reads,
    build: ({ commit, git }) => {
      commit("c.txt", "third");
      git("push", "--quiet", "origin", "main");
    },
  });
  await refusedBeforeUpload(moved.done, /REFUSED: the tree is at .* the approved commit is/);
  assert.deepEqual(moved.steps, ["read", "build true"]);
  const edited = deployIn(t, {
    expected: "vA",
    reads,
    build: ({ at }) => writeFileSync(join(at, "a.txt"), "edited during the build"),
  });
  await refusedBeforeUpload(edited.done, /REFUSED: the tree is not clean/);
  assert.deepEqual(edited.steps, ["read", "build true"]);
});

test("refused before the build: no approved version, drift, a split, unknown ancestry", async (t) => {
  const cases = [
    [undefined, (first) => [[upload("vA", first)]], /no approved live version/],
    ["vA", (first) => [[upload("vX", first), upload("vA", first)]], /the live version is vX/],
    ["vA", (first, head) => [[split("vA", "vB", head)]], /does not serve one version at 100%/],
    // the split's first version was built from this commit: that is no "live already"
    ["vB", (first, head) => [[split("vB", "vA", head)]], /does not serve one version at 100%/],
    ["vA", () => [[upload("vA", "c".repeat(40))]], /it is not known what this deploy releases/],
  ];
  for (const [expected, reads, refused] of cases) {
    const { done, steps } = deployIn(t, { expected, reads });
    await refusedBeforeUpload(done, refused);
    assert.deepEqual(steps, ["read"]);
  }
});

test("refused after the build, right before the upload: nothing is uploaded", async (t) => {
  const cases = [
    // another deploy landed during the build
    [
      (first) => [[upload("vA", first)], [upload("vX", first), upload("vA", first)]],
      /REFUSED: the live version is vX, and this deploy was approved over vA/,
    ],
    // this same commit went live during the build, by another hand
    [
      (first, head) => [[upload("vA", first)], [upload("vX", head), upload("vA", first)]],
      /REFUSED: the live version is vX/,
    ],
    // a split started during the build, with the approved version first
    [
      (first, head) => [[upload("vA", first)], [split("vA", "vX", head), upload("vA", first)]],
      /REFUSED: the Worker does not serve one version at 100%/,
    ],
    // a secret changed during the build: a new version, which nobody approved
    [
      (first) => [
        [upload("vA", first)],
        [
          {
            id: "s",
            versions: [{ version_id: "vS", percentage: 100 }],
            annotations: { "workers/triggered_by": "secret" },
          },
          upload("vA", first),
        ],
      ],
      /REFUSED: the live version is vS/,
    ],
    // the read right before the upload fails
    [(first) => [[upload("vA", first)]], /Cloudflare \/deployments: 500/],
  ];
  for (const [reads, refused] of cases) {
    const { done, steps } = deployIn(t, { expected: "vA", reads });
    await refusedBeforeUpload(done, refused);
    assert.deepEqual(steps, ["read", "build true", "read"]);
  }
});

test("from the upload on, every failure says that the upload was attempted and the live state is not verified", async (t) => {
  const before = (first) => [[upload("vA", first)], [upload("vA", first)]];
  const cases = [
    // the upload step fails part-way: what is live is read once, and here that read fails too
    [
      (first) => before(first),
      /wrangler deploy ended with exit 1\nREAD AFTER THE FAILURE: NOT KNOWN, the read failed: Cloudflare \/deployments: 500/,
      2,
    ],
    // the read after the upload fails
    [(first) => before(first), /Cloudflare \/deployments: 500/, 3],
    [(first) => [...before(first), [upload("vA", first)]], /the live version did not change/, 3],
    [
      (first) => [...before(first), [upload("vX", first), upload("vA", first)]],
      /names [0-9a-f]{40}, not [0-9a-f]{40}: another deployment landed after this upload/,
      3,
    ],
    [
      (first, head) => [...before(first), [split("vB", "vA", head), upload("vA", first)]],
      /does not serve one version at 100%/,
      3,
    ],
    // a deployment by another hand between the last read and the upload: this upload replaced
    // it, and the live version names this commit all the same
    [
      (first, head) => [
        ...before(first),
        [upload("vB", head), upload("vX", first), upload("vA", first)],
      ],
      /this upload replaced version vX, not the approved vA/,
      3,
    ],
    // the same, when the other hand started a split
    [
      (first, head) => [
        ...before(first),
        [upload("vB", head), split("vA", "vX", first), upload("vA", first)],
      ],
      /does not serve one version at 100%/,
      3,
    ],
  ];
  for (const [reads, said, readCount] of cases) {
    const { done, steps } = deployIn(t, {
      expected: "vA",
      reads,
      upload: () => {
        if (readCount === 2) throw new Error("wrangler deploy ended with exit 1");
      },
    });
    await assert.rejects(done, (error) => {
      assert.match(error.message, NOT_VERIFIED);
      assert.match(error.message, said);
      assert.match(error.message, /Read the deployments before any new plan/);
      return true;
    });
    assert.deepEqual(steps, ["read", "build true", "read", "upload true", "read"]);
  }
});

test("the Deployer's image is of the commit whose upload's tag names its digest in the registry", () => {
  const [a, b] = ["a".repeat(40), "b".repeat(40)];
  const both = [upload("vB", b, TODAY), upload("vA", a)];
  // a whole rollout: the application runs the image under the tag of B's version
  assert.equal(imageOf(both, running("vB")).commit, b);
  // 27 Nov 2026: B's upload went live, the push of its image timed out (the registry has no tag
  // of B's version), and the application kept the image that A's deploy pushed
  assert.equal(imageOf(both, running("vA", "completed", ["vB"])).commit, a);
  // the push ended and the rollout did not: B's tag is there, and the application runs A's
  assert.equal(imageOf(both, running("vA")).commit, a);
  // OVERLAPPING DEPLOYS: A's rollout started after B's upload, and B's own never did. The
  // times say "a rollout after B's upload"; the digest says A, and the digest is what counts
  assert.equal(imageOf(both, running("vA", "completed", ["vB"])).commit, a);
  // after a rollback of the Worker from B to A the image stays B's: wrangler rolls no image back
  const rollback = {
    versions: [{ version_id: "vA", percentage: 100 }],
    annotations: { "workers/message": "faults after the deploy" },
  };
  assert.equal(liveOf([rollback, ...both]).commit, a);
  assert.equal(imageOf([rollback, ...both], running("vB")).commit, b);
  // a second upload of B (a repair) whose image the registry held already pushes no new tag:
  // the digest is under the tag of B's first upload, and that is B's commit all the same
  const again = [upload("vC", b, "2026-11-27T09:00:00Z"), ...both];
  assert.equal(imageOf(again, running("vB", "completed", ["vC"])).commit, b);
  // not known, with the reason, and never a guess
  const read = running("vB");
  for (const [answer, why] of [
    [{ application: null, rollouts: [], digests: {} }, /no such container application/],
    [running("vB", "progressing"), /has not ended \(rollout-1, status progressing\)/],
    [
      { ...read, application: { ...read.application, active_rollout_id: "rollout-2" } },
      /has not ended/,
    ],
    [
      {
        ...read,
        application: { version: 61, configuration: { image: "registry/deployer:latest" } },
      },
      /names no digest/,
    ],
    // an image that no listed upload pushed: one by hand, or one older than Cloudflare's list
    [running("vOld"), /under the tag of none of the 2 uploads of this script/],
    // no digest was read at all
    [{ ...read, digests: {} }, /under the tag of none of the 2 uploads/],
  ]) {
    const image = imageOf(both, answer);
    assert.equal(image.commit, null);
    assert.match(image.why, why);
  }
  // an upload by another hand names no commit, so its tag ties the image to none
  const byHand = { ...upload("vH", b, TODAY), annotations: { "workers/message": "by hand" } };
  assert.equal(imageOf([byHand, upload("vA", a)], running("vH")).commit, null);
  // one digest under the tags of two commits cannot be: it is not known then
  const same = { ...read, digests: { vA: digestOf("vB"), vB: digestOf("vB") } };
  assert.match(imageOf(both, same).why, /uploads of different commits/);
});

/** The run of 27 Nov 2026 as the deployments list it: B's upload is live over A's. */
const workerAhead = (first, head) => [upload("vB", head, TODAY), upload("vA", first)];
/** The same, as the one read of a run that ends before its build. */
const workerAheadOnce = (first, head) => [workerAhead(first, head)];

test("a registry timeout after the Worker's upload is a partial rollout: exit 3 says so, and names the repair", async (t) => {
  // wrangler uploaded the Worker, then the push of the image failed, and wrangler ended with 1
  const { done, steps, first, head } = deployIn(t, {
    expected: "vA",
    reads: (first, head) => [
      [upload("vA", first)],
      [upload("vA", first)],
      workerAhead(first, head),
    ],
    images: () => [running("vA")],
    upload: () => {
      throw new Error("pnpm exec ended with exit 1");
    },
  });
  await assert.rejects(done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(error.message, /pnpm exec ended with exit 1/);
    assert.ok(
      error.message.includes(
        `READ AFTER THE FAILURE: PARTIAL ROLLOUT: the Worker serves version vB of commit ${head}, and the Deployer's image is of commit ${first}.`,
      ),
    );
    assert.ok(
      error.message.includes(`--commit ${head} --expect-live vB --lock heavy.lock --repair-image`),
    );
    return true;
  });
  // one read after the failure, and nothing after it: no retry, no second upload, no log check
  assert.deepEqual(steps, ["read", "build true", "read", "upload true", "read"]);
});

test("an upload step that fails before anything went live says that the approved version still serves", async (t) => {
  const { done } = deployIn(t, {
    expected: "vA",
    reads: (first) => [[upload("vA", first)], [upload("vA", first)], [upload("vA", first)]],
    upload: () => {
      throw new Error("pnpm exec ended with exit 1");
    },
  });
  await assert.rejects(done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(
      error.message,
      /the Worker still serves the approved version vA. No new version went live/,
    );
    assert.doesNotMatch(error.message, /PARTIAL ROLLOUT/);
    return true;
  });
});

test("an upload step that ends well with no rollout of the image is a partial rollout too; a rollout that ends late is waited for", async (t) => {
  const reads = (first, head) => [
    [upload("vA", first)],
    [upload("vA", first)],
    workerAhead(first, head),
  ];
  // the image never comes: three reads of it after the upload, then exit 3, and no log check
  const never = deployIn(t, { expected: "vA", reads, images: () => [running("vA")] });
  await assert.rejects(never.done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(error.message, /PARTIAL ROLLOUT: the Worker serves version vB/);
    return true;
  });
  assert.equal(never.steps.at(-1), "read");
  // the rollout runs at the first read after the upload, and has ended at the second
  const late = deployIn(t, {
    expected: "vA",
    reads,
    images: () => [running("vA"), running("vB", "progressing"), running("vB")],
  });
  assert.deepEqual(await late.done, { version: "vB", well: true });
  // a rollout that does not end in the time is not called live
  const stuck = deployIn(t, {
    expected: "vA",
    reads,
    images: () => [running("vA"), running("vB", "progressing")],
  });
  await assert.rejects(
    stuck.done,
    /THE DEPLOYER'S IMAGE IS NOT KNOWN TO BE OF THIS COMMIT[^]*a rollout of the application has not ended[^]*No repair is named/,
  );
});

test("a deployment by another hand while the image rolls out is not a verified deploy", async (t) => {
  // the image settles against the deployments of before the wait; the Worker moved meanwhile
  const { done, steps } = deployIn(t, {
    expected: "vA",
    reads: (first, head) => [
      [upload("vA", first)],
      [upload("vA", first)],
      workerAhead(first, head),
      [upload("vX", first, "2026-11-27T07:12:00Z"), ...workerAhead(first, head)],
    ],
    images: () => [running("vA"), running("vA"), running("vB")],
  });
  await assert.rejects(done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(
      error.message,
      /the live version is now vX of commit [0-9a-f]{40}, not this upload's vB/,
    );
    return true;
  });
  assert.deepEqual(steps, ["read", "build true", "read", "upload true", "read", "read"]);
});

test("the same target after a partial rollout is not 'already live': it is refused, and nothing is built or uploaded", async (t) => {
  const { done, steps, head } = deployIn(t, {
    expected: "vB",
    reads: workerAheadOnce,
    images: () => [running("vA")],
  });
  await refusedBeforeUpload(
    done,
    /REFUSED: PARTIAL ROLLOUT: the Worker serves version vB of commit/,
  );
  await assert.rejects(done, (error) =>
    error.message.includes(`--commit ${head} --expect-live vB --lock heavy.lock --repair-image`),
  );
  assert.deepEqual(steps, ["read"]);
  // an image that cannot be read, or whose commit is not known, is not "already live" either
  const unread = deployIn(t, { expected: "vB", reads: workerAheadOnce, images: () => [undefined] });
  await refusedBeforeUpload(unread.done, /containers\/applications: 403/);
  const unknown = deployIn(t, {
    expected: "vB",
    reads: workerAheadOnce,
    images: () => [running("vB", "progressing")],
  });
  await refusedBeforeUpload(
    unknown.done,
    /REFUSED: THE DEPLOYER'S IMAGE IS NOT KNOWN TO BE OF THIS COMMIT/,
  );
});

test("the repair is the same guarded deploy of the live commit: read, build, read, upload, read, image, log", async (t) => {
  const after = (first, head) => [
    upload("vC", head, "2026-11-27T09:00:00Z"),
    ...workerAhead(first, head),
  ];
  const { done, steps } = deployIn(t, {
    expected: "vB",
    repair: true,
    reads: (first, head) => [
      workerAhead(first, head),
      workerAhead(first, head),
      after(first, head),
    ],
    // before the build, after the build, and after the upload: the new image's rollout
    images: () => [running("vA"), running("vA"), running("vC")],
  });
  assert.deepEqual(await done, { version: "vC", well: true });
  assert.deepEqual(steps, [
    "read",
    "build true",
    "read",
    "upload true",
    "read",
    "read",
    "verify true vB",
  ]);
  // the repair's own upload can fail the same way: it is a partial rollout again, over the new version
  const again = deployIn(t, {
    expected: "vB",
    repair: true,
    reads: (first, head) => [
      workerAhead(first, head),
      workerAhead(first, head),
      after(first, head),
    ],
    images: () => [running("vA")],
  });
  await assert.rejects(again.done, (error) => {
    assert.match(error.message, NOT_VERIFIED);
    assert.match(
      error.message,
      /PARTIAL ROLLOUT: the Worker serves version vC[^]*--expect-live vC /,
    );
    return true;
  });
});

test("the repair repairs a partial rollout and nothing else: every guard of a deploy holds for it", async (t) => {
  // the image is of the live commit: nothing to repair, nothing built
  const whole = deployIn(t, { expected: "vB", repair: true, reads: workerAheadOnce });
  assert.equal(await whole.done, null);
  assert.deepEqual(whole.steps, ["read"]);
  // another hand repaired it during the build: nothing is uploaded
  const meanwhile = deployIn(t, {
    expected: "vB",
    repair: true,
    reads: (first, head) => [workerAhead(first, head), workerAhead(first, head)],
    images: () => [running("vA"), running("vB")],
  });
  assert.equal(await meanwhile.done, null);
  assert.deepEqual(meanwhile.steps, ["read", "build true", "read"]);
  // a rollout of the image started during the build: its commit is not known any more, and
  // the repair uploads nothing over it
  const started = deployIn(t, {
    expected: "vB",
    repair: true,
    reads: (first, head) => [workerAhead(first, head), workerAhead(first, head)],
    images: () => [running("vA"), running("vA", "progressing")],
  });
  await refusedBeforeUpload(
    started.done,
    /REFUSED: THE DEPLOYER'S IMAGE IS NOT KNOWN[^]*The image changed during the build. Nothing was uploaded/,
  );
  assert.deepEqual(started.steps, ["read", "build true", "read"]);
  // an image whose commit is not known is no repairable partial rollout: the repair's own
  // check could not know the image after the upload either, so nothing is uploaded
  for (const image of [running("vOld"), running("vA", "progressing")]) {
    const unknown = deployIn(t, {
      expected: "vB",
      repair: true,
      reads: workerAheadOnce,
      images: () => [image],
    });
    await refusedBeforeUpload(
      unknown.done,
      /REFUSED: THE DEPLOYER'S IMAGE IS NOT KNOWN[^]*No repair is named/,
    );
    assert.deepEqual(unknown.steps, ["read"]);
  }
  // the live commit lies behind: that is a deploy, and the flag does not turn it into a repair
  const behind = deployIn(t, {
    expected: "vA",
    repair: true,
    reads: (first) => [[upload("vA", first)]],
  });
  await refusedBeforeUpload(
    behind.done,
    /REFUSED: --repair-image is for the commit that the Worker serves already/,
  );
  assert.deepEqual(behind.steps, ["read"]);
  // the approved live version, the split and the drift during the build are refused as ever
  const cases = [
    [
      (first, head) => [workerAhead(first, head)],
      "vA",
      /REFUSED: the live version is vB, and this deploy was approved over vA/,
    ],
    [
      (first, head) => [[split("vB", "vA", head), upload("vA", first)]],
      "vB",
      /does not serve one version at 100%/,
    ],
    [
      (first, head) => [
        workerAhead(first, head),
        [upload("vX", head, "2026-11-27T08:00:00Z"), ...workerAhead(first, head)],
      ],
      "vB",
      /REFUSED: the live version is vX, and this deploy was approved over vB/,
    ],
  ];
  for (const [reads, expected, refused] of cases) {
    const { done, steps } = deployIn(t, {
      expected,
      repair: true,
      reads,
      images: () => [running("vA")],
    });
    await refusedBeforeUpload(done, refused);
    assert.ok(!steps.some((step) => step.startsWith("upload")));
  }
});

/** True when some open file holds the lock file `lock`: a new try to take it fails. */
const taken = (lock) =>
  spawnSync("flock", ["--nonblock", "--conflict-exit-code", "9", lock, "true"]).status === 9;

/** A lock file in a temporary folder. */
function lockFile(t) {
  const root = mkdtempSync(join(tmpdir(), "deploy-prd-lock-"));
  t.after(() => rmSync(root, { recursive: true, force: true }));
  return join(root, "heavy.lock");
}

test(
  "the lock is this process's own: held until its file closes, and another holder's lock is a refusal",
  { skip: noFlock },
  (t) => {
    const lock = lockFile(t);
    assert.equal(taken(lock), false);
    const held = takeLock(lock);
    // the `flock` that took it has ended, and the lock stays with the file that this process holds
    assert.equal(taken(lock), true);
    // a second taker, as another job is: it does not get the lock, and it does not go on
    assert.throws(() => takeLock(lock, 1), /REFUSED: .*heavy\.lock stayed taken for 1 seconds/);
    assert.equal(taken(lock), true);
    closeSync(held);
    assert.equal(taken(lock), false);
  },
);

test(
  "the command line refuses a deploy with a flag missing, and no variable stands in for the lock",
  { skip: noFlock },
  async (t) => {
    const lock = lockFile(t);
    const { CLOUDFLARE_API_TOKEN: _token, ...env } = process.env;
    const cli = (args) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8", env });
    const flags = ["--commit", "a".repeat(40), "--expect-live", "vA", "--lock", lock];
    for (const [missing, refused] of [
      [0, /REFUSED: no approved commit/],
      [2, /REFUSED: no approved live version/],
      [4, /REFUSED: no lock/],
    ]) {
      const run = cli(flags.toSpliced(missing, 2));
      assert.equal(run.status, 2);
      assert.match(run.stderr, refused);
    }
    // with every flag the run takes the lock and goes on, here to the missing token: exit 2,
    // nothing uploaded
    const locked = cli(flags);
    assert.equal(locked.status, 2);
    assert.match(locked.stderr, /CLOUDFLARE_API_TOKEN is not set/);
    // the repair is the same command with one more flag, and it takes the same lock
    const repair = cli([...flags, "--repair-image"]);
    assert.equal(repair.status, 2);
    assert.match(repair.stderr, /CLOUDFLARE_API_TOKEN is not set/);
    assert.equal(cli(["--repair-image"]).status, 2);
    // another job holds the lock, and the variable that an earlier form of this script trusted
    // is set: the run waits for the lock, and it reads nothing and builds nothing meanwhile
    const held = takeLock(lock);
    const waiting = spawn(process.execPath, [script, ...flags], {
      env: { ...env, DEPLOY_PRD_LOCK: lock },
      stdio: ["ignore", "ignore", "pipe"],
    });
    let said = "";
    waiting.stderr.on("data", (chunk) => (said += chunk));
    const ended = new Promise((resolve) => waiting.on("exit", resolve));
    const first = await Promise.race([
      ended,
      new Promise((resolve) => setTimeout(resolve, 1500, "waits")),
    ]);
    assert.equal(first, "waits");
    assert.equal(said, "");
    // the lock is free: the run takes it and goes on to the missing token
    closeSync(held);
    assert.equal(await ended, 2);
    assert.match(said, /CLOUDFLARE_API_TOKEN is not set/);
  },
);