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 () => {