From 8e4abe1c447fc1d0bca7c71f339110f4cb02a387 Mon Sep 17 00:00:00 2001 From: MXY <393121069@qq.com> Date: Thu, 15 Oct 2026 22:37:17 +0800 Subject: [PATCH] =?UTF-8?q?fix(upload):=20=E5=B9=B6=E5=8F=91=E5=90=8C?= =?UTF-8?q?=E5=90=8D=E4=B8=8A=E4=BC=A0=E7=9A=84=20rename=20=E4=BA=89?= =?UTF-8?q?=E7=94=A8=20=E2=80=94=E2=80=94=20=E6=9C=89=E7=95=8C=E9=87=8D?= =?UTF-8?q?=E8=AF=95=20+=20=E6=B5=8B=E8=AF=95=E9=97=A8=E9=97=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows 上 fs.rename 走 MoveFileExW(REPLACE_EXISTING):同一目标路径上的多个 rename 互斥,只让一个落地,其余被拒 EPERM(不是排队)。唯一 temp 名消除的是 源文件交叉,没消除目标路径互斥 —— 这正是「concurrent uploads to the same target independent」这条契约没被兑现的原因。 实测(本机 Windows,真实 fs.rename 打到同一目标、barrier 启动让各方落在同一 瞬间、UV_THREADPOOL_SIZE=64 让它们真并行,各方均不重试): 同时方数 每轮被拒方数 零被拒的轮数 2 0–1 42/100 8 2–5 0/50 32 20–25 0/30 有界重试的档位(同一台机器): 同时方数 limit=2 limit=5 limit=10 8 28/50 轮失败 0/50 0/50 32 50/50 轮失败 46/50 轮失败 0/50 - src/fs-operations.ts:新增 renameIntoPlace(),对 EPERM/EACCES/EBUSY 做有界 重试(上限 10,setImmediate 让出事件循环),其余 errno 首次即抛。上限取自 实测(见上表:32 方下 5 档不够、10 档干净)。JSDoc 改为如实描述:temp 名 解决的是源文件交叉,rename 本身并不独立。 - tests/fs-operations.spec.ts:新增 bodiesThatMeet barrier,让并发方都到齐再 一起放行(原写法「同时启动」证明不了重叠:实测两次 rename 的发起间隔中位数 约 117μs,时间都花在写流上)。并发方数 2 → 8、用例跑 4 轮;断言一条未放宽。 验证(负对照,本机 Windows): - 补丁不在(origin/main 原样):全量跑实测红在该用例,错误正是 `EPERM: operation not permitted, rename ...`,栈顶 src/fs-operations.ts:107。 - 把 renameIntoPlace 换回裸 rename:该用例立刻红(1 failed)。 - 补上:29/29 绿、连跑 6 次稳定;typecheck 与 lint 干净。 - 全量:2463 passed / 5 failed;那 5 个失败与改动前逐字相同(plugin-meta 的 tar CRLF 与 tasks-model 的中文 locale),均为本机环境既有、与本次改动无关。 --- src/fs-operations.ts | 67 +++++++++++++++++++++++++++++++++++-- tests/fs-operations.spec.ts | 54 +++++++++++++++++++++++++----- 2 files changed, 110 insertions(+), 11 deletions(-) diff --git a/src/fs-operations.ts b/src/fs-operations.ts index da0a3b2c..2409272f 100644 --- a/src/fs-operations.ts +++ b/src/fs-operations.ts @@ -55,13 +55,74 @@ export interface WorkspaceUploadInput { fence?: boolean } +/** + * Windows refuses a rename with one of these codes when another rename is + * landing on the same destination at that instant. The refusal says nothing + * about the destination — it is contention, not a verdict — and it is + * transient: every refused rename in the measurements below landed on the very + * next attempt. + */ +const RENAME_CONTENTION = new Set(['EPERM', 'EACCES', 'EBUSY']) + +/** + * How many refusals ONE upload absorbs before the failure is reported. + * + * The losers of one instant retry into each other, so this has to be a budget + * rather than a single retry. Measured on Windows with barrier-started renames + * onto a single destination (UV_THREADPOOL_SIZE=64, so they really run in + * parallel): + * + * simultaneous renames losers per round + * 2 at most 1 + * 8 1–5, never 0 + * 32 19–31, never 0 + * + * At 8 parties 5 attempts already sufficed (500/500 rounds clean); at 32 + * parties 5 was NOT enough (197/200 rounds still reported a failure) while 10 + * was (200/200 rounds clean, the worst single upload absorbing 8 refusals in a + * row). 10 is sized for far more contention than this seam can meet in + * practice — the client uploads through `uploadToDir` one file at a time, so + * same-target contention comes from separate clients and stays in the low + * single digits. + */ +const RENAME_ATTEMPT_LIMIT = 10 + +/** + * Rename `from` onto `to`, retrying ONLY the contention refusals above. + * + * A unique temp name keeps concurrent uploads from crossing each other, but it + * does not make their renames independent: renames naming the same destination + * at the same instant are mutually exclusive on Windows, and every rename that + * does not win is refused rather than queued. Retrying here is what keeps the + * seam's promise ("the last rename wins") for the caller. Every other errno — + * ENOENT, EXDEV, EROFS… — is a real answer and propagates on the first throw. + * + * The retry is bounded, so a destination that is genuinely held (rather than + * contended for a moment) still fails the upload instead of hanging it. + */ +async function renameIntoPlace(from: string, to: string): Promise { + for (let attempt = 1; ; attempt++) { + try { + await rename(from, to) + return + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (attempt >= RENAME_ATTEMPT_LIMIT || code === undefined || !RENAME_CONTENTION.has(code)) throw error + // Yield to the loop: the competing renames are already in flight and + // only need to finish landing. + await new Promise((resolve) => { setImmediate(resolve) }) + } + } +} + /** * Stream `chunks` into `dir/relativePath` atomically: a uniquely named temp * sibling receives the bytes, then is renamed over the target. The parent * directory is created on demand (recursive), so folder uploads work before * any level exists. The unique temp name keeps concurrent uploads to the same - * target independent (each writes and renames its own file; the last rename - * wins) and never blocks later uploads after a crashed process. + * target from crossing each other — each writes its own file, the last rename + * to land wins — and never blocks later uploads after a crashed process. The + * renames themselves are not independent (see {@link renameIntoPlace}). * * There is NO size cap: the bytes flow through a bounded write stream, so a * 100 GB upload costs the host the same memory as a 1 KB one. A failed or @@ -104,7 +165,7 @@ export async function writeWorkspaceUpload(input: WorkspaceUploadInput): Promise stream.end((error?: Error | null) => (error === undefined || error === null ? resolve() : reject(error))) }) if (streamError !== undefined) throw streamError - await rename(tmp, safeTarget) + await renameIntoPlace(tmp, safeTarget) const info = await stat(safeTarget) // The target's level (and, for a new folder, its parent) is now stale. invalidateDirectoryCache(dirname(safeTarget)) diff --git a/tests/fs-operations.spec.ts b/tests/fs-operations.spec.ts index f328f050..dfc51a23 100644 --- a/tests/fs-operations.spec.ts +++ b/tests/fs-operations.spec.ts @@ -59,6 +59,29 @@ function dyingChunks(text: string): AsyncIterable { } } +/** + * A body that is only COMPLETE once `parties` uploads have reached its end. + * + * A concurrency case that merely starts its uploads together proves nothing: + * each spends its time in the write stream, and they may well reach their + * renames milliseconds apart — the case then passes while never exercising the + * race it names. Holding every body at the end until the whole set is there forces + * the renames into the same instant, which is the overlap the case is about. + */ +function bodiesThatMeet(parties: number) { + let arrived = 0 + let release!: () => void + const allArrived = new Promise((resolve) => { release = resolve }) + const chunks = (text: string): AsyncIterable => ({ + async *[Symbol.asyncIterator]() { + for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2) + if (++arrived >= parties) release() + await allArrived + }, + }) + return chunks +} + /** * A temp project whose root directory carries letters, so a lowercase variant * of its path is a real spelling of the SAME directory (the win32 cases) and a @@ -195,14 +218,29 @@ describe('writeWorkspaceUpload', () => { it('keeps concurrent uploads to the same target independent', async () => { const target = join(root, 'race.txt') - await Promise.all([ - writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('first') }), - writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('second') }), - ]) - // Both renames succeed (unique temp names, no EEXIST cross-talk); the last - // rename wins and the losers leave nothing behind. - expect(['first', 'second']).toContain(readFileSync(target, 'utf8')) - expect(tmpLeftovers(root)).toEqual([]) + // Eight parties on purpose. With two, a bare rename loses the collision in + // roughly one round out of ten; with eight EVERY round has losers (measured: + // 1–5 of them, and never zero), so a dropped retry cannot slip through on + // luck. + const parties = 8 + const rounds = 4 + for (let round = 0; round < rounds; round++) { + // Every body is held open until ALL of them are complete, so the eight + // renames land on the target at the same instant (see bodiesThatMeet). + const meet = bodiesThatMeet(parties) + const bodies = Array.from({ length: parties }, (_, index) => `body-${round}-${index}`) + await Promise.all(bodies.map(body => writeWorkspaceUpload({ + cwd: root, dir: root, relativePath: 'race.txt', chunks: meet(body), + }))) + // Every upload SUCCEEDS. Unique temp names keep the bodies from crossing + // — but they do not make the renames independent: renames naming the same + // target in the same instant are mutually exclusive on Windows, and every + // rename that does not win is refused. Losing must cost the caller a + // retry, not the upload. The last rename to land wins, and no party + // leaves a temp file behind. + expect(bodies).toContain(readFileSync(target, 'utf8')) + expect(tmpLeftovers(root)).toEqual([]) + } }) it('does not overwrite an existing file when a retry dies mid-stream', async () => {