From 4e09e653f743e76fff5fa948d0b0b7429e658daf Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 17:53:09 +0000 Subject: [PATCH 1/3] fix(docs): keep cleanup off prefixes being re-uploaded and the token out of the build Cleanup aged a prefix by its _publish.json, which a same-commit re-upload keeps until its last put, so a concurrent cleanup could delete a prefix mid-upload. Every upload now writes an _uploading.json marker first, cleanup treats the newer of the two as the prefix's last activity, and it re-reads that immediately before each delete. The publish build also no longer receives the job token. A step before the content checkout fetches the release schedule into a file, and the build reads it through DOCS_RELEASE_SCHEDULE_FILE. Assisted-by: AI --- .github/workflows/publish-version.yml | 15 ++++-- apps/docs/package.json | 3 +- apps/docs/scripts/publish/cleanup.mjs | 52 ++++++++++++++---- apps/docs/scripts/publish/cleanup.test.mjs | 54 ++++++++++++++++++- .../docs/scripts/publish/release-schedule.mjs | 19 +++++++ apps/docs/scripts/publish/upload.mjs | 11 ++++ apps/docs/scripts/publish/upload.test.mjs | 35 ++++++++++-- apps/docs/scripts/sync-docs.mjs | 17 ++++-- turbo.json | 3 +- 9 files changed, 184 insertions(+), 25 deletions(-) create mode 100644 apps/docs/scripts/publish/release-schedule.mjs diff --git a/.github/workflows/publish-version.yml b/.github/workflows/publish-version.yml index cb4fa105..b95637bc 100644 --- a/.github/workflows/publish-version.yml +++ b/.github/workflows/publish-version.yml @@ -334,6 +334,16 @@ jobs: node -e 'const p=require(process.argv[1]); for (const k of ["kind","id","root"]) console.log(`${k}=${p[k]}`)' "$RUNNER_TEMP/plan.json" >> "$GITHUB_OUTPUT" cat "$RUNNER_TEMP/plan.json" + - name: Fetch the release schedule + # Before any content is on disk: this is the only step that holds the + # job's token, and the build reads the result from a file. + working-directory: engine/apps/docs + env: + DOCS_GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + pnpm run --silent publish:release-schedule -- --out "$RUNNER_TEMP/release-schedule.json" + - name: Check out the content tree at the resolved commit uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: @@ -401,9 +411,8 @@ jobs: # variable is "1": it builds the semantic index and turns on the # hybrid search dialog. DOCS_SEMANTIC_SEARCH: ${{ vars.DOCS_SEMANTIC_SEARCH }} - # Read-only: the release schedule is public, and the job's own token - # only lifts the anonymous rate limit for the sync's GitHub fetch. - DOCS_GITHUB_TOKEN: ${{ github.token }} + # Fetched above, before the content checkout. + DOCS_RELEASE_SCHEDULE_FILE: ${{ runner.temp }}/release-schedule.json run: | set -euo pipefail pnpm turbo run build --filter=@coder/docs-site diff --git a/apps/docs/package.json b/apps/docs/package.json index a5922062..3005bc9e 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -36,7 +36,8 @@ "publish:cleanup": "node --import tsx scripts/publish/cleanup.mjs", "publish:reconcile": "node --import tsx scripts/publish/reconcile.mjs", "publish:smoke": "node --import tsx scripts/publish/smoke.mjs", - "publish:rollback": "node --import tsx scripts/publish/rollback.mjs" + "publish:rollback": "node --import tsx scripts/publish/rollback.mjs", + "publish:release-schedule": "node --import tsx scripts/publish/release-schedule.mjs" }, "dependencies": { "@coder/docs-build": "workspace:*", diff --git a/apps/docs/scripts/publish/cleanup.mjs b/apps/docs/scripts/publish/cleanup.mjs index 0956b7ac..bd445322 100644 --- a/apps/docs/scripts/publish/cleanup.mjs +++ b/apps/docs/scripts/publish/cleanup.mjs @@ -5,7 +5,7 @@ import { del, list } from "@vercel/blob"; import { parseManifestItems, readManifestItems } from "@coder/docs-manifest"; import { withBlobRetry } from "./blob-retry.mjs"; import { need } from "./env.mjs"; -import { assertArchivePrefix, isArchivePrefix } from "./upload.mjs"; +import { UPLOADING_KEY, assertArchivePrefix, isArchivePrefix } from "./upload.mjs"; const TAG_PREFIX = /^versions\/\d+\.\d+\.\d+\//; @@ -74,25 +74,49 @@ async function* foldedFolders(prefix, token) { } while (cursor); } -async function listPrefixes(token) { +/** + * When a prefix last saw upload activity: the newer of its `_publish.json` + * (written last) and its `_uploading.json` (written first). A same-commit + * re-upload keeps the old index until its final put, so the index alone would + * age an in-flight upload out from under it. Undefined when there is no index. + * + * @param {string} prefix - without a trailing slash + * @param {(options: { prefix: string; limit: number }) => Promise<{ blobs: { uploadedAt: Date | string }[] }>} listPage + */ +export async function lastActivity(prefix, listPage) { + const [index] = (await listPage({ prefix: `${prefix}/_publish.json`, limit: 1 })).blobs; + if (!index) return undefined; + const [marker] = (await listPage({ prefix: `${prefix}/${UPLOADING_KEY}`, limit: 1 })).blobs; + return new Date(Math.max(new Date(index.uploadedAt), marker ? new Date(marker.uploadedAt) : 0)); +} + +/** + * Re-read a prefix's activity immediately before deleting it, because the + * listing that chose it can be minutes old by the time its turn comes. + * + * @param {{ prefix: string; listPage: Parameters[1]; now: Date; graceMs: number }} input + */ +export async function stillDeletable({ prefix, listPage, now, graceMs }) { + const latest = await lastActivity(prefix, listPage); + return latest !== undefined && now.getTime() - latest.getTime() >= graceMs; +} + +async function listPrefixes(token, listPage) { // versions///... : fold twice to enumerate prefixes, then read the // upload time from each prefix's _publish.json object. const prefixes = []; for await (const idFolder of foldedFolders("versions/", token)) { for await (const shaFolder of foldedFolders(idFolder, token)) { - const page = await listWithRetry({ prefix: `${shaFolder}_publish.json`, limit: 1, token }); - const indexBlob = page.blobs[0]; - if (!indexBlob) { + const prefix = shaFolder.replace(/\/$/, ""); + const uploadedAt = await lastActivity(prefix, listPage); + if (!uploadedAt) { // upload.mjs writes _publish.json last, so a prefix without one is an // upload still in flight (or one that failed and will be retried), not // an old orphan. Never judge its age; leave it for a later run. console.log(`cleanup: ${shaFolder} has no _publish.json yet; skipping`); continue; } - prefixes.push({ - prefix: shaFolder.replace(/\/$/, ""), - uploadedAt: new Date(indexBlob.uploadedAt), - }); + prefixes.push({ prefix, uploadedAt }); } } return prefixes; @@ -107,17 +131,23 @@ if (process.argv[1]?.endsWith("cleanup.mjs")) { configId: need("DOCS_VERSIONS_GLOBAL_CONFIG_ID"), }); const referenced = referencedPrefixes(items); - const prefixes = await listPrefixes(token); + const listPage = (options) => listWithRetry({ ...options, token }); + const prefixes = await listPrefixes(token, listPage); + const graceMs = 7 * 24 * 60 * 60 * 1000; const doomed = planCleanup({ prefixes, referenced, now: new Date(), - graceMs: 7 * 24 * 60 * 60 * 1000, + graceMs, }); for (const prefix of doomed) { // Last gate before a destructive call: planCleanup already filtered on // the shape, so this can only fail if that filter is ever loosened. assertArchivePrefix(prefix); + if (!(await stillDeletable({ prefix, listPage, now: new Date(), graceMs }))) { + console.log(`cleanup: ${prefix} saw upload activity since it was listed; skipping`); + continue; + } const urls = []; let cursor; do { diff --git a/apps/docs/scripts/publish/cleanup.test.mjs b/apps/docs/scripts/publish/cleanup.test.mjs index c187cb92..e0d8c01e 100644 --- a/apps/docs/scripts/publish/cleanup.test.mjs +++ b/apps/docs/scripts/publish/cleanup.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { planCleanup, referencedPrefixes } from "./cleanup.mjs"; +import { lastActivity, planCleanup, referencedPrefixes, stillDeletable } from "./cleanup.mjs"; const day = 24 * 60 * 60 * 1000; const now = new Date("2026-09-20T00:00:00Z"); @@ -134,3 +134,55 @@ test("a version served from a Vercel deployment has no archive prefix to protect }); assert.deepEqual([...refs], [`versions/2.35/${"b".repeat(40)}`]); }); + +// A fake store listing: `blobs` maps a full key to its upload time. +function fakeListing(blobs) { + return async ({ prefix }) => ({ + blobs: Object.entries(blobs) + .filter(([key]) => key.startsWith(prefix)) + .map(([pathname, uploadedAt]) => ({ pathname, uploadedAt })), + }); +} + +const orphan = `versions/2.36/${"c".repeat(40)}`; + +test("a prefix's last activity is the newer of its index and its upload marker", async () => { + const old = new Date(now.getTime() - 30 * day); + const recent = new Date(now.getTime() - 1 * day); + assert.deepEqual( + await lastActivity(orphan, fakeListing({ [`${orphan}/_publish.json`]: old })), + old, + ); + assert.deepEqual( + await lastActivity( + orphan, + fakeListing({ [`${orphan}/_publish.json`]: old, [`${orphan}/_uploading.json`]: recent }), + ), + recent, + ); + assert.equal(await lastActivity(orphan, fakeListing({})), undefined); +}); + +test("an in-place re-upload that started after the age check keeps its prefix from being deleted", async () => { + // The index is old because the re-upload has not reached its last put yet; + // only the marker written when the upload started says it is in flight. + const old = new Date(now.getTime() - 30 * day); + const idle = fakeListing({ [`${orphan}/_publish.json`]: old }); + assert.equal( + await stillDeletable({ prefix: orphan, listPage: idle, now, graceMs: 7 * day }), + true, + ); + const uploading = fakeListing({ + [`${orphan}/_publish.json`]: old, + [`${orphan}/_uploading.json`]: new Date(now.getTime() - 1000), + }); + assert.equal( + await stillDeletable({ prefix: orphan, listPage: uploading, now, graceMs: 7 * day }), + false, + ); +}); + +test("a prefix whose index has gone missing is not deleted", async () => { + const listPage = fakeListing({}); + assert.equal(await stillDeletable({ prefix: orphan, listPage, now, graceMs: 0 }), false); +}); diff --git a/apps/docs/scripts/publish/release-schedule.mjs b/apps/docs/scripts/publish/release-schedule.mjs new file mode 100644 index 00000000..a923a6d7 --- /dev/null +++ b/apps/docs/scripts/publish/release-schedule.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +// Fetch the release schedule with the job's token, so the build step that +// compiles the corpus can read it from a file and never holds the token. +import { writeReleaseSchedule } from "@coder/docs-build"; + +const flagAt = process.argv.indexOf("--out"); +const out = flagAt === -1 ? undefined : process.argv[flagAt + 1]; +if (!out || out.startsWith("--")) { + process.stderr.write( + "usage: DOCS_GITHUB_TOKEN=... release-schedule.mjs --out release-schedule.json\n", + ); + process.exit(1); +} +const schedule = await writeReleaseSchedule({ + outFile: out, + token: process.env.DOCS_GITHUB_TOKEN || undefined, + required: true, +}); +console.log(`release schedule: ${schedule?.generatedAt}`); diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index 2f058453..92625da7 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -110,6 +110,9 @@ export function liveArchivePrefix({ items, plan }) { // `_publish.json` hashes are the untrusted build's claims. const OBJECTS_KEY = "_objects.json"; +/** Written first by every upload, so cleanup can tell a prefix being re-uploaded from an idle orphan. */ +export const UPLOADING_KEY = "_uploading.json"; + async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { try { const result = await withBlobRetry( @@ -264,6 +267,14 @@ export async function uploadDir({ storeOrigin ??= new URL(result.url).origin; } } + await putWithRetry(`${prefix}/${UPLOADING_KEY}`, JSON.stringify({ version: 1 }), { + access: "private", + addRandomSuffix: false, + allowOverwrite: true, + contentType: "application/json; charset=utf-8", + cacheControlMaxAge: 60, + token, + }); await Promise.all(Array.from({ length: concurrency }, (_, id) => worker(id))); const recordedFiles = Object.fromEntries( Object.entries(recorded).toSorted(([a], [b]) => (a < b ? -1 : 1)), diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index 63b216ac..d9a5439c 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -97,6 +97,11 @@ test("a tampered contentType in the publish index never reaches the uploaded obj // Every archive object carries the year; only the index, which the publisher // rewrites and reads back, keeps the short TTL. assert.deepEqual(puts, [ + { + key: `${prefix}/_uploading.json`, + contentType: "application/json; charset=utf-8", + maxAge: 60, + }, { key: `${prefix}/_next/static/chunks/a.js`, contentType: "text/javascript; charset=utf-8", @@ -258,6 +263,7 @@ test("a rate-limited put is retried, logged with its key, and the file lands exa store.succeeded.toSorted(), [ ...files.map((f) => `${prefix}/${f}`), + `${prefix}/_uploading.json`, `${prefix}/_objects.json`, `${prefix}/_publish.json`, ].toSorted(), @@ -327,7 +333,12 @@ test("uploadDir sheds concurrency after a 429, down to the floor, and still uplo `${overlap} new files were in flight together after the run reached the floor`, ); // Every key once, each refused key exactly twice, the index last. - const expected = [...sorted, `${prefix}/_objects.json`, `${prefix}/_publish.json`].toSorted(); + const expected = [ + ...sorted, + `${prefix}/_uploading.json`, + `${prefix}/_objects.json`, + `${prefix}/_publish.json`, + ].toSorted(); assert.deepEqual(store.succeeded.toSorted(), expected); assert.ok([...store.attempts.values()].every((n) => n === 2)); assert.equal(store.succeeded.at(-1), `${prefix}/_publish.json`); @@ -500,7 +511,12 @@ test("with reuseFrom, an object whose recorded hash matches is copied instead of }); assert.deepEqual( store.puts.map((p) => p.key), - [`${prefix}/_next/static/chunks/a.js`, `${prefix}/_objects.json`, `${prefix}/_publish.json`], + [ + `${prefix}/_uploading.json`, + `${prefix}/_next/static/chunks/a.js`, + `${prefix}/_objects.json`, + `${prefix}/_publish.json`, + ], ); assert.equal(result.count, 2); assert.equal(result.copied, 1); @@ -529,7 +545,7 @@ test("a source prefix without a readable _objects.json means a full upload, not }); assert.equal(store.copies.length, 0); assert.equal(result.copied, 0); - assert.equal(store.puts.length, 4); + assert.equal(store.puts.length, 5); } }); @@ -592,3 +608,16 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.36" } }), undefined); assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined); }); + +test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + const keys = []; + const blobPut = async (key) => { + keys.push(key); + return { url: `https://store.private.blob.vercel-storage.com/${key}` }; + }; + const prefix = `versions/main/${sha}`; + await uploadDir({ dir, prefix, token: "t", concurrency: 1, blobPut }); + assert.equal(keys[0], `${prefix}/_uploading.json`); + assert.deepEqual(keys.slice(-2), [`${prefix}/_objects.json`, `${prefix}/_publish.json`]); +}); diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index 2e22973d..d2e63793 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -153,15 +153,22 @@ await writeFile(imageSizesPath(appDir), `${JSON.stringify(imageSizes)}\n`); // The fixture corpus renders the committed schedule, so CI needs no network; // a publish must not ship the Releases page without its table. const fixtureCorpus = !single && !process.env.DOCS_REPO; +// A schedule fetched earlier by a step that held the token, so the build that +// compiles the corpus never needs one. +const scheduleFile = process.env.DOCS_RELEASE_SCHEDULE_FILE; const schedule = await writeReleaseSchedule({ outFile: releaseSchedulePath(appDir), token: process.env.DOCS_GITHUB_TOKEN || undefined, required: process.env.DOCS_PUBLISH === "1", - schedule: fixtureCorpus - ? parseReleaseSchedule( - JSON.parse(await readFile(path.join(appDir, "fixtures", "release-schedule.json"), "utf8")), - ) - : undefined, + schedule: scheduleFile + ? parseReleaseSchedule(JSON.parse(await readFile(scheduleFile, "utf8"))) + : fixtureCorpus + ? parseReleaseSchedule( + JSON.parse( + await readFile(path.join(appDir, "fixtures", "release-schedule.json"), "utf8"), + ), + ) + : undefined, }); console.log(`[sync] release schedule: ${schedule ? schedule.generatedAt : "unavailable"}`); diff --git a/turbo.json b/turbo.json index a6b3e9eb..a0decdff 100644 --- a/turbo.json +++ b/turbo.json @@ -31,7 +31,8 @@ "DOCS_SOURCE_REPO", "DOCS_ENGINE_SHA", "DOCS_PUBLISH", - "DOCS_GITHUB_TOKEN" + "DOCS_GITHUB_TOKEN", + "DOCS_RELEASE_SCHEDULE_FILE" ] }, // The app builds consume content/ and public/ written by the uncacheable From f47af9cca5b5adef7d813d4c1f8dc05b0d245bea Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:54 -0700 Subject: [PATCH 2/3] fix(docs): re-check a cleanup candidate inside the retried delete call The re-read that keeps a prefix being re-uploaded from deletion ran before cleanup paged through the prefix's objects, so the real window was that whole listing, with rate-limit waits of up to five minutes per page, plus the delete. A re-upload that wrote its marker inside it would lose every object it had rewritten. Cleanup now lists the objects first and re-reads the index and the marker inside the retried delete closure, so a delete retried after a 429 checks again too. The main block moves into an exported runCleanup with list and delete seams, so the tests drive the delete loop against a fake store: a marker that is fresh at listing time, one that turns fresh while the objects are listed, one that turns fresh between a rate-limited delete and its retry, and an index that vanishes. The skip log now says which of those it was. The listing ages prefixes by the index alone, since the pre-delete re-read is what decides, which halves the list calls per prefix during the batches that compete with uploads. The marker-ordering upload test now holds the marker put open and asserts no object put starts until it resolves, and the release-schedule fetch requires its token instead of quietly going anonymous. Assisted-by: AI --- apps/docs/scripts/publish/cleanup.mjs | 143 +++++++++----- apps/docs/scripts/publish/cleanup.test.mjs | 186 ++++++++++++++---- apps/docs/scripts/publish/env.mjs | 2 +- .../docs/scripts/publish/release-schedule.mjs | 3 +- apps/docs/scripts/publish/upload.test.mjs | 15 +- 5 files changed, 252 insertions(+), 97 deletions(-) diff --git a/apps/docs/scripts/publish/cleanup.mjs b/apps/docs/scripts/publish/cleanup.mjs index bd445322..81c62e9e 100644 --- a/apps/docs/scripts/publish/cleanup.mjs +++ b/apps/docs/scripts/publish/cleanup.mjs @@ -65,55 +65,63 @@ export function planCleanup({ prefixes, referenced, now, graceMs }) { const listWithRetry = (options) => withBlobRetry(() => list(options), { key: `list ${options.prefix}` }); -async function* foldedFolders(prefix, token) { +/** @typedef {(options: { prefix: string; limit?: number; mode?: "folded"; cursor?: string }) => Promise<{ blobs: { url?: string; uploadedAt: Date | string }[]; folders?: string[]; hasMore?: boolean; cursor?: string }>} ListPage */ + +async function* pages(listPage, options) { let cursor; do { - const page = await listWithRetry({ prefix, mode: "folded", limit: 1000, cursor, token }); - for (const folder of page.folders ?? []) yield folder; + const page = await listPage({ ...options, cursor }); + yield page; cursor = page.hasMore ? page.cursor : undefined; } while (cursor); } +async function* foldedFolders(listPage, prefix) { + for await (const page of pages(listPage, { prefix, mode: "folded", limit: 1000 })) { + yield* page.folders ?? []; + } +} + +async function indexTime(prefix, listPage) { + const [index] = (await listPage({ prefix: `${prefix}/_publish.json`, limit: 1 })).blobs; + return index ? new Date(index.uploadedAt) : undefined; +} + /** - * When a prefix last saw upload activity: the newer of its `_publish.json` - * (written last) and its `_uploading.json` (written first). A same-commit - * re-upload keeps the old index until its final put, so the index alone would - * age an in-flight upload out from under it. Undefined when there is no index. - * - * @param {string} prefix - without a trailing slash - * @param {(options: { prefix: string; limit: number }) => Promise<{ blobs: { uploadedAt: Date | string }[] }>} listPage + * The newer of a prefix's index and upload marker; undefined when it has no index. + * @param {string} prefix + * @param {ListPage} listPage */ export async function lastActivity(prefix, listPage) { - const [index] = (await listPage({ prefix: `${prefix}/_publish.json`, limit: 1 })).blobs; + const index = await indexTime(prefix, listPage); if (!index) return undefined; const [marker] = (await listPage({ prefix: `${prefix}/${UPLOADING_KEY}`, limit: 1 })).blobs; - return new Date(Math.max(new Date(index.uploadedAt), marker ? new Date(marker.uploadedAt) : 0)); + return new Date(Math.max(index, marker ? new Date(marker.uploadedAt) : 0)); } /** - * Re-read a prefix's activity immediately before deleting it, because the - * listing that chose it can be minutes old by the time its turn comes. - * - * @param {{ prefix: string; listPage: Parameters[1]; now: Date; graceMs: number }} input + * Why a prefix must be kept right now, or undefined when it may be deleted. + * @param {{ prefix: string; listPage: ListPage; now: Date; graceMs: number }} input */ -export async function stillDeletable({ prefix, listPage, now, graceMs }) { +export async function keepReason({ prefix, listPage, now, graceMs }) { const latest = await lastActivity(prefix, listPage); - return latest !== undefined && now.getTime() - latest.getTime() >= graceMs; + if (latest === undefined) return "its _publish.json is gone"; + if (now.getTime() - latest.getTime() < graceMs) { + return `saw upload activity at ${latest.toISOString()}`; + } + return undefined; } -async function listPrefixes(token, listPage) { - // versions///... : fold twice to enumerate prefixes, then read the - // upload time from each prefix's _publish.json object. +async function listPrefixes(listPage, log) { + // versions///... : fold twice to enumerate prefixes, then age each by its _publish.json. const prefixes = []; - for await (const idFolder of foldedFolders("versions/", token)) { - for await (const shaFolder of foldedFolders(idFolder, token)) { + for await (const idFolder of foldedFolders(listPage, "versions/")) { + for await (const shaFolder of foldedFolders(listPage, idFolder)) { const prefix = shaFolder.replace(/\/$/, ""); - const uploadedAt = await lastActivity(prefix, listPage); + const uploadedAt = await indexTime(prefix, listPage); if (!uploadedAt) { - // upload.mjs writes _publish.json last, so a prefix without one is an - // upload still in flight (or one that failed and will be retried), not - // an old orphan. Never judge its age; leave it for a later run. - console.log(`cleanup: ${shaFolder} has no _publish.json yet; skipping`); + // upload.mjs writes _publish.json last, so this is an upload in flight, not an orphan. + log(`cleanup: ${shaFolder} has no _publish.json yet; skipping`); continue; } prefixes.push({ prefix, uploadedAt }); @@ -122,43 +130,70 @@ async function listPrefixes(token, listPage) { return prefixes; } -if (process.argv[1]?.endsWith("cleanup.mjs")) { - const dryRun = process.argv.includes("--dry-run"); - const token = need("BLOB_READ_WRITE_TOKEN"); - const items = await readManifestItems({ - token: need("DOCS_VERSIONS_WRITE_TOKEN"), - teamId: need("VERCEL_TEAM_ID"), - configId: need("DOCS_VERSIONS_GLOBAL_CONFIG_ID"), - }); +/** + * @param {{ + * items: unknown; + * listPage: ListPage; + * delPage: (urls: string[]) => Promise; + * now?: () => Date; + * graceMs: number; + * dryRun?: boolean; + * log?: (line: string) => void; + * retry?: Parameters[1]; + * }} input + */ +export async function runCleanup({ + items, + listPage, + delPage, + now = () => new Date(), + graceMs, + dryRun = false, + log = console.log, + retry = {}, +}) { const referenced = referencedPrefixes(items); - const listPage = (options) => listWithRetry({ ...options, token }); - const prefixes = await listPrefixes(token, listPage); - const graceMs = 7 * 24 * 60 * 60 * 1000; const doomed = planCleanup({ - prefixes, + prefixes: await listPrefixes(listPage, log), referenced, - now: new Date(), + now: now(), graceMs, }); for (const prefix of doomed) { // Last gate before a destructive call: planCleanup already filtered on // the shape, so this can only fail if that filter is ever loosened. assertArchivePrefix(prefix); - if (!(await stillDeletable({ prefix, listPage, now: new Date(), graceMs }))) { - console.log(`cleanup: ${prefix} saw upload activity since it was listed; skipping`); - continue; - } const urls = []; - let cursor; - do { - const page = await listWithRetry({ prefix: `${prefix}/`, limit: 1000, cursor, token }); + for await (const page of pages(listPage, { prefix: `${prefix}/`, limit: 1000 })) { urls.push(...page.blobs.map((b) => b.url)); - cursor = page.hasMore ? page.cursor : undefined; - } while (cursor); - console.log(`${dryRun ? "would delete" : "deleting"} ${prefix} (${urls.length} objects)`); - if (!dryRun && urls.length > 0) { - await withBlobRetry(() => del(urls, { token }), { key: `delete ${prefix}` }); } + // The re-read sits inside the retried closure so a delete retried after a 429 checks again. + const kept = await withBlobRetry( + async () => { + const reason = await keepReason({ prefix, listPage, now: now(), graceMs }); + if (reason) return reason; + if (!dryRun && urls.length > 0) await delPage(urls); + return undefined; + }, + { ...retry, key: `delete ${prefix}` }, + ); + if (kept) log(`cleanup: ${prefix} ${kept}; skipping`); + else log(`${dryRun ? "would delete" : "deleted"} ${prefix} (${urls.length} objects)`); } - if (doomed.length === 0) console.log("nothing to clean up"); + if (doomed.length === 0) log("nothing to clean up"); +} + +if (process.argv[1]?.endsWith("cleanup.mjs")) { + const token = need("BLOB_READ_WRITE_TOKEN"); + await runCleanup({ + items: await readManifestItems({ + token: need("DOCS_VERSIONS_WRITE_TOKEN"), + teamId: need("VERCEL_TEAM_ID"), + configId: need("DOCS_VERSIONS_GLOBAL_CONFIG_ID"), + }), + listPage: (options) => listWithRetry({ ...options, token }), + delPage: (urls) => del(urls, { token }), + graceMs: 7 * 24 * 60 * 60 * 1000, + dryRun: process.argv.includes("--dry-run"), + }); } diff --git a/apps/docs/scripts/publish/cleanup.test.mjs b/apps/docs/scripts/publish/cleanup.test.mjs index e0d8c01e..dfb8b008 100644 --- a/apps/docs/scripts/publish/cleanup.test.mjs +++ b/apps/docs/scripts/publish/cleanup.test.mjs @@ -1,6 +1,13 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { lastActivity, planCleanup, referencedPrefixes, stillDeletable } from "./cleanup.mjs"; +import { BlobServiceRateLimited } from "@vercel/blob"; +import { + keepReason, + lastActivity, + planCleanup, + referencedPrefixes, + runCleanup, +} from "./cleanup.mjs"; const day = 24 * 60 * 60 * 1000; const now = new Date("2026-09-20T00:00:00Z"); @@ -135,54 +142,157 @@ test("a version served from a Vercel deployment has no archive prefix to protect assert.deepEqual([...refs], [`versions/2.35/${"b".repeat(40)}`]); }); -// A fake store listing: `blobs` maps a full key to its upload time. -function fakeListing(blobs) { - return async ({ prefix }) => ({ - blobs: Object.entries(blobs) - .filter(([key]) => key.startsWith(prefix)) - .map(([pathname, uploadedAt]) => ({ pathname, uploadedAt })), - }); +// A fake store: `blobs` maps a full key to its upload time, and `onList` sees every list call. +function fakeStore(blobs, onList = () => {}) { + const listPage = async (options) => { + onList(options); + const keys = Object.keys(blobs).filter((key) => key.startsWith(options.prefix)); + if (options.mode === "folded") { + const folders = new Set( + keys.map((key) => `${options.prefix}${key.slice(options.prefix.length).split("/")[0]}/`), + ); + return { blobs: [], folders: [...folders], hasMore: false }; + } + return { + blobs: keys.map((pathname) => ({ + pathname, + url: `${store}/${pathname}`, + uploadedAt: blobs[pathname], + })), + hasMore: false, + }; + }; + return { blobs, listPage }; } const orphan = `versions/2.36/${"c".repeat(40)}`; +const live = `versions/2.36/${"a".repeat(40)}`; +const items = { + "line_2-36": { + id: "2.36", + label: "v2.36", + ref: "release/2.36", + sha: "a".repeat(40), + deployment: `${store}/${live}`, + publishedAt: "2026-09-01T00:00:00Z", + }, + mainline: "2.36", +}; +const old = new Date(now.getTime() - 30 * day); + +function archive(extra = {}) { + return { + [`${live}/_publish.json`]: old, + [`${live}/index.html`]: old, + [`${orphan}/_publish.json`]: old, + [`${orphan}/_uploading.json`]: old, + [`${orphan}/index.html`]: old, + ...extra, + }; +} + +async function cleanup(fake, options = {}) { + const deleted = []; + const lines = []; + await runCleanup({ + items, + listPage: fake.listPage, + delPage: async (urls) => { + deleted.push(...urls); + }, + now: () => now, + graceMs: 7 * day, + log: (line) => lines.push(line), + ...options, + ...(options.delPage ? { delPage: (urls) => options.delPage(urls, deleted) } : {}), + }); + return { deleted, lines }; +} test("a prefix's last activity is the newer of its index and its upload marker", async () => { - const old = new Date(now.getTime() - 30 * day); const recent = new Date(now.getTime() - 1 * day); - assert.deepEqual( - await lastActivity(orphan, fakeListing({ [`${orphan}/_publish.json`]: old })), - old, - ); - assert.deepEqual( - await lastActivity( - orphan, - fakeListing({ [`${orphan}/_publish.json`]: old, [`${orphan}/_uploading.json`]: recent }), - ), - recent, - ); - assert.equal(await lastActivity(orphan, fakeListing({})), undefined); + const { listPage: idle } = fakeStore({ [`${orphan}/_publish.json`]: old }); + assert.deepEqual(await lastActivity(orphan, idle), old); + const { listPage: busy } = fakeStore({ + [`${orphan}/_publish.json`]: old, + [`${orphan}/_uploading.json`]: recent, + }); + assert.deepEqual(await lastActivity(orphan, busy), recent); + assert.equal(await lastActivity(orphan, fakeStore({}).listPage), undefined); }); -test("an in-place re-upload that started after the age check keeps its prefix from being deleted", async () => { - // The index is old because the re-upload has not reached its last put yet; - // only the marker written when the upload started says it is in flight. - const old = new Date(now.getTime() - 30 * day); - const idle = fakeListing({ [`${orphan}/_publish.json`]: old }); - assert.equal( - await stillDeletable({ prefix: orphan, listPage: idle, now, graceMs: 7 * day }), - true, +test("an idle unreferenced prefix past the grace period is deleted, every object of it", async () => { + const { deleted } = await cleanup(fakeStore(archive())); + assert.deepEqual(deleted.toSorted(), [ + `${store}/${orphan}/_publish.json`, + `${store}/${orphan}/_uploading.json`, + `${store}/${orphan}/index.html`, + ]); +}); + +test("a dry run deletes nothing", async () => { + const { deleted, lines } = await cleanup(fakeStore(archive()), { dryRun: true }); + assert.deepEqual(deleted, []); + assert.ok(lines.includes(`would delete ${orphan} (3 objects)`)); +}); + +test("a prefix whose upload marker is already fresh at listing time is never deleted", async () => { + const fake = fakeStore( + archive({ [`${orphan}/_uploading.json`]: new Date(now.getTime() - 1000) }), ); - const uploading = fakeListing({ + const { deleted, lines } = await cleanup(fake); + assert.deepEqual(deleted, []); + assert.ok(lines.some((l) => l.startsWith(`cleanup: ${orphan} saw upload activity at `))); +}); + +test("a re-upload that starts while cleanup lists the prefix's objects keeps the prefix", async () => { + // The marker turns fresh during the object listing, after the listing that chose the prefix. + const fake = fakeStore(archive(), ({ prefix }) => { + if (prefix === `${orphan}/`) + fake.blobs[`${orphan}/_uploading.json`] = new Date(now.getTime() - 1000); + }); + const { deleted } = await cleanup(fake); + assert.deepEqual(deleted, []); +}); + +test("a delete retried after a 429 re-checks the prefix first", async () => { + const fake = fakeStore(archive()); + let attempts = 0; + const { deleted } = await cleanup(fake, { + retry: { sleep: async () => {}, onRetry: () => {}, jitter: () => 0 }, + delPage: async (urls, sink) => { + attempts++; + if (attempts === 1) { + fake.blobs[`${orphan}/_uploading.json`] = new Date(now.getTime() - 1000); + throw new BlobServiceRateLimited(1); + } + sink.push(...urls); + }, + }); + assert.equal(attempts, 1); + assert.deepEqual(deleted, []); +}); + +test("a prefix whose index disappears before its delete is kept, and the log says why", async () => { + const fake = fakeStore(archive(), ({ prefix }) => { + if (prefix === `${orphan}/`) delete fake.blobs[`${orphan}/_publish.json`]; + }); + const { deleted, lines } = await cleanup(fake); + assert.deepEqual(deleted, []); + assert.ok(lines.includes(`cleanup: ${orphan} its _publish.json is gone; skipping`)); +}); + +test("keepReason allows an idle prefix and names what keeps a busy one", async () => { + const graceMs = 7 * day; + const { listPage: idle } = fakeStore({ [`${orphan}/_publish.json`]: old }); + assert.equal(await keepReason({ prefix: orphan, listPage: idle, now, graceMs }), undefined); + const recent = new Date(now.getTime() - 1000); + const { listPage: busy } = fakeStore({ [`${orphan}/_publish.json`]: old, - [`${orphan}/_uploading.json`]: new Date(now.getTime() - 1000), + [`${orphan}/_uploading.json`]: recent, }); assert.equal( - await stillDeletable({ prefix: orphan, listPage: uploading, now, graceMs: 7 * day }), - false, + await keepReason({ prefix: orphan, listPage: busy, now, graceMs }), + `saw upload activity at ${recent.toISOString()}`, ); }); - -test("a prefix whose index has gone missing is not deleted", async () => { - const listPage = fakeListing({}); - assert.equal(await stillDeletable({ prefix: orphan, listPage, now, graceMs: 0 }), false); -}); diff --git a/apps/docs/scripts/publish/env.mjs b/apps/docs/scripts/publish/env.mjs index 16f5db1c..6344f401 100644 --- a/apps/docs/scripts/publish/env.mjs +++ b/apps/docs/scripts/publish/env.mjs @@ -1,4 +1,4 @@ -// Shared by the publish scripts (cleanup, mirror, plan, reconcile). +// Shared by the publish scripts (cleanup, mirror, plan, reconcile, release-schedule). export function need(name) { const v = process.env[name]; if (!v) throw new Error(`${name} must be set`); diff --git a/apps/docs/scripts/publish/release-schedule.mjs b/apps/docs/scripts/publish/release-schedule.mjs index a923a6d7..fee72a75 100644 --- a/apps/docs/scripts/publish/release-schedule.mjs +++ b/apps/docs/scripts/publish/release-schedule.mjs @@ -2,6 +2,7 @@ // Fetch the release schedule with the job's token, so the build step that // compiles the corpus can read it from a file and never holds the token. import { writeReleaseSchedule } from "@coder/docs-build"; +import { need } from "./env.mjs"; const flagAt = process.argv.indexOf("--out"); const out = flagAt === -1 ? undefined : process.argv[flagAt + 1]; @@ -13,7 +14,7 @@ if (!out || out.startsWith("--")) { } const schedule = await writeReleaseSchedule({ outFile: out, - token: process.env.DOCS_GITHUB_TOKEN || undefined, + token: need("DOCS_GITHUB_TOKEN"), required: true, }); console.log(`release schedule: ${schedule?.generatedAt}`); diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index d9a5439c..01941e75 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -611,13 +611,22 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => { const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + const prefix = `versions/main/${sha}`; + const marker = `${prefix}/_uploading.json`; const keys = []; + let releaseMarker; + const markerHeld = new Promise((resolve) => { + releaseMarker = resolve; + }); const blobPut = async (key) => { keys.push(key); + if (key === marker) await markerHeld; return { url: `https://store.private.blob.vercel-storage.com/${key}` }; }; - const prefix = `versions/main/${sha}`; - await uploadDir({ dir, prefix, token: "t", concurrency: 1, blobPut }); - assert.equal(keys[0], `${prefix}/_uploading.json`); + const upload = uploadDir({ dir, prefix, token: "t", concurrency: 4, blobPut }); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.deepEqual(keys, [marker]); + releaseMarker(); + await upload; assert.deepEqual(keys.slice(-2), [`${prefix}/_objects.json`, `${prefix}/_publish.json`]); }); From 385b1566a6ccf3f25a83479c9390ded3e51e0992 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:36:54 -0700 Subject: [PATCH 3/3] docs: record the upload marker and the token-free build step ARCHITECTURE.md still said the sync fetches the release schedule itself, and the README's TTL and cleanup notes predated the upload marker. Write down the invariants the code now relies on: every upload writes its marker first and its index last, cleanup decides on the newer of the two re-read just before each delete, and there is no token in the build step's environment. Assisted-by: AI --- ARCHITECTURE.md | 5 ++++- apps/docs/README.md | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3c888fa2..cd6a8e02 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -200,7 +200,10 @@ It is the next step if the sanitizer ever has to be weakened, and otherwise a la The Releases page's release schedule is data, not content: coder/coder authors a `
` marker with a fallback link, and the engine fills it from GitHub. `buildReleaseSchedule` in `@coder/docs-config` is the one definition of the rows: stable is the minor of GitHub's latest release, mainline and security support are the released minor lines either side of it (ordered by major, then minor), the ESR set comes from coder/coder's `scripts/release_channels/esr_versions.txt`, and an ESR drops out 365 days after its first release. -The sync fetches the schedule once per build (`writeReleaseSchedule` in `@coder/docs-build`), a publish fails if it cannot, and `remarkReleasesTable` rewrites the marker into `ReleasesTable`, whose children carry the same rows as a Markdown table for search and the Markdown twin. +The sync gets the schedule once per build (`writeReleaseSchedule` in `@coder/docs-build`), and `remarkReleasesTable` rewrites the marker into `ReleasesTable`, whose children carry the same rows as a Markdown table for search and the Markdown twin. +In a publish, a separate `Fetch the release schedule` step fetches it with the job's token before the content checkout, and the sync reads that file through `DOCS_RELEASE_SCHEDULE_FILE` instead of fetching. +That keeps the invariant that there is no token in the build step's environment, the step that compiles untrusted content, so never pass that step a token. +A publish fails if the fetch does. A tag build is never rebuilt, so on the public site `ReleasesTable` refreshes from the router's `/releases.json`, which fetches GitHub at most once an hour per isolate; the offline export keeps its build-time table. Older refs carry a static table between `RELEASE_CALENDAR_START/END` comments; the sync strips comments, so `rewriteLegacyReleaseCalendar` turns that region into the marker first, line for line. diff --git a/apps/docs/README.md b/apps/docs/README.md index 9caeb2f2..fa8d382d 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -321,6 +321,13 @@ Any experiment with `DOCS_UPLOAD_CONCURRENCY` above `16` must be a single publis `publish:cleanup` deletes an archive prefix once the manifest no longer references it and it has stayed unreferenced for at least seven days, giving an in-flight reader time to finish against a prefix the manifest just stopped pointing at. A tag prefix (`versions///` for a `vX.Y.Z` tag) is never deleted by the pipeline, whatever the manifest says, since a tag is frozen forever once published. +Every upload writes a small `_uploading.json` marker at the prefix root before any other object, and `_publish.json` last. +A re-upload of the same commit leaves the old `_publish.json` in place until its final put, so cleanup takes the newer of the two as the prefix's last activity and keeps any prefix whose last activity falls inside the grace period. +The listing ages each prefix by `_publish.json` alone to pick candidates; the check that decides is a re-read of both objects, made after the candidate's objects have been listed and immediately before each delete call, including a delete retried after a rate limit. +A prefix without `_publish.json` is never deleted: at listing time it is an upload in flight, and at delete time it is already gone. +A skipped candidate is logged with the reason, either `saw upload activity at