From 7ef56160901726811af039f746b74edb8af828ba Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Thu, 26 Nov 2026 14:48:51 +0800 Subject: [PATCH 1/4] fix(deploy-cloudflare): handle stale staging status --- packages/deploy-cloudflare/src/version.ts | 82 ++++++--- .../test/unit/version.test.ts | 168 ++++++++++++++++++ .../void/src/cli/deploy-cloudflare-helpers.ts | 25 ++- .../void/test/unit/cloudflare-deploy.test.ts | 42 +++++ 4 files changed, 294 insertions(+), 23 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index b71670a22..3905fabf1 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -121,6 +121,8 @@ export type CloudflareVersionActivation = diagnostic?: string; /** Wrangler reached Cloudflare's Containers entitlement endpoint and received a 403. */ containersUnavailable?: boolean; + /** The final status check stopped activation after the version was uploaded. */ + beforeActivation?: true; versionId?: string; previousVersionId?: string | null; rollback?: 'not-needed' | 'succeeded' | 'failed' | 'unavailable' | 'unsafe'; @@ -878,7 +880,7 @@ export type CloudflareVersionActivationOptions = { fetch?: typeof globalThis.fetch; sleep?: (milliseconds: number) => Promise; /** - * Waits between reads of Cloudflare's Worker version list while it lags behind a write. + * Waits between reads while Cloudflare's Worker version list or staged deployment status lags. * Defaults to {@link STALE_VERSION_HISTORY_DELAYS_MS}. */ versionHistoryRetryDelaysMs?: ReadonlyArray; @@ -1709,44 +1711,84 @@ async function activateCloudflareVersionWithSecretsFile( // Readiness can take long enough for another deploy or rollback to finish. Never flatten that // newer operation using the stale `previous` snapshot captured before this upload began. - const ownerBeforeActivation = await readCurrentProductionVersion(options); - if (ownerBeforeActivation.kind === 'failed') { - return { - ok: false, - reason: 'status-failed', - status: ownerBeforeActivation.status, - versionId, - previousVersionId: previous.versionId, - }; + const previousTraffic = previous.versionId + ? [{ versionId: previous.versionId, percentage: 100 }] + : []; + const stagedTraffic = stagedVersionOverride + ? stagedVersionPercentages(previous.versionId, versionId) + : undefined; + const isLaggingStagingStatus = (owner: CurrentProductionVersion) => + stagedTraffic !== undefined && + previous.versionId !== null && + owner.kind === 'ok' && + productionVersionPercentagesEqual(owner.versions, previousTraffic); + let ownerBeforeActivation = await readCurrentProductionVersion(options); + const statusDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; + for ( + let attempt = 0; + attempt < statusDelays.length && isLaggingStagingStatus(ownerBeforeActivation); + attempt++ + ) { + if (attempt === 0) { + options.onProgress?.( + "Waiting for Cloudflare's deployment status to show the staged version...", + ); + } + await (options.sleep ?? delay)(statusDelays[attempt]); + if (!options.verifyUploader()) { + return { + ok: false, + reason: 'uploader-changed', + versionId, + previousVersionId: previous.versionId, + }; + } + ownerBeforeActivation = await readCurrentProductionVersion(options); } if (ownerBeforeActivation.kind === 'split') { return { ok: false, reason: 'traffic-split-unsupported', + beforeActivation: true, versionId, previousVersionId: previous.versionId, + rollback: 'not-needed', }; } - const expectedTrafficBeforeActivation = stagedVersionOverride - ? stagedVersionPercentages(previous.versionId, versionId) - : previous.versionId - ? [{ versionId: previous.versionId, percentage: 100 }] - : []; if ( + ownerBeforeActivation.kind === 'failed' || ownerBeforeActivation.versionId !== previous.versionId || !productionVersionPercentagesEqual( ownerBeforeActivation.versions, - expectedTrafficBeforeActivation, + stagedTraffic ?? previousTraffic, ) ) { + const failure = + ownerBeforeActivation.kind === 'failed' + ? { reason: 'status-failed' as const, status: ownerBeforeActivation.status } + : { reason: 'deployment-changed' as const }; + const restore = + stagedTraffic?.length && + (ownerBeforeActivation.kind === 'failed' || isLaggingStagingStatus(ownerBeforeActivation)) + ? await restorePreviousVersion( + options, + previous.versionId, + 'pre-activation status check failed', + [stagedTraffic], + ) + : { + rollback: 'not-needed' as const, + ...(ownerBeforeActivation.kind === 'ok' + ? { activeVersionId: ownerBeforeActivation.versionId } + : {}), + }; return { ok: false, - reason: 'deployment-changed', + ...failure, + beforeActivation: true, versionId, previousVersionId: previous.versionId, - activeVersionId: ownerBeforeActivation.versionId, - rollback: 'not-needed', - triggerRepair: 'succeeded', + ...restore, ...cloudflareStagingPairGuidance(ownerBeforeActivation.deployment, options), }; } diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 50966c92e..bd11aeec0 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -3929,6 +3929,174 @@ describe('Cloudflare version activation', () => { ); }); + describe('staged deployment status', () => { + const status = (...versions: Array) => ok(JSON.stringify({ versions })); + const previous = status({ version_id: CURRENT, percentage: 100 }); + const concurrent = status({ version_id: CONCURRENT, percentage: 100 }); + const staging = [`${CURRENT}@100`, `${NEXT}@0`]; + + function stagedActivation(...statusReads: Array) { + const base = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); + let staged = false; + const runWrangler = operationFixture((args: Array) => { + if (staged && args[0] === 'deployments') { + const read = statusReads.shift(); + if (read) { + return read; + } + } + staged ||= args.includes(`${NEXT}@0`); + return base(args); + }); + const sleep = vi.fn(async (_milliseconds: number) => {}); + return { + runWrangler, + sleep, + options: { + runWrangler, + verifyUploader: () => true, + workerName: 'my-worker', + workersDevSubdomain: 'example', + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + versionHistoryRetryDelaysMs: [17, 29], + sleep, + }, + }; + } + + it('waits for Cloudflare to show its 0% staging deployment before activating', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous); + + await expect(activateCloudflareVersion(options)).resolves.toMatchObject({ + ok: true, + versionId: NEXT, + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${NEXT}@100`]]); + }); + + it.each([ + ['a different active version', concurrent, CONCURRENT], + [ + 'a different staged version', + status({ version_id: CURRENT, percentage: 100 }, { version_id: CONCURRENT, percentage: 0 }), + CURRENT, + ], + ] as const)( + 'stops at %s during the wait without another traffic write', + async (_kind, read, activeVersionId) => { + const { options, runWrangler, sleep } = stagedActivation(previous, read); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId, + rollback: 'not-needed', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(runWrangler.mock.calls.some(([args]) => args[0] === 'triggers')).toBe(false); + }, + ); + + it('clears its staging deployment if the status only catches up during the final ownership check', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous, previous, previous); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId: CURRENT, + rollback: 'succeeded', + }); + expect(sleep.mock.calls).toEqual([[17], [29]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${CURRENT}@100`]]); + }); + + it.each([ + ['another deployment', concurrent, CONCURRENT], + ['the pre-staging deployment', previous, CURRENT], + ] as const)( + 'leaves production alone when the final ownership check sees %s', + async (_kind, read, activeVersionId) => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + previous, + previous, + read, + ); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId, + rollback: 'unsafe', + }); + expect(sleep.mock.calls).toEqual([[17], [29]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + }, + ); + + it('clears its staging deployment after a failed read if the ownership check confirms it', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous, { ...ok(), status: 1 }); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + status: 1, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId: CURRENT, + rollback: 'succeeded', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${CURRENT}@100`]]); + }); + + it('stops at a split during the wait without writing traffic', async () => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + status({ version_id: CURRENT, percentage: 50 }, { version_id: CONCURRENT, percentage: 50 }), + ); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'traffic-split-unsupported', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + rollback: 'not-needed', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + + it('does not read or write through an uploader that changes during the wait', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous); + let trusted = true; + sleep.mockImplementation(async () => { + trusted = false; + }); + + await expect( + activateCloudflareVersion({ ...options, verifyUploader: () => trusted }), + ).resolves.toMatchObject({ ok: false, reason: 'uploader-changed' }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(runWrangler.mock.calls.filter(([args]) => args[0] === 'deployments')).toHaveLength(3); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + }); + it('does not stage over a production owner that changed after upload', async () => { let statusCalls = 0; const runWrangler = operationFixture(async (args: Array) => { diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 999e641c3..dfeba5a60 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -554,6 +554,19 @@ export function formatCloudflareActivationError( : message; } +function formatStagingCleanup(result: Exclude): string { + switch (result.rollback) { + case 'succeeded': + return ` Void removed the staged version. Worker version ${result.activeVersionId ?? '(unknown)'} continues serving 100% of traffic.`; + case 'failed': + return ' Cloudflare did not confirm removal of the staged version.'; + case 'unsafe': + return ' Void could not safely remove its staged version.'; + default: + return ''; + } +} + function formatCloudflareActivationFailure( result: Exclude, ): string { @@ -563,6 +576,7 @@ function formatCloudflareActivationFailure( ? '' : ` Cloudflare error code: ${String(result.cloudflareErrorCode)}.`; const diagnostic = result.diagnostic ? `\n\n${result.diagnostic}` : ''; + const stagingCleanup = result.beforeActivation ? formatStagingCleanup(result) : ''; switch (result.reason) { case 'uploader-changed': if (result.rollback === 'succeeded') { @@ -580,8 +594,8 @@ function formatCloudflareActivationFailure( return 'deploy: the verified Wrangler uploader changed before version activation.'; case 'status-failed': if (result.versionId) { - if (result.rollback === 'not-needed') { - return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}. Inspect \`void project status\` before retrying.`; + if (result.beforeActivation || result.rollback === 'not-needed') { + return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}.${stagingCleanup} Inspect \`void project status\` before retrying.`; } return `deploy: Worker version ${result.versionId} was published, but current deployment status could not be verified${status}. Inspect \`void project status\` before retrying.`; } @@ -590,6 +604,9 @@ function formatCloudflareActivationFailure( if (result.diagnostic) { return result.diagnostic; } + if (result.beforeActivation) { + return `deploy: Cloudflare deployment status did not match the expected traffic.${stagingCleanup} Inspect the active Worker version ${result.activeVersionId ?? '(unknown)'} before retrying.`; + } return result.triggerRepair === 'succeeded' ? `deploy: another Cloudflare operation superseded this deployment. Void restored triggers for the active version ${result.activeVersionId ?? '(unknown)'}; retry from fresh deployment status.` : `deploy: another Cloudflare operation superseded this deployment, but its trigger state could not be verified. Inspect the active Worker version ${result.activeVersionId ?? '(unknown)'} immediately.`; @@ -616,7 +633,9 @@ function formatCloudflareActivationFailure( return [ 'deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.', 'Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout', - 'in Cloudflare, then retry; no version was uploaded.', + result.beforeActivation && result.versionId + ? `in Cloudflare, then retry. Worker version ${result.versionId} was uploaded but not activated.` + : 'in Cloudflare, then retry; no version was uploaded.', ].join('\n'); case 'upload-failed': return `deploy: Cloudflare Worker Version upload failed${status}; production traffic is unchanged.${cloudflareCode}${diagnostic}`; diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index b61787c0f..29a54789e 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -527,6 +527,48 @@ describe('Cloudflare activation diagnostics', () => { }, ); + it.each([ + ['succeeded', 'continues serving 100% of traffic'], + ['unsafe', 'Void could not safely remove its staged version'], + ['failed', 'Cloudflare did not confirm removal of the staged version'], + ] as const)('reports staging cleanup outcome %s', (rollback, details) => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + rollback, + activeVersionId: '11111111-1111-4111-8111-111111111111', + }); + expect(message).toContain(details); + expect(message).not.toContain('restored triggers'); + }); + + it('reports the uploaded version when the final deployment status read fails', () => { + const versionId = '22222222-2222-4222-8222-222222222222'; + const message = formatCloudflareActivationError({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + versionId, + rollback: 'succeeded', + activeVersionId: '11111111-1111-4111-8111-111111111111', + }); + expect(message).toContain(`Worker version ${versionId} was uploaded`); + expect(message).toContain('Void removed the staged version'); + }); + + it('reports the uploaded version when the final deployment status shows a traffic split', () => { + const versionId = '22222222-2222-4222-8222-222222222222'; + const message = formatCloudflareActivationError({ + ok: false, + reason: 'traffic-split-unsupported', + beforeActivation: true, + versionId, + }); + expect(message).toContain(`Worker version ${versionId} was uploaded but not activated`); + expect(message).not.toContain('no version was uploaded'); + }); + it('does not suggest an account subdomain when workers.dev is off', () => { const versionId = '22222222-2222-4222-8222-222222222222'; for (const reason of [ From 8e06a25361b43ae253014d561ee1a2772eab0e40 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Thu, 26 Nov 2026 15:34:31 +0800 Subject: [PATCH 2/4] fix(deploy-cloudflare): match staging snapshots by deployment ID --- packages/deploy-cloudflare/src/version.ts | 111 ++++++++-------- .../test/unit/version.test.ts | 121 ++++++++++++++++-- .../void/src/cli/deploy-cloudflare-helpers.ts | 12 +- .../void/test/unit/cloudflare-deploy.test.ts | 59 ++++++--- 4 files changed, 216 insertions(+), 87 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 3905fabf1..f82f20297 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -169,6 +169,7 @@ type CurrentProductionVersion = kind: 'ok'; versionId: string | null; versions: ReadonlyArray; + deploymentId?: string; } | { kind: 'failed'; status: number } | { kind: 'split' }; @@ -1563,7 +1564,7 @@ async function activateCloudflareVersionWithSecretsFile( : undefined; let readinessUrl = reportedPreviewUrl; let readinessUsesCustomRoute = false; - let stagedVersionOverride = false; + let stagedVersionOverride: Extract | undefined; if (!readinessUrl) { if ( !options.preserveTriggers && @@ -1588,16 +1589,16 @@ async function activateCloudflareVersionWithSecretsFile( if (fallbackSubdomain && fallbackSubdomain === options.readinessHeadersWorkersDevSubdomain) { authenticatedWorkersDevSubdomain = fallbackSubdomain; } - const stagingFailure = await stageCandidateForReadiness( + const staging = await stageCandidateForReadiness( options, previous.versionId, versionId, message, ); - if (stagingFailure) { - return stagingFailure; + if (!staging.ok) { + return staging; } - stagedVersionOverride = true; + stagedVersionOverride = staging; } else if ( desiredTriggerConfig.workers_dev || desiredTriggerConfig.routes.length > 0 || @@ -1659,19 +1660,19 @@ async function activateCloudflareVersionWithSecretsFile( ) : customRouteReadinessUrl(desiredTriggerConfig.routes); if (stableReadinessUrl && stableReadinessUrl !== readinessUrl) { - const stagingFailure = await stageCandidateForReadiness( + const staging = await stageCandidateForReadiness( options, previous.versionId, versionId, message, ); - if (stagingFailure) { - return stagingFailure; + if (!staging.ok) { + return staging; } readinessUrl = stableReadinessUrl; authenticatedWorkersDevSubdomain = extractWorkersDevSubdomain(stableReadinessUrl); readinessUsesCustomRoute = !desiredTriggerConfig.workers_dev; - stagedVersionOverride = true; + stagedVersionOverride = staging; ready = await probe(readinessUrl); } } @@ -1717,42 +1718,45 @@ async function activateCloudflareVersionWithSecretsFile( const stagedTraffic = stagedVersionOverride ? stagedVersionPercentages(previous.versionId, versionId) : undefined; - const isLaggingStagingStatus = (owner: CurrentProductionVersion) => - stagedTraffic !== undefined && - previous.versionId !== null && - owner.kind === 'ok' && - productionVersionPercentagesEqual(owner.versions, previousTraffic); let ownerBeforeActivation = await readCurrentProductionVersion(options); - const statusDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; - for ( - let attempt = 0; - attempt < statusDelays.length && isLaggingStagingStatus(ownerBeforeActivation); - attempt++ - ) { - if (attempt === 0) { - options.onProgress?.( - "Waiting for Cloudflare's deployment status to show the staged version...", - ); - } - await (options.sleep ?? delay)(statusDelays[attempt]); - if (!options.verifyUploader()) { - return { - ok: false, - reason: 'uploader-changed', - versionId, - previousVersionId: previous.versionId, - }; + let laggingStagingStatus = false; + if (stagedVersionOverride?.previousDeploymentId) { + const { previousDeploymentId } = stagedVersionOverride; + const isLaggingStagingStatus = (owner: CurrentProductionVersion) => + owner.kind === 'ok' && + owner.deploymentId === previousDeploymentId && + productionVersionPercentagesEqual(owner.versions, previousTraffic); + const statusDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; + for ( + let attempt = 0; + attempt < statusDelays.length && isLaggingStagingStatus(ownerBeforeActivation); + attempt++ + ) { + if (attempt === 0) { + options.onProgress?.( + "Waiting for Cloudflare's deployment status to show the staged version...", + ); + } + await (options.sleep ?? delay)(statusDelays[attempt]); + if (!options.verifyUploader()) { + return { + ok: false, + reason: 'uploader-changed', + versionId, + previousVersionId: previous.versionId, + rollback: 'unsafe', + }; + } + ownerBeforeActivation = await readCurrentProductionVersion(options); } - ownerBeforeActivation = await readCurrentProductionVersion(options); + laggingStagingStatus = isLaggingStagingStatus(ownerBeforeActivation); } if (ownerBeforeActivation.kind === 'split') { return { ok: false, reason: 'traffic-split-unsupported', - beforeActivation: true, versionId, previousVersionId: previous.versionId, - rollback: 'not-needed', }; } if ( @@ -1768,20 +1772,20 @@ async function activateCloudflareVersionWithSecretsFile( ? { reason: 'status-failed' as const, status: ownerBeforeActivation.status } : { reason: 'deployment-changed' as const }; const restore = - stagedTraffic?.length && - (ownerBeforeActivation.kind === 'failed' || isLaggingStagingStatus(ownerBeforeActivation)) + stagedTraffic?.length && (ownerBeforeActivation.kind === 'failed' || laggingStagingStatus) ? await restorePreviousVersion( options, previous.versionId, 'pre-activation status check failed', [stagedTraffic], ) - : { - rollback: 'not-needed' as const, - ...(ownerBeforeActivation.kind === 'ok' - ? { activeVersionId: ownerBeforeActivation.versionId } - : {}), - }; + : ownerBeforeActivation.kind === 'ok' + ? { + activeVersionId: ownerBeforeActivation.versionId, + rollback: 'not-needed' as const, + ...(stagedTraffic === undefined ? { triggerRepair: 'succeeded' as const } : {}), + } + : {}; return { ok: false, ...failure, @@ -2887,6 +2891,7 @@ async function readCurrentProductionVersion( versionId: active?.versionId ?? null, versions, deployment, + deploymentId: typeof deployment.id === 'string' ? deployment.id : undefined, }; } catch { return { kind: 'failed', status: result.status }; @@ -2920,13 +2925,17 @@ function stagedVersionPercentages( : []; } +type ReadinessStagingResult = + | { ok: true; previousDeploymentId: string | undefined } + | Extract; + /** Stage the candidate at 0% beside the unchanged previous version so readiness can select it. */ async function stageCandidateForReadiness( options: CloudflareVersionActivationOptions, previousVersionId: string | null, versionId: string, message: string, -): Promise | null> { +): Promise { if (!options.verifyUploader()) { return { ok: false, @@ -2936,9 +2945,9 @@ async function stageCandidateForReadiness( rollback: 'not-needed', }; } - const ownerFailure = await verifyReadinessStagingOwner(options, previousVersionId, versionId); - if (ownerFailure) { - return ownerFailure; + const owner = await verifyReadinessStagingOwner(options, previousVersionId, versionId); + if (!owner.ok) { + return owner; } const staged = await deployVersionPercentages( options, @@ -2958,7 +2967,7 @@ async function stageCandidateForReadiness( rollback: 'not-needed', }; } - return null; + return owner; } async function verifyReadinessStagingOwner( @@ -2968,7 +2977,7 @@ async function verifyReadinessStagingOwner( >, previousVersionId: string | null, versionId: string, -): Promise | null> { +): Promise { const owner = await readCurrentProductionVersion(options); if (owner.kind === 'failed') { return { @@ -3004,7 +3013,7 @@ async function verifyReadinessStagingOwner( ...cloudflareStagingPairGuidance(owner.deployment, options), }; } - return null; + return { ok: true, previousDeploymentId: owner.deploymentId }; } async function probeReadiness( diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index bd11aeec0..3c76de3e2 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -3930,16 +3930,26 @@ describe('Cloudflare version activation', () => { }); describe('staged deployment status', () => { - const status = (...versions: Array) => ok(JSON.stringify({ versions })); - const previous = status({ version_id: CURRENT, percentage: 100 }); - const concurrent = status({ version_id: CONCURRENT, percentage: 100 }); + const status = (id: string | undefined, ...versions: Array) => ({ + ...ok(), + data: { id, versions }, + }); + const beforeUpload = status('before-upload', { version_id: CURRENT, percentage: 100 }); + const previous = status('before-staging', { version_id: CURRENT, percentage: 100 }); + const concurrent = status('concurrent', { version_id: CONCURRENT, percentage: 100 }); const staging = [`${CURRENT}@100`, `${NEXT}@0`]; function stagedActivation(...statusReads: Array) { const base = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); let staged = false; + let readBeforeUpload = false; const runWrangler = operationFixture((args: Array) => { - if (staged && args[0] === 'deployments') { + if (args[0] === 'deployments') { + if (!staged) { + const read = readBeforeUpload ? previous : beforeUpload; + readBeforeUpload = true; + return read; + } const read = statusReads.shift(); if (read) { return read; @@ -3980,7 +3990,11 @@ describe('Cloudflare version activation', () => { ['a different active version', concurrent, CONCURRENT], [ 'a different staged version', - status({ version_id: CURRENT, percentage: 100 }, { version_id: CONCURRENT, percentage: 0 }), + status( + 'concurrent', + { version_id: CURRENT, percentage: 100 }, + { version_id: CONCURRENT, percentage: 0 }, + ), CURRENT, ], ] as const)( @@ -4003,6 +4017,30 @@ describe('Cloudflare version activation', () => { }, ); + it.each([ + ['a different deployment ID', 'concurrent'], + ['no deployment ID', undefined], + ] as const)('stops at the same active version with %s during the wait', async (_kind, id) => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + status(id, { version_id: CURRENT, percentage: 100 }), + status( + 'staged', + { version_id: CURRENT, percentage: 100 }, + { version_id: NEXT, percentage: 0 }, + ), + ); + + await expect(activateCloudflareVersion(options)).resolves.toMatchObject({ + ok: false, + reason: 'deployment-changed', + activeVersionId: CURRENT, + rollback: 'not-needed', + }); + expect(sleep).not.toHaveBeenCalledWith(29); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + it('clears its staging deployment if the status only catches up during the final ownership check', async () => { const { options, runWrangler, sleep } = stagedActivation(previous, previous, previous); @@ -4066,16 +4104,18 @@ describe('Cloudflare version activation', () => { it('stops at a split during the wait without writing traffic', async () => { const { options, runWrangler, sleep } = stagedActivation( previous, - status({ version_id: CURRENT, percentage: 50 }, { version_id: CONCURRENT, percentage: 50 }), + status( + 'concurrent', + { version_id: CURRENT, percentage: 50 }, + { version_id: CONCURRENT, percentage: 50 }, + ), ); await expect(activateCloudflareVersion(options)).resolves.toEqual({ ok: false, reason: 'traffic-split-unsupported', - beforeActivation: true, versionId: NEXT, previousVersionId: CURRENT, - rollback: 'not-needed', }); expect(sleep.mock.calls).toEqual([[17]]); expect(deployRequests(runWrangler)).toEqual([staging]); @@ -4090,13 +4130,74 @@ describe('Cloudflare version activation', () => { await expect( activateCloudflareVersion({ ...options, verifyUploader: () => trusted }), - ).resolves.toMatchObject({ ok: false, reason: 'uploader-changed' }); + ).resolves.toMatchObject({ ok: false, reason: 'uploader-changed', rollback: 'unsafe' }); expect(sleep.mock.calls).toEqual([[17]]); - expect(runWrangler.mock.calls.filter(([args]) => args[0] === 'deployments')).toHaveLength(3); + expect(runWrangler.mock.invocationCallOrder.at(-1)).toBeLessThan( + sleep.mock.invocationCallOrder[0], + ); expect(deployRequests(runWrangler)).toEqual([staging]); }); }); + it.each([ + [ + 'failed', + { ...ok(), status: 7 }, + { reason: 'status-failed', status: 7, beforeActivation: true }, + ], + [ + 'different active version', + ok(JSON.stringify({ versions: [{ version_id: CONCURRENT, percentage: 100 }] })), + { + reason: 'deployment-changed', + activeVersionId: CONCURRENT, + rollback: 'not-needed', + triggerRepair: 'succeeded', + beforeActivation: true, + }, + ], + [ + 'split', + ok( + JSON.stringify({ + versions: [ + { version_id: CURRENT, percentage: 50 }, + { version_id: CONCURRENT, percentage: 50 }, + ], + }), + ), + { reason: 'traffic-split-unsupported' }, + ], + ] as const)( + 'preserves the result for a %s final status read without staging', + async (_kind, read, expected) => { + const base = runner(); + let statusReads = 0; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'deployments' && ++statusReads === 2) { + return read; + } + return base(args); + }); + + await expect( + activateCloudflareVersion({ + runWrangler, + verifyUploader: () => true, + workerName: 'my-worker', + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + }), + ).resolves.toEqual({ + ok: false, + versionId: NEXT, + previousVersionId: CURRENT, + ...expected, + }); + expect(deployRequests(runWrangler)).toEqual([]); + }, + ); + it('does not stage over a production owner that changed after upload', async () => { let statusCalls = 0; const runWrangler = operationFixture(async (args: Array) => { diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index dfeba5a60..6aab426f4 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -557,11 +557,11 @@ export function formatCloudflareActivationError( function formatStagingCleanup(result: Exclude): string { switch (result.rollback) { case 'succeeded': - return ` Void removed the staged version. Worker version ${result.activeVersionId ?? '(unknown)'} continues serving 100% of traffic.`; + return ' Void redeployed the previous version at 100% of traffic.'; case 'failed': - return ' Cloudflare did not confirm removal of the staged version.'; + return ' Void tried to redeploy the previous version at 100% of traffic, but Cloudflare did not confirm it.'; case 'unsafe': - return ' Void could not safely remove its staged version.'; + return ' Void left its 0% staging deployment in place because it could not confirm that deployment is still its own.'; default: return ''; } @@ -605,7 +605,7 @@ function formatCloudflareActivationFailure( return result.diagnostic; } if (result.beforeActivation) { - return `deploy: Cloudflare deployment status did not match the expected traffic.${stagingCleanup} Inspect the active Worker version ${result.activeVersionId ?? '(unknown)'} before retrying.`; + return `deploy: Cloudflare deployment status did not show the expected deployment before activation.${stagingCleanup} Inspect \`void project status\` before retrying.`; } return result.triggerRepair === 'succeeded' ? `deploy: another Cloudflare operation superseded this deployment. Void restored triggers for the active version ${result.activeVersionId ?? '(unknown)'}; retry from fresh deployment status.` @@ -633,8 +633,8 @@ function formatCloudflareActivationFailure( return [ 'deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.', 'Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout', - result.beforeActivation && result.versionId - ? `in Cloudflare, then retry. Worker version ${result.versionId} was uploaded but not activated.` + result.versionId + ? `in Cloudflare, then retry. Void uploaded Worker version ${result.versionId} and stopped before activating it.` : 'in Cloudflare, then retry; no version was uploaded.', ].join('\n'); case 'upload-failed': diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 29a54789e..5b52ca2fc 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -528,19 +528,26 @@ describe('Cloudflare activation diagnostics', () => { ); it.each([ - ['succeeded', 'continues serving 100% of traffic'], - ['unsafe', 'Void could not safely remove its staged version'], - ['failed', 'Cloudflare did not confirm removal of the staged version'], + ['succeeded', ' Void redeployed the previous version at 100% of traffic.'], + [ + 'unsafe', + ' Void left its 0% staging deployment in place because it could not confirm that deployment is still its own.', + ], + [ + 'failed', + ' Void tried to redeploy the previous version at 100% of traffic, but Cloudflare did not confirm it.', + ], + ['not-needed', ''], ] as const)('reports staging cleanup outcome %s', (rollback, details) => { const message = formatCloudflareActivationError({ ok: false, reason: 'deployment-changed', beforeActivation: true, rollback, - activeVersionId: '11111111-1111-4111-8111-111111111111', }); - expect(message).toContain(details); - expect(message).not.toContain('restored triggers'); + expect(message).toBe( + `deploy: Cloudflare deployment status did not show the expected deployment before activation.${details} Inspect \`void project status\` before retrying.`, + ); }); it('reports the uploaded version when the final deployment status read fails', () => { @@ -551,23 +558,35 @@ describe('Cloudflare activation diagnostics', () => { beforeActivation: true, versionId, rollback: 'succeeded', - activeVersionId: '11111111-1111-4111-8111-111111111111', }); - expect(message).toContain(`Worker version ${versionId} was uploaded`); - expect(message).toContain('Void removed the staged version'); + expect(message).toBe( + `deploy: Worker version ${versionId} was uploaded, but Cloudflare deployment status could not be verified before activation. Void redeployed the previous version at 100% of traffic. Inspect \`void project status\` before retrying.`, + ); }); - it('reports the uploaded version when the final deployment status shows a traffic split', () => { - const versionId = '22222222-2222-4222-8222-222222222222'; - const message = formatCloudflareActivationError({ - ok: false, - reason: 'traffic-split-unsupported', - beforeActivation: true, - versionId, - }); - expect(message).toContain(`Worker version ${versionId} was uploaded but not activated`); - expect(message).not.toContain('no version was uploaded'); - }); + it.each([ + [ + '22222222-2222-4222-8222-222222222222', + 'in Cloudflare, then retry. Void uploaded Worker version 22222222-2222-4222-8222-222222222222 and stopped before activating it.', + ], + [undefined, 'in Cloudflare, then retry; no version was uploaded.'], + ] as const)( + 'describes the upload state when the deployment status shows a traffic split (%s)', + (versionId, lastLine) => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'traffic-split-unsupported', + versionId, + }); + expect(message).toBe( + [ + 'deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.', + 'Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout', + lastLine, + ].join('\n'), + ); + }, + ); it('does not suggest an account subdomain when workers.dev is off', () => { const versionId = '22222222-2222-4222-8222-222222222222'; From f1d1f7fca237fefc34cd3c134d846080ec0221be Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Thu, 26 Nov 2026 16:01:40 +0800 Subject: [PATCH 3/4] fix(deploy-cloudflare): clarify staging cleanup diagnostics --- packages/deploy-cloudflare/src/version.ts | 4 ++- .../test/unit/version.test.ts | 17 +++++++---- .../void/src/cli/deploy-cloudflare-helpers.ts | 6 ++-- .../void/test/unit/cloudflare-deploy.test.ts | 29 ++++++++++++++++--- 4 files changed, 43 insertions(+), 13 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index f82f20297..f7eeb4b8d 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -121,7 +121,7 @@ export type CloudflareVersionActivation = diagnostic?: string; /** Wrangler reached Cloudflare's Containers entitlement endpoint and received a 403. */ containersUnavailable?: boolean; - /** The final status check stopped activation after the version was uploaded. */ + /** The deployment stopped after upload and before activation. */ beforeActivation?: true; versionId?: string; previousVersionId?: string | null; @@ -1697,6 +1697,7 @@ async function activateCloudflareVersionWithSecretsFile( return { ok: false, reason: 'uploader-changed', + beforeActivation: true, versionId, previousVersionId: previous.versionId, ...(stagedVersionOverride @@ -1742,6 +1743,7 @@ async function activateCloudflareVersionWithSecretsFile( return { ok: false, reason: 'uploader-changed', + beforeActivation: true, versionId, previousVersionId: previous.versionId, rollback: 'unsafe', diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 3c76de3e2..604a45ea4 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -4130,7 +4130,12 @@ describe('Cloudflare version activation', () => { await expect( activateCloudflareVersion({ ...options, verifyUploader: () => trusted }), - ).resolves.toMatchObject({ ok: false, reason: 'uploader-changed', rollback: 'unsafe' }); + ).resolves.toMatchObject({ + ok: false, + reason: 'uploader-changed', + beforeActivation: true, + rollback: 'unsafe', + }); expect(sleep.mock.calls).toEqual([[17]]); expect(runWrangler.mock.invocationCallOrder.at(-1)).toBeLessThan( sleep.mock.invocationCallOrder[0], @@ -4141,12 +4146,12 @@ describe('Cloudflare version activation', () => { it.each([ [ - 'failed', + 'adds beforeActivation when the final status read fails', { ...ok(), status: 7 }, { reason: 'status-failed', status: 7, beforeActivation: true }, ], [ - 'different active version', + 'adds beforeActivation when the final status read reports a different deployment', ok(JSON.stringify({ versions: [{ version_id: CONCURRENT, percentage: 100 }] })), { reason: 'deployment-changed', @@ -4157,7 +4162,7 @@ describe('Cloudflare version activation', () => { }, ], [ - 'split', + 'reports the traffic split from the final status read', ok( JSON.stringify({ versions: [ @@ -4169,8 +4174,8 @@ describe('Cloudflare version activation', () => { { reason: 'traffic-split-unsupported' }, ], ] as const)( - 'preserves the result for a %s final status read without staging', - async (_kind, read, expected) => { + '%s after readiness succeeds on the path without a staging deployment', + async (_title, read, expected) => { const base = runner(); let statusReads = 0; const runWrangler = operationFixture((args: Array) => { diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 6aab426f4..6b9d925fc 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -561,7 +561,7 @@ function formatStagingCleanup(result: Exclude { it.each([ ['succeeded', ' Void redeployed the previous version at 100% of traffic.'], - [ - 'unsafe', - ' Void left its 0% staging deployment in place because it could not confirm that deployment is still its own.', - ], [ 'failed', ' Void tried to redeploy the previous version at 100% of traffic, but Cloudflare did not confirm it.', @@ -550,6 +546,31 @@ describe('Cloudflare activation diagnostics', () => { ); }); + it('reports an uploader change before activation when staging cleanup is unsafe', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'uploader-changed', + beforeActivation: true, + rollback: 'unsafe', + }); + expect(message).toBe( + 'deploy: the verified Wrangler uploader changed before version activation. Void did not invoke the changed binary to remove its 0% staging deployment; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.', + ); + }); + + it('reports that the current deployment is unchanged when staging ownership is unconfirmed', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + activeVersionId: 'another-version', + rollback: 'unsafe', + }); + expect(message).toBe( + "deploy: Cloudflare deployment status did not show the expected deployment before activation. Void left the current deployment unchanged because it could not confirm it is Void's 0% staging deployment. Inspect `void project status` before retrying.", + ); + }); + it('reports the uploaded version when the final deployment status read fails', () => { const versionId = '22222222-2222-4222-8222-222222222222'; const message = formatCloudflareActivationError({ From 1eb92ff7cf746f9e8b09ffacb472eca86912980f Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 27 Nov 2026 08:35:37 +0800 Subject: [PATCH 4/4] fix(deploy-cloudflare): verify staging deployment identity --- packages/deploy-cloudflare/src/version.ts | 41 +++++- .../test/unit/operations.test.ts | 10 +- .../test/unit/version.test.ts | 54 +++++++- .../void/src/cli/deploy-cloudflare-helpers.ts | 7 +- .../void/test/unit/cloudflare-deploy.test.ts | 130 +++++++++++++++++- 5 files changed, 223 insertions(+), 19 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index f7eeb4b8d..9c6760e5c 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1686,9 +1686,13 @@ async function activateCloudflareVersionWithSecretsFile( ? customRouteReadinessOriginField(readinessUrl) : {}), ...(stagedVersionOverride - ? await restorePreviousVersion(options, previous.versionId, 'readiness failed', [ - stagedVersionPercentages(previous.versionId, versionId), - ]) + ? await restorePreviousVersion( + options, + previous.versionId, + 'readiness failed', + [stagedVersionPercentages(previous.versionId, versionId)], + stagedVersionOverride.deploymentId, + ) : { rollback: 'not-needed' as const }), }; } @@ -1706,6 +1710,7 @@ async function activateCloudflareVersionWithSecretsFile( previous.versionId, 'uploader verification failed', [stagedVersionPercentages(previous.versionId, versionId)], + stagedVersionOverride.deploymentId, ) : { rollback: 'not-needed' as const }), }; @@ -1764,6 +1769,8 @@ async function activateCloudflareVersionWithSecretsFile( if ( ownerBeforeActivation.kind === 'failed' || ownerBeforeActivation.versionId !== previous.versionId || + (stagedVersionOverride !== undefined && + ownerBeforeActivation.deploymentId !== stagedVersionOverride.deploymentId) || !productionVersionPercentagesEqual( ownerBeforeActivation.versions, stagedTraffic ?? previousTraffic, @@ -1774,12 +1781,15 @@ async function activateCloudflareVersionWithSecretsFile( ? { reason: 'status-failed' as const, status: ownerBeforeActivation.status } : { reason: 'deployment-changed' as const }; const restore = - stagedTraffic?.length && (ownerBeforeActivation.kind === 'failed' || laggingStagingStatus) + stagedVersionOverride && + stagedTraffic?.length && + (ownerBeforeActivation.kind === 'failed' || laggingStagingStatus) ? await restorePreviousVersion( options, previous.versionId, 'pre-activation status check failed', [stagedTraffic], + stagedVersionOverride.deploymentId, ) : ownerBeforeActivation.kind === 'ok' ? { @@ -2928,7 +2938,7 @@ function stagedVersionPercentages( } type ReadinessStagingResult = - | { ok: true; previousDeploymentId: string | undefined } + | { ok: true; previousDeploymentId: string | undefined; deploymentId: string } | Extract; /** Stage the candidate at 0% beside the unchanged previous version so readiness can select it. */ @@ -2969,7 +2979,19 @@ async function stageCandidateForReadiness( rollback: 'not-needed', }; } - return owner; + const deploymentId = isRecord(staged.data) ? staged.data.id : undefined; + if (typeof deploymentId !== 'string' || !deploymentId.trim()) { + return { + ok: false, + reason: 'status-failed', + beforeActivation: true, + diagnostic: 'Cloudflare did not return the 0% staging deployment ID.', + versionId, + previousVersionId, + rollback: 'unsafe', + }; + } + return { ...owner, deploymentId }; } async function verifyReadinessStagingOwner( @@ -2979,7 +3001,10 @@ async function verifyReadinessStagingOwner( >, previousVersionId: string | null, versionId: string, -): Promise { +): Promise< + | { ok: true; previousDeploymentId: string | undefined } + | Extract +> { const owner = await readCurrentProductionVersion(options); if (owner.kind === 'failed') { return { @@ -3280,6 +3305,7 @@ async function restorePreviousVersion( previousVersionId: string | null, cause: string, expectedOwnedTraffic: ReadonlyArray>, + expectedDeploymentId?: string, ): Promise { if (!previousVersionId) { return { rollback: 'unavailable' }; @@ -3292,6 +3318,7 @@ async function restorePreviousVersion( return { owns: owner.kind === 'ok' && + (expectedDeploymentId === undefined || owner.deploymentId === expectedDeploymentId) && expectedOwnedTraffic.some((expected) => productionVersionPercentagesEqual(owner.versions, expected), ), diff --git a/packages/deploy-cloudflare/test/unit/operations.test.ts b/packages/deploy-cloudflare/test/unit/operations.test.ts index 6054e3672..fbf05a268 100644 --- a/packages/deploy-cloudflare/test/unit/operations.test.ts +++ b/packages/deploy-cloudflare/test/unit/operations.test.ts @@ -8,7 +8,6 @@ import { activateCloudflareVersion, encodeCloudflareVersionMessage } from '../.. const current = '11111111-1111-4111-8111-111111111111'; const next = '22222222-2222-4222-8222-222222222222'; -const other = '33333333-3333-4333-8333-333333333333'; function setup( data: unknown, @@ -19,6 +18,7 @@ function setup( const calls: Array = []; let uploaded = false; let triggerFailed = false; + let deployment = 0; let versions = [{ version_id: current, percentage: 100 }]; const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { calls.push(operation); @@ -30,7 +30,7 @@ function setup( }); switch (operation.type) { case 'deployments.status': - return ok({ versions }); + return ok({ id: String(deployment), versions }); case 'versions.list': return ok([ { @@ -63,7 +63,7 @@ function setup( return { ...ok(), status: 1, errorCode: 10_000 }; } if (rollback === 'deployed-elsewhere') { - versions = [{ version_id: other, percentage: 100 }]; + deployment++; } return { ...ok(), status: 1, errorCode: 10_220 }; } @@ -79,7 +79,7 @@ function setup( version_id: versionId, percentage, })); - return ok(); + return ok({ id: String(++deployment) }); case 'triggers.deploy': if (failure === 'triggers' && !triggerFailed) { triggerFailed = true; @@ -207,7 +207,7 @@ it.each(recoveries)( }, ); -it('does not force a restore after someone else deploys', async () => { +it('does not force a restore after another deployment reuses the staged split', async () => { const { result, rollbacks } = await recover(recoveries[0], 'deployed-elsewhere'); expect(result).toMatchObject({ ok: false, reason: 'readiness-failed', rollback: 'unsafe' }); expect(result).not.toHaveProperty('restoredOlderSecrets'); diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 604a45ea4..380d0a63d 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -242,6 +242,7 @@ function runner(overrides?: { let triggerCalls = 0; let statusCalls = 0; let activeVersionId: string | null = CURRENT; + let deploymentId = 'initial-deployment'; let deploymentVersions: Array = [{ version_id: CURRENT, percentage: 100 }]; let uploaded = false; return operationFixture((args: Array) => { @@ -254,7 +255,7 @@ function runner(overrides?: { } return overrides.status; } - return ok(JSON.stringify({ versions: deploymentVersions })); + return ok(JSON.stringify({ id: deploymentId, versions: deploymentVersions })); } if (args[0] === 'versions' && args[1] === 'upload') { uploaded = true; @@ -270,12 +271,14 @@ function runner(overrides?: { const result = deployCalls === 1 ? (overrides?.activate ?? ok()) : (overrides?.rollback ?? ok()); if (result.status === 0) { + deploymentId = `deployment-${deployCalls}`; deploymentVersions = args.flatMap((argument) => { const matched = argument.match(/^([^@]+)@(\d+(?:\.\d+)?)$/); return matched ? [{ version_id: matched[1], percentage: Number(matched[2]) }] : []; }); activeVersionId = deploymentVersions.find((version) => version.percentage === 100)?.version_id ?? null; + return { ...result, data: result.data ?? { id: deploymentId } }; } return result; } @@ -3975,6 +3978,48 @@ describe('Cloudflare version activation', () => { }; } + it('skips staging cleanup when a failed status read is followed by a different deployment ID', async () => { + const { options, runWrangler } = stagedActivation( + { ...ok(), status: 1 }, + status( + 'other-staging', + { version_id: CURRENT, percentage: 100 }, + { version_id: NEXT, percentage: 0 }, + ), + ); + + const result = await activateCloudflareVersion(options); + + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(result).toMatchObject({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + rollback: 'unsafe', + }); + }); + + it('stops when the staging write does not report its deployment ID', async () => { + const { options, runWrangler } = stagedActivation(); + + const result = await activateCloudflareVersion({ + ...options, + runWrangler: (operation, command) => { + const result = runWrangler(operation, command); + return operation.type === 'versions.deploy' ? ok() : result; + }, + }); + + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(result).toMatchObject({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + diagnostic: 'Cloudflare did not return the 0% staging deployment ID.', + rollback: 'unsafe', + }); + }); + it('waits for Cloudflare to show its 0% staging deployment before activating', async () => { const { options, runWrangler, sleep } = stagedActivation(previous); @@ -4308,10 +4353,11 @@ describe('Cloudflare version activation', () => { it('does not restore failed readiness staging over a concurrent candidate', async () => { let deploymentVersions = [{ version_id: CURRENT, percentage: 100 }]; + let deploymentId = 'initial'; let deployCalls = 0; const runWrangler = operationFixture(async (args: Array) => { if (args[0] === 'deployments') { - return ok(JSON.stringify({ versions: deploymentVersions })); + return ok(JSON.stringify({ id: deploymentId, versions: deploymentVersions })); } if (args[0] === 'versions' && args[1] === 'list') { return ok(JSON.stringify([{ id: CURRENT, annotations: {} }])); @@ -4321,11 +4367,12 @@ describe('Cloudflare version activation', () => { } if (args[0] === 'versions' && args[1] === 'deploy') { deployCalls++; + deploymentId = 'staged'; deploymentVersions = [ { version_id: CURRENT, percentage: 100 }, { version_id: NEXT, percentage: 0 }, ]; - return ok(); + return { ...ok(), data: { id: deploymentId } }; } throw new Error(`Unexpected command: ${args.join(' ')}`); }); @@ -4338,6 +4385,7 @@ describe('Cloudflare version activation', () => { workersDevSubdomain: 'developer-platform-experience', message: encodeCloudflareVersionMessage([]), fetch: async () => { + deploymentId = 'concurrent'; deploymentVersions = [ { version_id: CURRENT, percentage: 100 }, { version_id: CONCURRENT, percentage: 0 }, diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 6b9d925fc..b604ce267 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -597,7 +597,7 @@ function formatCloudflareActivationFailure( case 'status-failed': if (result.versionId) { if (result.beforeActivation || result.rollback === 'not-needed') { - return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}.${stagingCleanup} Inspect \`void project status\` before retrying.`; + return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}.${stagingCleanup} Inspect \`void project status\` before retrying.${diagnostic}`; } return `deploy: Worker version ${result.versionId} was published, but current deployment status could not be verified${status}. Inspect \`void project status\` before retrying.`; } @@ -864,7 +864,10 @@ function formatCloudflareReadinessRestoration( case 'failed': return 'Automatic traffic restoration failed; inspect `void project status` immediately.'; case 'unsafe': - return 'Void did not invoke the changed Wrangler binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.'; + // Uploader verification stops cleanup before a status read, so activeVersionId is absent. + return result.activeVersionId === undefined + ? 'Void skipped staging cleanup because the verified Wrangler uploader changed. Inspect `void project status` and reinstall Wrangler from a trusted lockfile before retrying.' + : `${formatStagingCleanup(result).trim()} Inspect \`void project status\` before retrying.`; case 'unavailable': return 'No previous version was available to restore; inspect `void project status` immediately.'; default: diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index bfab29ec2..830a86605 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -34,6 +34,7 @@ import { operationFixtureRequest, } from '../../../deploy-cloudflare/test/operation-fixture.ts'; import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts'; +import { createCfVersionRunner } from '../../src/cli/cf-version-runner.ts'; import { readCloudflareLink } from '../../src/cli/cloudflare-link.ts'; import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-validation.ts'; import { @@ -201,6 +202,118 @@ const cleanExit: DeployWranglerRunResult = { error: null, }; +it('does not change traffic when another Cloudflare deployment has the staged split', async () => { + const root = makeProject({ + 'wrangler.json': JSON.stringify({ name: 'site', workers_dev: true }), + }); + const live = '11111111-1111-4111-8111-111111111111'; + const candidate = '22222222-2222-4222-8222-222222222222'; + const stagedTraffic = [ + { version_id: live, percentage: 100 }, + { version_id: candidate, percentage: 0 }, + ]; + const writes: Array> = []; + const runWrangler = createCfVersionRunner({ + output: { directory: root, dispose: async () => {} }, + workerName: 'site', + verifyResources: async () => cleanExit, + runCf: (args) => { + const command = args.slice(1, 3).join(' '); + if (command === 'deployments list') { + return { + ...cleanExit, + stdout: JSON.stringify({ + deployments: [ + { + id: writes.length ? 'other-deployment' : 'live-deployment', + versions: writes.at(-1) ?? [{ version_id: live, percentage: 100 }], + }, + ], + }), + }; + } + if (command === 'versions create') { + return { ...cleanExit, stdout: JSON.stringify({ versionId: candidate }) }; + } + if (command === 'deployments create') { + const versions = JSON.parse(args[args.indexOf('--versions') + 1]) as typeof stagedTraffic; + writes.push(versions); + return { ...cleanExit, stdout: JSON.stringify({ id: 'void-staging', versions }) }; + } + throw new Error(`Unexpected cf command: ${command}`); + }, + }); + + const result = await activateCloudflareVersionPrimitive({ + runWrangler, + configPath: join(root, 'wrangler.json'), + workerName: 'site', + workersDevSubdomain: 'example', + preserveTriggers: true, + message: 'Staged deployment', + verifyUploader: () => true, + fetch: async () => Response.json({ ready: true }), + }); + + expect(writes).toEqual([stagedTraffic]); + expect(result).toMatchObject({ ok: false, reason: 'deployment-changed', beforeActivation: true }); +}); + +it('reports successful staging cleanup when deployment status catches up after the activation check', async () => { + const root = makeProject({ + 'wrangler.json': JSON.stringify({ name: 'site', workers_dev: true }), + }); + const live = '11111111-1111-4111-8111-111111111111'; + const candidate = '22222222-2222-4222-8222-222222222222'; + const previous = { + id: 'live-deployment', + versions: [{ version_id: live, percentage: 100 }], + }; + const staging = { + id: 'void-staging', + versions: [...previous.versions, { version_id: candidate, percentage: 0 }], + }; + // The status read only sees the staging write when Void checks ownership for cleanup. + const statusReads = [previous, previous, previous, staging]; + const writes: Array> = []; + const runWrangler: DeployWranglerRun = (operation) => { + switch (operation.type) { + case 'deployments.status': + return { ...cleanExit, data: statusReads.shift() }; + case 'versions.upload': + return { ...cleanExit, data: { versionId: candidate } }; + case 'versions.deploy': + writes.push( + operation.versions.map(({ versionId, percentage }) => `${versionId}@${percentage}`), + ); + return { ...cleanExit, data: { id: writes.length === 1 ? staging.id : 'restored' } }; + default: + throw new Error(`Unexpected Cloudflare operation: ${operation.type}`); + } + }; + + const result = await activateCloudflareVersionPrimitive({ + runWrangler, + configPath: join(root, 'wrangler.json'), + workerName: 'site', + accountId: 'test-account', + workersDevSubdomain: 'example', + preserveTriggers: true, + message: 'Staged deployment', + verifyUploader: () => true, + fetch: async () => Response.json({ ready: true }), + versionHistoryRetryDelaysMs: [], + }); + + expect(writes).toEqual([[`${live}@100`, `${candidate}@0`], [`${live}@100`]]); + if (result.ok) { + throw new Error('Expected staging cleanup to stop activation'); + } + expect(formatCloudflareActivationError(result)).toBe( + 'deploy: Cloudflare deployment status did not show the expected deployment before activation. Void redeployed the previous version at 100% of traffic. Inspect `void project status` before retrying.', + ); +}); + // Most native deploy failures leave through exit(1), which skips the deploy_end that runDeploy // writes on a throw. These tests read the JSONL file back from a temp home folder. describe('Cloudflare deploy log end record', () => { @@ -794,8 +907,21 @@ describe('Cloudflare activation diagnostics', () => { ok: false, reason: 'readiness-failed', rollback: 'unsafe', + activeVersionId: null, }), - ).toContain('did not invoke the changed Wrangler binary'); + ).toContain( + "could not confirm it is Void's 0% staging deployment. Inspect `void project status` before retrying.", + ); + }); + + it('recommends reinstalling Wrangler when uploader verification blocks readiness cleanup', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'readiness-failed', + rollback: 'unsafe', + }); + expect(message).toContain('the verified Wrangler uploader changed'); + expect(message).toContain('reinstall Wrangler from a trusted lockfile'); }); it.each(['readiness-failed', 'uploader-changed'] as const)( @@ -1875,7 +2001,7 @@ describe('existing Cloudflare site handoff', () => { percentage, })); deploymentId = `publish-${publishes.length}`; - return cleanExit; + return { ...cleanExit, data: { id: deploymentId } }; case 'triggers.deploy': case 'triggers.clear-crons': return cleanExit;