Skip to content

Commit acbdba9

Browse files
fix(deploy): Wait until Cloudflare serves a version before deploying it (#2438)
Production deploys keep stopping at the stage step with Cloudflare error 100146 ("The requested Worker version could not be found"), for example in [43952070458](https://github.com/getsentry/toolkit/actions/runs/43952070458) and [44604518080](https://github.com/getsentry/toolkit/actions/runs/44604518080). Prod stays on the old version, but someone has to restart the deploy. Wrangler's versions deploy fetches each version by ID before it creates the deployment ([source](https://github.com/cloudflare/workers-sdk/blob/wrangler%404.156.1/packages/wrangler/src/versions/deploy.ts)). Stage starts a few seconds after upload, and in that window Cloudflare can still answer 404 for the new version. `deployVersions()` in `scripts/cloudflare-deployment.mjs` is now the only way to move traffic. It waits until Cloudflare returns every version by ID three times in a row, then deploys. 404, 429, 5xx, and network errors mean "not yet"; auth and other errors fail at once. The wait gives up after 60 seconds, before any traffic moves, so a version that never appears fails the job instead of holding the deploy queue. Stage, promote, recovery, and the Docs MCP deploy (which had the same race) all use it. Workflows that call Wrangler's deploy directly are rejected, and AGENTS.md records that rule next to what enforces it. The 60-second limit comes from Cloudflare history: production stages from Nov 10 to Nov 19 ran 3.1 to 5.9 seconds after upload, and the two failures hit the 404 at about 3.6 and 4.6 seconds. Some stages that ran earlier than that succeeded, so the lag looks like lagging replicas rather than a fixed delay. That is why one successful read is not enough. <!-- junior-request-attribution:start --> via @dcramer. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent-dispatch%3Adispatch_cf6800c4aced5971469327ef0837e3a4 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent-dispatch%3Adispatch_cf6800c4aced5971469327ef0837e3a4) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent-dispatch%3Adispatch_cf6800c4aced5971469327ef0837e3a4/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: David Cramer <23610+dcramer@users.noreply.github.com>
1 parent e692073 commit acbdba9

6 files changed

Lines changed: 314 additions & 34 deletions

File tree

‎.github/workflows/deploy-docs-mcp.yml‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,20 @@ jobs:
153153
fi
154154
155155
- name: Deploy exact Docs MCP version
156-
working-directory: apps/docs-mcp
157156
env:
158157
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
159158
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
160159
CANDIDATE_VERSION: ${{ steps.uploaded.outputs.candidate_version }}
161-
run: pnpm exec wrangler versions deploy "$CANDIDATE_VERSION@100" --yes --message "$DEPLOYMENT_MARKER"
160+
run: |
161+
node --input-type=module <<'NODE'
162+
import { deployVersions } from './scripts/cloudflare-deployment.mjs';
163+
await deployVersions(
164+
process.env,
165+
{ [process.env.CANDIDATE_VERSION]: 100 },
166+
process.env.DEPLOYMENT_MARKER,
167+
{ worker: 'docs-mcp' },
168+
);
169+
NODE
162170
163171
- name: Verify active Docs MCP version
164172
env:

‎AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ Toolkit contains the Sentry CLI, the Sentry MCP server, and shared code. Product
1616
- **Lint rules**: Write new lint rules for Oxlint: a built-in rule in `.oxlintrc.json`, or a custom rule in `packages/cli/lint-rules/cli-oxlint-plugin.js`. Do not add ast-grep rules. See docs/contributing/coding-guidelines.md#formatting-and-linting.
1717
- **Package CI**: Put checks for one workspace package in its `package.json` scripts and `sentryCi`, which `test.yml` runs per project. Do not add a workflow for them. See docs/operations/github-actions.md#package-ci-checks.
1818

19+
## Enforced Rules
20+
21+
| Rule | Enforced by |
22+
| ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
23+
| Move Cloudflare traffic only with `deployVersions()`, never `wrangler versions deploy`; Cloudflare 404s (100146) on a fresh version for seconds | `scripts/deploy-workflow.test.mjs` (`pnpm run test:ci-projects`) |
24+
1925
## Repository Structure
2026

2127
```

‎docs/operations/github-actions.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,16 @@ If `main` advances after that check, the deploy job's own revision checks fail i
247247
Failure to identify the prior active version, verify deployment ownership, or
248248
confirm the restored version fails the job rather than guessing a recovery.
249249

250+
Every traffic change goes through `deployVersions()` in
251+
`scripts/cloudflare-deployment.mjs`. Cloudflare can answer 404 (code 100146)
252+
for a version for a few seconds after `wrangler versions upload`, and
253+
`wrangler versions deploy` fails on that read. `deployVersions()` waits until
254+
Cloudflare serves each version by ID on three reads in a row, then deploys. It
255+
gives up after 60 seconds, before any traffic moves, so a version that never
256+
appears fails the job instead of holding the deploy queue.
257+
`scripts/deploy-workflow.test.mjs` fails any workflow that calls
258+
`wrangler versions deploy` directly.
259+
250260
## Manual Deployment
251261

252262
Manual dispatch cannot deploy a new revision. Use a reviewed change and its

‎scripts/cloudflare-deployment.mjs‎

Lines changed: 123 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,16 @@ import { fileURLToPath } from "node:url";
66

77
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
88
const WORKER = "sentry-mcp";
9+
// Wrangler reads each Worker's config from its package directory.
10+
const WORKER_DIRS = {
11+
"sentry-mcp": "../packages/mcp-cloudflare",
12+
"docs-mcp": "../apps/docs-mcp",
13+
};
914
const SETTLE_ATTEMPTS = 15;
1015
const SETTLE_DELAY_MS = 2_000;
16+
const READABLE_STREAK = 3;
17+
// Observed lag is under 6 s; 60 s gives about ten times that.
18+
const READABLE_TIMEOUT_MS = 60_000;
1119

1220
// Messages are fixed strings, so they are safe to print in CI logs, unlike
1321
// errors from fetch or JSON parsing that may carry API content.
@@ -205,8 +213,7 @@ export function assertOwnedCandidate(deployments, journal) {
205213
return journal.previous.version;
206214
}
207215

208-
/** Read deployment history for an existing Worker without exposing API responses. */
209-
export async function listDeployments(env, worker = WORKER) {
216+
function workerApi(env, worker, path) {
210217
if (
211218
!/^[0-9a-f]{32}$/i.test(env.CLOUDFLARE_ACCOUNT_ID ?? "") ||
212219
!env.CLOUDFLARE_API_TOKEN
@@ -215,13 +222,18 @@ export async function listDeployments(env, worker = WORKER) {
215222
"Cloudflare account ID and API token are required",
216223
);
217224
}
218-
const response = await fetch(
219-
`https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${encodeURIComponent(worker)}/deployments?per_page=3`,
225+
return fetch(
226+
`https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${encodeURIComponent(worker)}/${path}`,
220227
{
221228
headers: { Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}` },
222229
signal: AbortSignal.timeout(15_000),
223230
},
224231
);
232+
}
233+
234+
/** Read deployment history for an existing Worker without exposing API responses. */
235+
export async function listDeployments(env, worker = WORKER) {
236+
const response = await workerApi(env, worker, "deployments?per_page=3");
225237
if (!response.ok) {
226238
throw new DeploymentError("Cloudflare deployment lookup failed");
227239
}
@@ -252,6 +264,99 @@ export async function listSettled(
252264
return deployments;
253265
}
254266

267+
/**
268+
* Whether Cloudflare serves the version by ID. Right after `versions upload`
269+
* this read can return 404 (code 100146) for a few seconds, and Wrangler's
270+
* `versions deploy` makes exactly this read before it creates a deployment.
271+
* 404, 429, 5xx, and network errors mean "not yet"; any other answer, such as
272+
* an auth error, cannot fix itself and fails at once.
273+
*/
274+
export async function isVersionReadable(env, versionId, worker = WORKER) {
275+
let response;
276+
try {
277+
response = await workerApi(
278+
env,
279+
worker,
280+
`versions/${encodeURIComponent(versionId)}`,
281+
);
282+
} catch (error) {
283+
if (error instanceof DeploymentError) throw error;
284+
return false;
285+
}
286+
if (
287+
response.status === 404 ||
288+
response.status === 429 ||
289+
response.status >= 500
290+
) {
291+
return false;
292+
}
293+
if (!response.ok) {
294+
throw new DeploymentError("Cloudflare version lookup failed");
295+
}
296+
const body = await response.json();
297+
return body.success === true && body.result?.id === versionId;
298+
}
299+
300+
// Reads can flip between replicas, so one success is not enough. The wait is
301+
// bounded so a version that never appears fails the step instead of holding
302+
// the production deploy queue.
303+
async function waitUntilReadable(
304+
env,
305+
versionIds,
306+
worker,
307+
{ readVersion = isVersionReadable, sleep = delay, now = Date.now } = {},
308+
) {
309+
const deadline = now() + READABLE_TIMEOUT_MS;
310+
let streak = 0;
311+
while (now() < deadline) {
312+
const readable = await Promise.all(
313+
versionIds.map((versionId) => readVersion(env, versionId, worker)),
314+
);
315+
streak = readable.every(Boolean) ? streak + 1 : 0;
316+
if (streak === READABLE_STREAK) return;
317+
await sleep(SETTLE_DELAY_MS);
318+
}
319+
throw new DeploymentError(
320+
"Cloudflare did not serve the Worker version within 60 seconds",
321+
);
322+
}
323+
324+
/**
325+
* The only way to change production traffic. Waits until Cloudflare serves
326+
* every version by ID, then runs `wrangler versions deploy`. Never call
327+
* Wrangler's deploy directly: it fails with 100146 on a version that is not
328+
* readable yet, and that failure stops the rollout.
329+
*/
330+
export async function deployVersions(
331+
env,
332+
traffic,
333+
message,
334+
{ worker = WORKER, spawn = spawnSync, ...options } = {},
335+
) {
336+
const versionIds = Object.keys(traffic);
337+
if (
338+
!Object.hasOwn(WORKER_DIRS, worker) ||
339+
versionIds.length === 0 ||
340+
!versionIds.every((id) => UUID.test(id))
341+
) {
342+
throw new DeploymentError("Invalid Worker versions to deploy");
343+
}
344+
await waitUntilReadable(env, versionIds, worker, options);
345+
runWrangler(
346+
WORKER_DIRS[worker],
347+
[
348+
"versions",
349+
"deploy",
350+
...versionIds.map((id) => `${id}@${traffic[id]}`),
351+
"--yes",
352+
"--message",
353+
message,
354+
],
355+
env,
356+
spawn,
357+
);
358+
}
359+
255360
function runMarker(env) {
256361
if (
257362
!/^[1-9]\d*$/.test(env.SOURCE_RUN_ID ?? env.GITHUB_RUN_ID ?? "") ||
@@ -265,9 +370,10 @@ function runMarker(env) {
265370
return `toolkit-mcp:${env.SOURCE_RUN_ID ?? env.GITHUB_RUN_ID}:${env.SOURCE_RUN_ATTEMPT ?? env.GITHUB_RUN_ATTEMPT}:${env.SOURCE_SHA ?? env.TESTED_SHA}`;
266371
}
267372

268-
function runWrangler(args, env, spawn = spawnSync) {
373+
// Call only from deployVersions.
374+
function runWrangler(dir, args, env, spawn) {
269375
const child = spawn("pnpm", ["exec", "wrangler", ...args], {
270-
cwd: join(import.meta.dirname, "../packages/mcp-cloudflare"),
376+
cwd: join(import.meta.dirname, dir),
271377
env,
272378
stdio: "inherit",
273379
});
@@ -313,18 +419,17 @@ export async function restorePreviousVersion(
313419
deployments,
314420
journal,
315421
env,
316-
{ list = listDeployments, sleep = delay, spawn = spawnSync } = {},
422+
{ list = listDeployments, sleep = delay, ...options } = {},
317423
) {
318424
const previous = assertOwnedCandidate(deployments, journal);
319425
if (!UUID.test(previous)) {
320426
throw new DeploymentError("Invalid captured previous version");
321427
}
322428
const message = `Toolkit recovery ${env.GITHUB_RUN_ID}`;
323-
runWrangler(
324-
["versions", "deploy", `${previous}@100`, "--yes", "--message", message],
325-
env,
326-
spawn,
327-
);
429+
await deployVersions(env, { [previous]: 100 }, message, {
430+
sleep,
431+
...options,
432+
});
328433
const current = await listSettled(
329434
env,
330435
(listed) => newestMessage(listed) === message,
@@ -433,17 +538,10 @@ async function main(command, env) {
433538
"Prior deployment changed before candidate staging",
434539
);
435540
}
436-
runWrangler(
437-
[
438-
"versions",
439-
"deploy",
440-
`${journal.previous.version}@100`,
441-
`${journal.candidateVersion}@0`,
442-
"--yes",
443-
"--message",
444-
`${journal.marker}:stage`,
445-
],
541+
await deployVersions(
446542
env,
543+
{ [journal.previous.version]: 100, [journal.candidateVersion]: 0 },
544+
`${journal.marker}:stage`,
447545
);
448546
// Tells recovery that a stage exists even if Cloudflare does not list it.
449547
const deployed = { ...journal, stageDeployed: true };
@@ -460,16 +558,10 @@ async function main(command, env) {
460558
}
461559
if (command === "promote") {
462560
verifyStagedCandidate(deployments, journal);
463-
runWrangler(
464-
[
465-
"versions",
466-
"deploy",
467-
`${journal.candidateVersion}@100`,
468-
"--yes",
469-
"--message",
470-
`${journal.marker}:promote`,
471-
],
561+
await deployVersions(
472562
env,
563+
{ [journal.candidateVersion]: 100 },
564+
`${journal.marker}:promote`,
473565
);
474566
const promoted = verifyPromotedCandidate(
475567
await listSettled(

0 commit comments

Comments
 (0)