Skip to content

fix(prerender): write output files atomically - #4488

Closed
sobol-sudo wants to merge 6 commits into
nitrojs:mainfrom
sobol-sudo:fix/atomic-prerender-write
Closed

sobol-sudo wants to merge 6 commits into
nitrojs:mainfrom
sobol-sudo:fix/atomic-prerender-write

Conversation

@sobol-sudo

@sobol-sudo sobol-sudo commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

🔗 Linked issue

Resolves the "not written atomically" half of #4487. The dedup half landed in #4491.

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

With prerender.concurrency > 1, two writes to one output file can overlap. fs.writeFile truncates and writes in place, so the file can end up torn between both payloads: the shorter body followed by the longer one's tail. This is the corruption reported in #4487.

#4491 claims each output path before writing, so routes resolving to the same path no longer race. Routes with different paths can still alias one file, for example /About and /about on a case-insensitive filesystem (macOS, Windows).

This adds writeFileAtomic in src/utils/fs.ts and uses it only for prerendered output. It writes to a temp file in the same directory and renames it into place. rename is atomic within a filesystem, so overlapping writers give last-one-wins instead of a torn file.

  • The temp file is named .nitro-<random>.tmp, independent of the target name, so target names close to the 255-byte limit still fit.
  • On Windows, the rename is retried briefly on EPERM / EACCES / EBUSY (antivirus or indexers holding the destination open).
  • The temp file is removed if the write or rename fails.
  • The shared writeFile (build info, presets, dev worker entry) is unchanged and still writes in place.

The extra rename per file is within noise when writing 5000 files at concurrency 10.

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

test/unit/fs.test.ts covers basic writes, overwrites, near-limit file names, temp file cleanup on failure, and concurrent writers (fails on main, passes with this change).

🤖 Generated with AI assistant

@sobol-sudo
sobol-sudo requested a review from pi0 as a code owner July 28, 2026 14:57
@vercel

vercel Bot commented Jul 28, 2026

Copy link
Copy Markdown

@sobol-sudo is attempting to deploy a commit to the Nitro Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e7f74e72-bcd5-4091-bcc8-7a4c749ecee3
📥 Commits

Reviewing files that changed from the base of the PR and between 3b88d56 and 130f0c5.

📒 Files selected for processing: 3
  • src/prerender/prerender.ts
  • src/utils/fs.ts
  • test/unit/fs.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

📝 Walkthrough

A new writeFileAtomic utility writes through a sibling temporary file and renames it into place. Prerendering now uses this utility. Unit tests cover write outcomes, cleanup, and concurrent writes.

Changes: Atomic file writes

Layer / File(s) Summary
Temporary-file write and replacement
src/utils/fs.ts
writeFileAtomic creates the parent directory, writes to a randomly named sibling temporary file, and renames it into place. It attempts temporary-file cleanup after failures and retries selected rename errors on Windows.
Prerender integration
src/prerender/prerender.ts
Prerendered files are now written with writeFileAtomic.
Write behavior and concurrency tests
test/unit/fs.test.ts
Tests cover nested directory creation, file contents, overwriting, long filenames, cleanup after failure, and complete-file results from concurrent writes.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 130f0

No merge-blocking issue was identified in the atomic prerender write change. It is ready for normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title follows Conventional Commits syntax with the fix(prerender): prefix and accurately describes the atomic output-file change.
Description check Passed The description directly explains the prerender write corruption issue, the atomic-write implementation, affected files, cleanup behavior, retry behavior, and test coverage.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/utils/fs.ts (1)

54-56: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove implementation-explaining comments.

