From 3baa2a8a1a5e549dbf7c3fcc14c738445b3c69b6 Mon Sep 17 00:00:00 2001 From: konaito <81353953+konaito@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:58:17 +0900 Subject: [PATCH 1/4] Wait for a lagging Cloudflare Worker version list during deploy Cloudflare's Worker version list can trail a write by minutes. Before the upload, wait while the list lacks the active version. After the upload, wait while the list still equals the baseline, on a schedule of about 5.5 minutes instead of 250 ms and 500 ms. Failed reads keep their two quick retries. Refs #891 --- packages/deploy-cloudflare/src/version.ts | 64 ++++++++-- .../test/unit/version.test.ts | 111 +++++++++++++++++- 2 files changed, 166 insertions(+), 9 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index c48e37ddd..1ddd36fd8 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -867,6 +867,11 @@ export type CloudflareVersionActivationOptions = { allowFirstDeploymentBootstrap?: boolean; fetch?: typeof globalThis.fetch; sleep?: (milliseconds: number) => Promise; + /** + * Waits between reads of Cloudflare's Worker version list while it lags behind a write. + * Defaults to {@link STALE_VERSION_HISTORY_DELAYS_MS}. + */ + versionHistoryRetryDelaysMs?: ReadonlyArray; readinessAttempts?: number; /** Require readiness to report the uploaded Worker's actual version UUID. */ requireVersionMetadata?: boolean; @@ -969,7 +974,28 @@ async function activateCloudflareVersionWithSecretsFile( let activeSecretsPinned = false; let pinnedActiveSecrets: Array<{ name: string; type: 'secret_key' | 'secret_text' }> | undefined; if (options.expectedPreviousVersionId !== undefined || options.verifyInheritedSecrets === true) { - const recent = await readRecentCloudflareVersionIds(options); + let recent = await readRecentCloudflareVersionIds(options); + // The deployment status above names the active Worker Version. A version list that does not + // contain it is behind that write, so wait for it instead of failing the lineage check below. + // A list that never shows it still fails below, as before. + const delays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; + for ( + let attempt = 0; + previous.versionId !== null && + recent !== null && + !recent.some((version) => version.id === previous.versionId) && + attempt < delays.length; + attempt++ + ) { + if (attempt === 0) { + options.onProgress?.("Waiting for Cloudflare's Worker version list to catch up..."); + } + await (options.sleep ?? delay)(delays[attempt]!); + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + recent = await readRecentCloudflareVersionIds(options); + } if (recent === null) { return { ok: false, reason: 'inheritance-source-unavailable' }; } @@ -1313,19 +1339,31 @@ async function activateCloudflareVersionWithSecretsFile( if (baseline) { // The list can still show the exact pre-upload history after a successful upload. // Wait for a fresh read, but pass any other history straight to the lineage check. + let stale = false; const readUpdatedHistory = async () => { - const recent = await readRecentCloudflareVersionIds(options); + const read = await readRecentCloudflareVersionIds(options); const unchanged = - recent?.length === baseline.length && - recent.every( + read?.length === baseline.length && + read.every( (version, index) => version.id === baseline[index]!.id && version.number === baseline[index]!.number, ); - return unchanged ? null : recent; + stale = unchanged; + return unchanged ? null : read; }; + const historyDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; let recent = await readUpdatedHistory(); - for (let attempt = 0; recent === null && attempt < 2; attempt++) { - await (options.sleep ?? delay)(250 * 2 ** attempt); + for ( + let attempt = 0; + recent === null && + attempt < historyDelays.length && + (stale || attempt < UNAVAILABLE_VERSION_HISTORY_RETRIES); + attempt++ + ) { + if (attempt === 0 && stale) { + options.onProgress?.("Waiting for Cloudflare's Worker version list to catch up..."); + } + await (options.sleep ?? delay)(historyDelays[attempt]!); if (!options.verifyUploader()) { return { ok: false, @@ -2016,6 +2054,18 @@ async function isVoidSecretDraftPlaceholderVersion( } } +/** + * Cloudflare's Worker version list can trail a write by minutes (1.5 to 4 minutes were measured + * for a small Worker). The waits double up to 30 seconds and add up to about five and a half minutes. + */ +export const STALE_VERSION_HISTORY_DELAYS_MS: ReadonlyArray = [ + 250, 500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000, 30_000, 30_000, 30_000, 30_000, 30_000, + 30_000, 30_000, 30_000, 30_000, +]; + +/** A failed read, as opposed to a stale one, is retried only this many times. */ +const UNAVAILABLE_VERSION_HISTORY_RETRIES = 2; + async function readRecentCloudflareVersionIds( options: Pick< Parameters[0], diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index b3e6b6fa4..ed1535ab0 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -16,6 +16,7 @@ import { type CloudflareOperation, type CloudflareTriggerConfig, } from '../../src/index.ts'; +import { STALE_VERSION_HISTORY_DELAYS_MS } from '../../src/version.ts'; import { operationFixture } from '../operation-fixture.ts'; import { apiSecretDraftVersion, voidSecretDraftVersion } from '../secret-draft-fixture.ts'; @@ -1304,15 +1305,24 @@ describe('Cloudflare version activation', () => { : 'uploader-changed', }, ); + // A failed read gets two quick retries. A stale one waits out the whole schedule. + const exhaustedDelays = + firstRead === 'stale' + ? STALE_VERSION_HISTORY_DELAYS_MS + : STALE_VERSION_HISTORY_DELAYS_MS.slice(0, 2); expect(reads).toBe( outcome === 'exhausted' - ? 3 + ? 1 + exhaustedDelays.length : outcome === 'uploader-changed' || firstRead === 'different' ? 1 : 2, ); expect(sleep.mock.calls).toEqual( - outcome === 'exhausted' ? [[250], [500]] : firstRead === 'different' ? [] : [[250]], + outcome === 'exhausted' + ? exhaustedDelays.map((delay) => [delay]) + : firstRead === 'different' + ? [] + : [[STALE_VERSION_HISTORY_DELAYS_MS[0]]], ); expect(runWrangler.mock.calls.filter(([args]) => args[1] === 'upload')).toHaveLength(1); expect(runWrangler.mock.calls.some(([args]) => args[1] === 'deploy')).toBe( @@ -1321,6 +1331,103 @@ describe('Cloudflare version activation', () => { }, ); + it.each([ + { outcome: 'present' }, + { outcome: 'recovers' }, + { outcome: 'exhausted' }, + { outcome: 'uploader-changed' }, + ] as const)( + 'waits for a stale version list to show the active version before upload ($outcome)', + async ({ outcome }) => { + const base = runner(); + let uploaded = false; + let reads = 0; + let uploaderVerified = true; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'versions' && args[1] === 'upload') { + uploaded = true; + } + if (args[0] === 'versions' && args[1] === 'list' && !uploaded) { + reads++; + // The version list has not caught up with the write that made CURRENT active. + const behind = outcome === 'exhausted' || outcome === 'uploader-changed' || reads <= 2; + if (outcome !== 'present' && behind) { + return ok(JSON.stringify([{ id: CONCURRENT, number: 0 }])); + } + } + return base(args); + }); + const sleep = vi.fn(async () => { + if (outcome === 'uploader-changed') { + uploaderVerified = false; + } + }); + const delays = [10, 20, 30]; + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => uploaderVerified, + expectedPreviousVersionId: CURRENT, + message: encodeCloudflareVersionMessage([], triggersWith()), + fetch: async () => Response.json({ ready: true }), + sleep, + versionHistoryRetryDelaysMs: delays, + }); + expect(result).toMatchObject( + outcome === 'present' || outcome === 'recovers' + ? { ok: true, versionId: NEXT } + : { + ok: false, + reason: outcome === 'exhausted' ? 'inheritance-source-changed' : 'uploader-changed', + }, + ); + expect(sleep.mock.calls).toEqual( + outcome === 'present' + ? [] + : outcome === 'recovers' + ? [[10], [20]] + : outcome === 'exhausted' + ? [[10], [20], [30]] + : [[10]], + ); + expect(reads).toBe( + outcome === 'present' ? 1 : outcome === 'recovers' ? 3 : outcome === 'exhausted' ? 4 : 1, + ); + // The wait happens before the upload, so a version list that never catches up uploads nothing. + expect(runWrangler.mock.calls.some(([args]) => args[1] === 'upload')).toBe( + outcome === 'present' || outcome === 'recovers', + ); + }, + ); + + it('waits on the default schedule of about five minutes for a version list that never catches up', async () => { + const base = runner(); + const runWrangler = operationFixture((args: Array) => + args[0] === 'versions' && args[1] === 'list' + ? ok(JSON.stringify([{ id: CONCURRENT, number: 0 }])) + : base(args), + ); + const sleep = vi.fn(async (_milliseconds: number) => {}); + const onProgress = vi.fn(); + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + expectedPreviousVersionId: CURRENT, + message: encodeCloudflareVersionMessage([], triggersWith()), + sleep, + onProgress, + }); + expect(result).toMatchObject({ ok: false, reason: 'inheritance-source-changed' }); + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([...STALE_VERSION_HISTORY_DELAYS_MS]); + const totalMs = STALE_VERSION_HISTORY_DELAYS_MS.reduce((sum, ms) => sum + ms, 0); + expect(totalMs).toBeGreaterThanOrEqual(5 * 60_000); + expect(totalMs).toBeLessThan(6 * 60_000); + expect(onProgress).toHaveBeenCalledWith( + "Waiting for Cloudflare's Worker version list to catch up...", + ); + }); + it('links an existing version without publishing routes or Worker settings', async () => { const directory = mkdtempSync(join(tmpdir(), 'void-link-version-')); const configPath = join(directory, 'wrangler.json'); From c348401fe62cd98e14744df90922c767b288358c Mon Sep 17 00:00:00 2001 From: konaito <81353953+konaito@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:30:19 +0900 Subject: [PATCH 2/4] Retry a Cloudflare Worker version list whose pages disagree The version list reads page 2 only above 10 versions. If a write lands between the two page reads, the pages overlap and the read fails. That failure ended the pre-upload check with no wait and left only two quick retries after the upload. The runner now marks this failure as version-history-changed, and both waits retry it on the same schedule as a stale list. Other failures keep their behavior, and an overlap that outlasts the schedule still stops with inheritance-source-unavailable. Export STALE_VERSION_HISTORY_DELAYS_MS from the package entry. Refs #891 --- packages/deploy-cloudflare/src/execute.ts | 11 ++- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/version.ts | 41 +++++++---- .../test/unit/version.test.ts | 69 +++++++++++++++++++ packages/void/src/cli/cf-version-runner.ts | 10 ++- packages/void/src/cli/env-validation.ts | 6 +- packages/void/src/cli/provision.ts | 6 +- .../void/test/unit/cf-version-runner.test.ts | 33 +++++++++ 8 files changed, 159 insertions(+), 18 deletions(-) diff --git a/packages/deploy-cloudflare/src/execute.ts b/packages/deploy-cloudflare/src/execute.ts index a53154e3b..437e2f748 100644 --- a/packages/deploy-cloudflare/src/execute.ts +++ b/packages/deploy-cloudflare/src/execute.ts @@ -3,7 +3,11 @@ export type CloudflareCommandResult = { /** Structured provider response. stdout is diagnostics only. */ data?: unknown; errorCode?: number; - failure?: 'not-found' | 'durable-migration' | 'containers-unavailable'; + failure?: + | 'not-found' + | 'durable-migration' + | 'containers-unavailable' + | 'version-history-changed'; errors?: Array; stdout: string; stderr: string; @@ -56,6 +60,11 @@ export function isCleanCommandExit(result: CloudflareCommandResult): boolean { return result.status === 0 && isCompletedCommand(result); } +/** The version list's pages disagreed because a write landed while they were being read. */ +export function isVersionHistoryChanged(result: CloudflareCommandResult): boolean { + return isCompletedCommand(result) && result.failure === 'version-history-changed'; +} + /** Cloudflare reported that the Worker or its deployment does not exist (code 10007). */ export function isWorkerNotFound(result: CloudflareCommandResult): boolean { return ( diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 3d5507cd8..1474f73d1 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -36,6 +36,7 @@ export { } from './static.ts'; export { activateCloudflareVersion, + STALE_VERSION_HISTORY_DELAYS_MS, deployCloudflareVersionTriggers, deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 1ddd36fd8..ea1fd7747 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -10,6 +10,7 @@ import { cloudflareCommandDiagnostic } from './diagnostics.ts'; import { isCleanCommandExit, isCompletedCommand, + isVersionHistoryChanged, isWorkerNotFound, type CloudflareCommandResult, type CloudflareCommandRunner, @@ -974,16 +975,18 @@ async function activateCloudflareVersionWithSecretsFile( let activeSecretsPinned = false; let pinnedActiveSecrets: Array<{ name: string; type: 'secret_key' | 'secret_text' }> | undefined; if (options.expectedPreviousVersionId !== undefined || options.verifyInheritedSecrets === true) { - let recent = await readRecentCloudflareVersionIds(options); + let read = await readRecentCloudflareVersionHistory(options); // The deployment status above names the active Worker Version. A version list that does not // contain it is behind that write, so wait for it instead of failing the lineage check below. - // A list that never shows it still fails below, as before. + // Pages that disagree mean a write landed between the two page reads, so that read is retried + // on the same schedule. A list that never settles still fails below, as before. const delays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; for ( let attempt = 0; - previous.versionId !== null && - recent !== null && - !recent.some((version) => version.id === previous.versionId) && + (read.changing || + (previous.versionId !== null && + read.versions !== null && + !read.versions.some((version) => version.id === previous.versionId))) && attempt < delays.length; attempt++ ) { @@ -994,8 +997,9 @@ async function activateCloudflareVersionWithSecretsFile( if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } - recent = await readRecentCloudflareVersionIds(options); + read = await readRecentCloudflareVersionHistory(options); } + const recent = read.versions; if (recent === null) { return { ok: false, reason: 'inheritance-source-unavailable' }; } @@ -1341,14 +1345,15 @@ async function activateCloudflareVersionWithSecretsFile( // Wait for a fresh read, but pass any other history straight to the lineage check. let stale = false; const readUpdatedHistory = async () => { - const read = await readRecentCloudflareVersionIds(options); + const { versions: read, changing } = await readRecentCloudflareVersionHistory(options); const unchanged = read?.length === baseline.length && read.every( (version, index) => version.id === baseline[index]!.id && version.number === baseline[index]!.number, ); - stale = unchanged; + // Pages that disagree are a read that raced a write, so they wait like a stale list does. + stale = unchanged || changing; return unchanged ? null : read; }; const historyDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; @@ -2066,23 +2071,33 @@ export const STALE_VERSION_HISTORY_DELAYS_MS: ReadonlyArray = [ /** A failed read, as opposed to a stale one, is retried only this many times. */ const UNAVAILABLE_VERSION_HISTORY_RETRIES = 2; -async function readRecentCloudflareVersionIds( +/** `changing` marks a read that failed only because the list's pages moved during the read. */ +type RecentCloudflareVersionHistory = { + versions: Array | null; + changing: boolean; +}; + +async function readRecentCloudflareVersionHistory( options: Pick< Parameters[0], 'configPath' | 'runWrangler' | 'workerName' >, -): Promise | null> { +): Promise { const result = await options.runWrangler( { type: 'versions.list', configPath: options.configPath, workerName: options.workerName }, { capture: true }, ); if (!isCleanCommandExit(result)) { if (isWorkerNotFound(result)) { - return []; + return { versions: [], changing: false }; } - return null; + return { versions: null, changing: isVersionHistoryChanged(result) }; } - const versions = result.data; + return { versions: parseRecentCloudflareVersions(result.data), changing: false }; +} + +function parseRecentCloudflareVersions(data: unknown): Array | null { + const versions = data; if ( !Array.isArray(versions) || !versions.every( diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index ed1535ab0..0090b6bd1 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -1400,6 +1400,75 @@ describe('Cloudflare version activation', () => { }, ); + it.each([ + { phase: 'before', failure: 'overlap', outcome: 'recovers' }, + { phase: 'before', failure: 'overlap', outcome: 'exhausted' }, + { phase: 'before', failure: 'other', outcome: 'exhausted' }, + { phase: 'after', failure: 'overlap', outcome: 'recovers' }, + { phase: 'after', failure: 'overlap', outcome: 'exhausted' }, + { phase: 'after', failure: 'other', outcome: 'exhausted' }, + ] as const)( + 'retries a version list whose pages overlapped on the stale-list schedule ($phase upload, $failure failure, $outcome)', + async ({ phase, failure, outcome }) => { + const base = runner(); + let uploaded = false; + let reads = 0; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'versions' && args[1] === 'upload') { + uploaded = true; + } + if (args[0] === 'versions' && args[1] === 'list' && uploaded === (phase === 'after')) { + reads++; + if (outcome === 'exhausted' || reads <= 2) { + return failure === 'overlap' + ? { + status: 1, + stdout: '', + stderr: 'The Cloudflare Worker version history changed during inspection.', + failure: 'version-history-changed', + } + : { status: 1, stdout: '', stderr: 'Version list rejected' }; + } + } + return base(args); + }); + const sleep = vi.fn(async (_milliseconds: number) => {}); + const delays = [10, 20, 30]; + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + ...(phase === 'before' + ? { expectedPreviousVersionId: CURRENT } + : { verifyInheritedSecrets: true }), + message: encodeCloudflareVersionMessage([], triggersWith()), + fetch: async () => Response.json({ ready: true }), + sleep, + versionHistoryRetryDelaysMs: delays, + }); + expect(result).toMatchObject( + outcome === 'recovers' + ? { ok: true, versionId: NEXT } + : { ok: false, reason: 'inheritance-source-unavailable' }, + ); + // Only the overlap failure waits the whole schedule. Any other failure stops at once before + // the upload and keeps its two quick retries after it. + const waits = + outcome === 'recovers' + ? delays.slice(0, 2) + : failure === 'overlap' + ? delays + : phase === 'before' + ? [] + : delays.slice(0, 2); + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual(waits); + expect(reads).toBe(1 + waits.length); + expect(runWrangler.mock.calls.some(([args]) => args[1] === 'upload')).toBe( + outcome === 'recovers' || phase === 'after', + ); + }, + ); + it('waits on the default schedule of about five minutes for a version list that never catches up', async () => { const base = runner(); const runWrangler = operationFixture((args: Array) => diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index bf1fb35b3..6a2b8a92d 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -636,7 +636,10 @@ export function createCfVersionRunner(options: { } const numbers = next.versions.map((item) => item.number as number); if (Math.min(...numbers) <= last) { - return failed('The Cloudflare Worker version history changed during inspection.'); + return { + ...failed('The Cloudflare Worker version history changed during inspection.'), + failure: 'version-history-changed', + }; } versions.push(...next.versions); last = Math.max(...numbers); @@ -648,7 +651,10 @@ export function createCfVersionRunner(options: { } } } else if (Math.max(...secondNumbers) >= Math.min(...firstNumbers)) { - return failed('The Cloudflare Worker version history changed during inspection.'); + return { + ...failed('The Cloudflare Worker version history changed during inspection.'), + failure: 'version-history-changed', + }; } } } diff --git a/packages/void/src/cli/env-validation.ts b/packages/void/src/cli/env-validation.ts index 7250f2800..55bc56c4c 100644 --- a/packages/void/src/cli/env-validation.ts +++ b/packages/void/src/cli/env-validation.ts @@ -225,7 +225,11 @@ async function requiredSchemaKeys(schema: Record): Promise ]); }, 30_000); +it('marks a version list whose pages overlap as a changed history', async () => { + const prepared = await output(); + try { + const page = (first: number) => + Array.from({ length: 10 }, (_, index) => ({ + id: `v${first + index}`, + number: first + index, + })); + const runner = createCfVersionRunner({ + output: prepared, + workerName: 'void-test', + verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + runCf: (args) => ({ + status: 0, + // A write between the reads moved page 2 up to overlap page 1. + stdout: JSON.stringify(args.at(-1) === '1' ? page(5) : page(10)), + stderr: '', + }), + }); + const result = await runner( + { type: 'versions.list', configPath: 'generated.json', workerName: 'void-test' }, + { capture: true }, + ); + expect(result).toMatchObject({ + status: 1, + stderr: 'The Cloudflare Worker version history changed during inspection.', + failure: 'version-history-changed', + }); + } finally { + await prepared.dispose(); + } +}); + it('preserves activation metadata and sorts cf version history for the existing protocol', async () => { const prepared = await output(); try { From f72b076b20d62d6cfdee0dfd5e5f7af806565b24 Mon Sep 17 00:00:00 2001 From: konaito <81353953+konaito@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:49:58 +0900 Subject: [PATCH 3/4] Accept the version-history-changed failure in the process envelope The process envelope decoder accepted only three of the four runner failures, so a version-history-changed envelope from a child process would have been rejected as invalid. The cf runner is in-process today, so this path was not reachable. The accepted failures are now a record keyed by the CloudflareCommandResult failure union, so a failure added to the union fails the typecheck until it is accepted here too. Refs #891 --- packages/void/src/cli/cloudflare-process.ts | 11 ++++++++++- packages/void/test/unit/cloudflare-process.test.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/void/src/cli/cloudflare-process.ts b/packages/void/src/cli/cloudflare-process.ts index 565c20dfa..ed9a5c4d0 100644 --- a/packages/void/src/cli/cloudflare-process.ts +++ b/packages/void/src/cli/cloudflare-process.ts @@ -25,6 +25,14 @@ type OperationEnvelopeFields = { error?: string | null; }; +/** Keyed by the runner's failure union, so a new failure cannot be left off the whitelist. */ +const CLOUDFLARE_COMMAND_FAILURES: Record, true> = { + 'not-found': true, + 'durable-migration': true, + 'containers-unavailable': true, + 'version-history-changed': true, +}; + /** True only for a child that ran to completion with a clean exit 0. */ export function isCleanCloudflareExit( result: Pick, @@ -62,7 +70,8 @@ export function decodeCloudflareOperationResult( (envelope.error != null && typeof envelope.error !== 'string') || (envelope.errorCode !== undefined && !Number.isSafeInteger(envelope.errorCode)) || (envelope.failure !== undefined && - !['not-found', 'durable-migration', 'containers-unavailable'].includes(envelope.failure)) || + (typeof envelope.failure !== 'string' || + !Object.hasOwn(CLOUDFLARE_COMMAND_FAILURES, envelope.failure))) || (envelope.errors !== undefined && (!Array.isArray(envelope.errors) || envelope.errors.some( diff --git a/packages/void/test/unit/cloudflare-process.test.ts b/packages/void/test/unit/cloudflare-process.test.ts index c636d87d2..f81bcb146 100644 --- a/packages/void/test/unit/cloudflare-process.test.ts +++ b/packages/void/test/unit/cloudflare-process.test.ts @@ -74,6 +74,18 @@ describe('typed Cloudflare process protocol', () => { }); }); + it.each(['not-found', 'durable-migration', 'containers-unavailable', 'version-history-changed'])( + 'accepts the %s failure from the runner', + (failure) => { + const value = decodeCloudflareOperationResult({ + ...processResult({ operationResult: 1, failure }), + status: 1, + }); + expect(value).toMatchObject({ status: 1, failure }); + expect(value.stderr).not.toContain('invalid operation response'); + }, + ); + it.each([ null, [], From e4fbe90ae461d005df1aa18ec5a777ca300fb7f9 Mon Sep 17 00:00:00 2001 From: konaito <81353953+konaito@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:00:29 +0900 Subject: [PATCH 4/4] Recheck production after a version list wait and skip older rollbacks A rollback during either version list wait was not seen until after the candidate receipt was saved with the old active version as its parent. The deploy then stopped, and the next deploy failed on that receipt. After a wait, production is now read again before the upload and before the receipt is saved. If it changed, the deploy stops with deployment-changed and saves no receipt. A rollback to a version older than the ten listed versions can never appear in the list, but the pre-upload check waited the whole schedule for it. The active version's number is now read with versions.view, and the deploy waits only when that number is not below the list's lowest number. A number that cannot be read keeps the wait. Refs #891 --- packages/deploy-cloudflare/src/version.ts | 114 ++++++++++++++- .../test/unit/version.test.ts | 134 +++++++++++++++++- 2 files changed, 243 insertions(+), 5 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index ea1fd7747..c627d8ddf 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -981,12 +981,33 @@ async function activateCloudflareVersionWithSecretsFile( // Pages that disagree mean a write landed between the two page reads, so that read is retried // on the same schedule. A list that never settles still fails below, as before. const delays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; + // A rollback can make a version older than the listed ones active. The list will never show + // that version, so only an active version that is not older than the list is waited for. + let activeNumber: number | null | undefined; + const listIsBehind = async (versions: ReadonlyArray) => { + if ( + previous.versionId === null || + versions.some((version) => version.id === previous.versionId) + ) { + return false; + } + if (versions.length === 0) { + return true; + } + if (activeNumber === undefined) { + activeNumber = await readCloudflareVersionNumber(options, previous.versionId); + } + // A number that cannot be read keeps the wait: a version the list trails may not be + // readable yet either, and a list that never shows it still fails the checks below. + return ( + activeNumber === null || + activeNumber >= Math.min(...versions.map((version) => version.number)) + ); + }; + let waited = false; for ( let attempt = 0; - (read.changing || - (previous.versionId !== null && - read.versions !== null && - !read.versions.some((version) => version.id === previous.versionId))) && + (read.changing || (read.versions !== null && (await listIsBehind(read.versions)))) && attempt < delays.length; attempt++ ) { @@ -994,11 +1015,32 @@ async function activateCloudflareVersionWithSecretsFile( options.onProgress?.("Waiting for Cloudflare's Worker version list to catch up..."); } await (options.sleep ?? delay)(delays[attempt]!); + waited = true; if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } read = await readRecentCloudflareVersionHistory(options); } + if (waited) { + // A rollback or another deploy during the wait must not be built on, or recorded as the + // parent of a candidate that would then break the next deploy. + const owner = await readCurrentProductionVersion(options); + if (owner.kind === 'failed') { + return { ok: false, reason: 'status-failed', status: owner.status }; + } + if ( + owner.kind !== 'ok' || + owner.versionId !== previous.versionId || + !productionVersionPercentagesEqual(owner.versions, previous.versions) + ) { + return { + ok: false, + reason: 'deployment-changed', + activeVersionId: owner.kind === 'ok' ? owner.versionId : null, + rollback: 'not-needed', + }; + } + } const recent = read.versions; if (recent === null) { return { ok: false, reason: 'inheritance-source-unavailable' }; @@ -1340,6 +1382,7 @@ async function activateCloudflareVersionWithSecretsFile( } options.onProgress?.('Verifying the uploaded Worker...'); const baseline = inheritanceBaseline; + let waitedAfterUpload = false; if (baseline) { // The list can still show the exact pre-upload history after a successful upload. // Wait for a fresh read, but pass any other history straight to the lineage check. @@ -1369,6 +1412,7 @@ async function activateCloudflareVersionWithSecretsFile( options.onProgress?.("Waiting for Cloudflare's Worker version list to catch up..."); } await (options.sleep ?? delay)(historyDelays[attempt]!); + waitedAfterUpload = true; if (!options.verifyUploader()) { return { ok: false, @@ -1412,6 +1456,35 @@ async function activateCloudflareVersionWithSecretsFile( } } await options.validateUploadedVersion?.(versionId); + if (waitedAfterUpload) { + // The receipt names the live version as the candidate's parent. A rollback during the wait + // above would make that parent wrong and break the next deploy, so stop before saving it. + const owner = await readCurrentProductionVersion(options); + if (owner.kind === 'failed') { + return { + ok: false, + reason: 'status-failed', + status: owner.status, + versionId, + previousVersionId: previous.versionId, + }; + } + if ( + owner.kind !== 'ok' || + owner.versionId !== previous.versionId || + !productionVersionPercentagesEqual(owner.versions, previous.versions) + ) { + return { + ok: false, + reason: 'deployment-changed', + versionId, + previousVersionId: previous.versionId, + activeVersionId: owner.kind === 'ok' ? owner.versionId : null, + rollback: 'not-needed', + triggerRepair: 'succeeded', + }; + } + } if (options.recordVerifiedCandidate) { if (!options.validateUploadedVersion && !inheritanceBaseline) { throw new Error( @@ -2068,6 +2141,39 @@ export const STALE_VERSION_HISTORY_DELAYS_MS: ReadonlyArray = [ 30_000, 30_000, 30_000, 30_000, ]; +/** The Worker Version's sequential number, or null when it cannot be read. */ +async function readCloudflareVersionNumber( + options: Pick< + Parameters[0], + 'configPath' | 'runWrangler' | 'workerName' + >, + versionId: string, +): Promise { + try { + const result = await options.runWrangler( + { + type: 'versions.view', + versionId, + configPath: options.configPath, + workerName: options.workerName, + }, + { capture: true }, + ); + if (!isCleanCommandExit(result)) { + return null; + } + const version = result.data; + return isRecord(version) && + version.id === versionId && + typeof version.number === 'number' && + Number.isSafeInteger(version.number) + ? version.number + : null; + } catch { + return null; + } +} + /** A failed read, as opposed to a stale one, is retried only this many times. */ const UNAVAILABLE_VERSION_HISTORY_RETRIES = 2; diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 0090b6bd1..f4fdc6478 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -1355,6 +1355,10 @@ describe('Cloudflare version activation', () => { return ok(JSON.stringify([{ id: CONCURRENT, number: 0 }])); } } + if (args[0] === 'versions' && args[1] === 'view' && args[2] === CURRENT) { + // CURRENT is newer than everything the stale list shows. + return ok(JSON.stringify({ id: CURRENT, number: 1 })); + } return base(args); }); const sleep = vi.fn(async () => { @@ -1474,7 +1478,9 @@ describe('Cloudflare version activation', () => { const runWrangler = operationFixture((args: Array) => args[0] === 'versions' && args[1] === 'list' ? ok(JSON.stringify([{ id: CONCURRENT, number: 0 }])) - : base(args), + : args[0] === 'versions' && args[1] === 'view' && args[2] === CURRENT + ? ok(JSON.stringify({ id: CURRENT, number: 1 })) + : base(args), ); const sleep = vi.fn(async (_milliseconds: number) => {}); const onProgress = vi.fn(); @@ -1497,6 +1503,132 @@ describe('Cloudflare version activation', () => { ); }); + it.each([{ phase: 'before' }, { phase: 'after' }] as const)( + 'stops without saving a candidate when a rollback lands during the version list wait ($phase upload)', + async ({ phase }) => { + const base = runner(); + let uploaded = false; + let rolledBack = false; + let reads = 0; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'versions' && args[1] === 'upload') { + uploaded = true; + } + if (args[0] === 'deployments' && rolledBack) { + return ok(JSON.stringify({ versions: [{ version_id: CONCURRENT, percentage: 100 }] })); + } + if (args[0] === 'versions' && args[1] === 'list' && uploaded === (phase === 'after')) { + reads++; + if (reads === 1) { + // Before the upload the list trails the write that made CURRENT active. After it, the + // list still shows the exact pre-upload history. + return ok( + JSON.stringify( + phase === 'before' ? [{ id: CONCURRENT, number: 0 }] : [{ id: CURRENT, number: 1 }], + ), + ); + } + } + if (args[0] === 'versions' && args[1] === 'view' && args[2] === CURRENT) { + return ok(JSON.stringify({ id: CURRENT, number: 1 })); + } + return base(args); + }); + const sleep = vi.fn(async (_milliseconds: number) => { + // Someone rolls production back to CONCURRENT while this deploy waits. + rolledBack = true; + }); + const recordVerifiedCandidate = vi.fn(); + const fetch = vi.fn(async () => Response.json({ ready: true })); + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + verifyInheritedSecrets: true, + recordVerifiedCandidate, + message: encodeCloudflareVersionMessage([], triggersWith()), + fetch, + sleep, + versionHistoryRetryDelaysMs: [10, 20, 30], + }); + expect(result).toMatchObject({ + ok: false, + reason: 'deployment-changed', + activeVersionId: CONCURRENT, + rollback: 'not-needed', + }); + expect(sleep.mock.calls).toEqual([[10]]); + // A receipt naming CURRENT as the parent would break the next deploy from CONCURRENT. + expect(recordVerifiedCandidate).not.toHaveBeenCalled(); + expect(runWrangler.mock.calls.some(([args]) => args[1] === 'upload')).toBe(phase === 'after'); + expect(fetch).not.toHaveBeenCalled(); + expect(runWrangler.mock.calls.some(([args]) => args[1] === 'deploy')).toBe(false); + }, + ); + + it.each([ + { view: 'older', waits: false }, + { view: 'unnumbered', waits: true }, + { view: 'failed', waits: true }, + { view: 'throws', waits: true }, + ] as const)( + 'waits for an absent active version only when it is not older than the version list ($view)', + async ({ view, waits }) => { + const base = runner(); + // The ten most recent versions are 11 to 20. Production was rolled back to CURRENT, number 1. + const listed = Array.from({ length: 10 }, (_, index) => ({ + id: `44444444-4444-4444-8444-4444444444${String(index + 11)}`, + number: index + 11, + })); + let uploaded = false; + let numberReads = 0; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'versions' && args[1] === 'upload') { + uploaded = true; + } + if (args[0] === 'versions' && args[1] === 'list') { + return ok( + JSON.stringify(uploaded ? [...listed.slice(1), { id: NEXT, number: 21 }] : listed), + ); + } + if (args[0] === 'versions' && args[1] === 'view') { + const resources = { bindings: [] }; + if (args[2] === CURRENT && numberReads++ === 0) { + if (view === 'unnumbered') { + return ok(JSON.stringify({ id: CURRENT, resources })); + } + if (view === 'failed') { + return { status: 1, stdout: '', stderr: 'Version unavailable' }; + } + if (view === 'throws') { + throw new Error('Version transport failed'); + } + } + return ok( + JSON.stringify({ id: args[2], number: args[2] === CURRENT ? 1 : 20, resources }), + ); + } + return base(args); + }); + const sleep = vi.fn(async (_milliseconds: number) => {}); + const delays = [10, 20, 30]; + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + verifyInheritedSecrets: true, + message: encodeCloudflareVersionMessage([], triggersWith()), + fetch: async () => Response.json({ ready: true }), + sleep, + versionHistoryRetryDelaysMs: delays, + }); + expect(result).toMatchObject({ ok: true, versionId: NEXT }); + // A version older than the list can never appear in it, so waiting only delays the deploy. + // A number that cannot be read keeps the wait, since a lagging version may not be readable. + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual(waits ? delays : []); + }, + ); + it('links an existing version without publishing routes or Worker settings', async () => { const directory = mkdtempSync(join(tmpdir(), 'void-link-version-')); const configPath = join(directory, 'wrangler.json');