The code is self-explanatory; these comments violate the source-file guideline. As per coding guidelines, “Do not add comments explaining what the line does unless prompted.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/fs.ts` around lines 54 - 56, Remove the implementation-explaining
comment above the sibling temporary-file write and rename logic in the
filesystem utility, leaving the underlying atomic write behavior unchanged.

Source: Coding guidelines

test/unit/fs.test.ts (1)

26-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover cleanup after a failed replacement.

This only tests successful cleanup after rename. Add a test that forces the post-write replacement to fail and verifies the sibling temporary file is removed, as required by the PR objective.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit/fs.test.ts` around lines 26 - 30, Add a failure-path test alongside
“leaves no temporary files behind” that forces the post-write replacement/rename
to fail, then verifies the sibling temporary file is removed from dir. Reuse the
existing filesystem helper and temporary-file naming behavior, and assert
cleanup occurs after the write operation rejects.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/utils/fs.ts`:
- Around line 54-56: Remove the implementation-explaining comment above the
sibling temporary-file write and rename logic in the filesystem utility, leaving
the underlying atomic write behavior unchanged.

In `@test/unit/fs.test.ts`:
- Around line 26-30: Add a failure-path test alongside “leaves no temporary
files behind” that forces the post-write replacement/rename to fail, then
verifies the sibling temporary file is removed from dir. Reuse the existing
filesystem helper and temporary-file naming behavior, and assert cleanup occurs
after the write operation rejects.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 147c1344-e67e-4c9b-943d-388f2fe4c419

📥 Commits

Reviewing files that changed from the base of the PR and between 77b77ff and 0551607.

📒 Files selected for processing (2)
  • src/utils/fs.ts
  • test/unit/fs.test.ts

@pi0x pi0x added bug Something isn't working (PRs; issues use the Bug type) prerender Prerendering and crawler v3 labels Sep 2, 2026
@pi0x
pi0x force-pushed the fix/atomic-prerender-write branch from 0551607 to 607a830 Compare September 7, 2026 22:12
@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pi0x

pi0x commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Thanks for this, and for the very clear write-up.

Rebase

I rebased the branch onto the latest main and force-pushed it. There were no conflicts. The diff is still exactly your two files.

Review

I checked the fix and it looks correct.

  • The temp file is created next to the target file, so the rename stays inside one filesystem and is atomic.
  • The temp name uses the pid plus a counter, so two writers in the same process, or in two processes, cannot pick the same name.
  • The failed write is cleaned up and the error is re-thrown, so callers still see it.

I also confirmed the regression test really is a regression test. I put the old non-atomic writeFile back and ran test/unit/fs.test.ts: the concurrency test fails right away. With your change all tests pass.

What I added

One small commit on top: a test for the cleanup path. Your tests covered the happy path, but nothing covered the rm in the catch block. The new test makes the rename fail (the target path is an existing directory) and then checks that no .tmp file is left behind.

Notes for the maintainers, not things you need to change

  1. There is a second, almost identical writeFile in src/presets/_utils/fs.ts that is still not atomic. It is not used by the prerenderer, and presets write their config files one at a time, so this fix does not need it. But the two copies now behave differently.
  2. Replacing a file by rename gives the new file default permissions instead of keeping the old file's mode. For prerender output this does not matter.
  3. If the build is killed in the middle of a write, a *.tmp file can be left in publicDir. That is a fair trade for not shipping a corrupted page, but it is worth knowing.

Leaving the dedup half out was the right call in my opinion, and your #4491 covers it.

This comment was written by an AI assistant on behalf of the Nitro maintainers. Please double-check anything that looks wrong.

@pkg-pr-new

pkg-pr-new Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/nitro@4488

commit: 130f0c5

pi0 added 3 commits October 13, 2026 13:38
Keep the shared `writeFile` in place-write semantics for build info,
presets and the dev worker entry. Name the temp file independently of the
target so near-limit file names still fit, and retry the rename on Windows
when another process transiently holds the destination open.
@pi0x pi0x changed the title fix(prerender): write files atomically to avoid torn output fix(prerender): write output files atomically Oct 22, 2026
@pi0x

pi0x commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Thanks for this. Since #4491 claims each output path before writing, the only remaining way to tear a file is routes that differ only in case on a case-insensitive filesystem, which #4895 now handles by deduping them. Closing in favor of that.

Triaged with AI assistance.

@pi0x pi0x closed this Oct 22, 2026
@pi0x pi0x removed the v3 label Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working (PRs; issues use the Bug type) prerender Prerendering and crawler

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants