Repository navigation
node:fs: stop writeFile from truncating files opened with a non-truncating flag - #33355
Conversation
|
Updated 4:07 AM PT - Jul 5th, 2026
❌ @robobun, your commit 9f1dea9 has 1 failures in 🧪 To try this PR locally: bunx bun-pr 33355That installs a local version of the PR into your bun-33355 --bun |
WalkthroughThis PR updates Node fs write semantics so truncation is driven by explicit truncating flags, append writes skip preallocation, and tests cover non-truncating, partial-failure, and large-buffer write cases. ChangesNode fs write semantics
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Pushed Keeping the // O_TRUNC is dropped on purpose: leaving the existing blocks
// allocated makes repeatedly rewriting a large file cheaper. The
// `ftruncate` after the write sets the final size instead.
let flags = args.flag.as_int() & !sys::O::TRUNC;
Same for The iterable slow path. Good catch, real bug, reproduced: fs.writeFileSync("f.txt", "0123456789");
await fs.promises.writeFile("f.txt", (async function* () { yield "ZZ"; })(), { flag: "r+" });
// node: "ZZ23456789" bun before: "ZZ"
Tests now cover |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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.
Inline comments:
In `@src/runtime/node/node_fs.rs`:
- Around line 7433-7437: The deferred truncation in the write path can be
skipped when sys::write returns an error, leaving stale tail data mixed with
partially written content. Update the write/open flow in the node_fs logic
around the truncating modes so the final ftruncate happens on every exit path,
not only after successful writes; a scopeguard-based cleanup like the one used
in copy_file_inner is the right pattern here. Make sure the guard is declared in
the correct order relative to _close so the file descriptor is still open when
truncation runs, and keep the fix localized to the truncating write handling in
this area.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 831e5574-e0a8-45a7-bbf3-83dafa1950bf
📒 Files selected for processing (3)
src/js/node/fs.promises.tssrc/runtime/node/node_fs.rstest/js/node/fs/fs.test.ts
|
fs.writeFileSync("f.txt", "0123456789");
fs.writeFileSync("f.txt", "ZZ", { flag: c.O_WRONLY | c.O_CREAT | c.O_APPEND | c.O_TRUNC });
// node, main: "ZZ" ade1a49: "01"
Write fails partway. The resize only ran on the success path. This one predates the PR: The write loop's error is now held in an The parity matrix grew to 62 cases (six numeric flag combinations, plus the iterable slow path). |
…ating flag writeFile/writeFileSync ran an unconditional ftruncate(fd, written) after every non-append write to a path, so `flag: "r+"`, `"rs+"` and numeric O_RDWR discarded everything past the bytes written. The truncation was load-bearing because FileSystemFlags::W was O_WRONLY|O_CREAT, missing the O_TRUNC the string-flag map already had for "w". Add O_TRUNC to FileSystemFlags::W and only resize the file when the open flags asked for truncation. The same function also preallocated with fallocate() before an O_APPEND write. fallocate() grows the file, so the write then landed past the new end and left a hole of zeroes. Skip preallocation when the kernel picks the write offset: args.flag for paths, fcntl(F_GETFL) for descriptors.
Not passing O_TRUNC to open() is deliberate: the existing blocks stay
allocated, so repeatedly rewriting a large file does not free and re-allocate
them. Mask it out of the open flags explicitly and keep the ftruncate as the
thing that sets the final size, now gated on whether the flag carries O_TRUNC.
Fix the same truncate in the iterable slow path of fs.promises.writeFile:
`!flag.includes("a")` let `r+`, `rs+` and `sr+` through and destroyed the tail.
…C for appends Two holes in the deferred truncation: An O_APPEND write lands at the end of the file, so dropping O_TRUNC from the open left the old content in place, put the data after it, and then resized down to the byte count, keeping the head of the old file and discarding the write. Numeric O_APPEND|O_TRUNC went from "ZZ" to "01". Keep O_TRUNC in the open whenever O_APPEND is set; the block-reuse win does not apply there anyway. A write that failed partway returned before the resize, leaving the old tail behind the bytes that did land. This already happened on main for the default flag, which never carried O_TRUNC: a 1000 byte write that dies at 512 bytes over a 2000 byte file left 1488 stale bytes where node leaves none. Hold the error back until after the resize.
openat() on Windows derives its NtCreateFile disposition from O_WRONLY and never looks at O_TRUNC, so an O_APPEND|O_TRUNC open does not empty the file there. The result is "0123456789ZZ" on main and on this branch alike, which is a gap in the Windows open path rather than in the writer.
415cd87 to
416262a
Compare
|
Rebased onto CI on let overwrite = (flags & O::WRONLY) != 0 && (flags & O::APPEND) == 0;libuv keys it off That mapping also means The other red lanes were a stale base ( |
The forcing mechanism is Linux-specific. Under RLIMIT_FSIZE, generic_write_checks() clamps the write to `limit - pos` and fails the following one with EFBIG, so exactly 512 of the 1000 bytes land. BSD kernels reject the whole write instead, which makes the byte split unportable.
Status: diff is green, CI red on two unrelated darwin failuresBuild 68504 on 1. Two shards never ran a test (
2. One shard hit a That test touches no Not pushing an empty retrigger commit: the artifact timeout has reproduced on three consecutive builds, so a re-roll would land right back here while adding a junk commit to the history. Re-running the three darwin shards from the UI is the cheaper path. Everything the diff touches is green: no Recap of the diffThree bug classes in
25 tests in |
…s mode (#34773) ## Repro ```js const fs = require("fs"); fs.writeFileSync("f.txt", "0123456789"); fs.writeFileSync("f.txt", "ZZ", { flag: fs.constants.O_WRONLY | fs.constants.O_CREAT }); fs.readFileSync("f.txt", "utf8"); // node, bun linux: "ZZ23456789" // bun windows: "ZZ" ``` The inverse also fails: `O_WRONLY | O_CREAT | O_APPEND | O_TRUNC` is supposed to empty the file at open and then append, but on Windows it appends to the existing content (the test for this was added in #33355 and left `skipIf(isWindows)` pointing at this bug). ## Cause `openat_windows_impl` (the POSIX-flag to `NtCreateFile` bridge used by `bun_sys::openat` on Windows) picked its create disposition from the access mode: ```rust let overwrite = (flags & O::WRONLY) != 0 && (flags & O::APPEND) == 0; ``` `O::TRUNC` was never consulted, so `O_WRONLY|O_CREAT` became `FILE_OVERWRITE_IF` (truncates) while `O_RDWR|O_CREAT|O_TRUNC` became `FILE_OPEN_IF` (preserves). `Dir::create_file_z({ read: true, truncate: true })` and any other `O_RDWR|O_TRUNC` caller silently did not truncate. The user-visible symptom above is `fs.writeFileSync`, whose `write_file_with_path_buffer` opens via `sys::openat` (the NtCreateFile path, not libuv) since #33355 gated the post-write resize on `O_TRUNC`. ## Fix Derive the create disposition from `O_CREAT`/`O_EXCL`/`O_TRUNC` alone; the read/write access mode only affects `access_mask`. ```rust match (creat, excl, truncate) { (true, true, _) => FILE_CREATE, (true, false, true) => FILE_OVERWRITE_IF, (true, false, false) => FILE_OPEN_IF, (false, _, true) => FILE_OVERWRITE, (false, _, false) => FILE_OPEN, } ``` Two internal callers were relying on the old `O_WRONLY` implying truncation and now pass `O::TRUNC` explicitly: `CopyFileWindows::prepare_pathlike` and the resolver's Windows tmpfile. Sites where the new mapping changes behavior and that change is kept: - `libarchive/lib.rs:1639` opens `O_WRONLY` then reads `get_file_size`; the old `FILE_OVERWRITE` left it reading zero, so the existing-content branch was dead on Windows. - `FileSink::Options::flags()` returns `O_WRONLY|O_CREAT` (no `O_TRUNC`) and its `truncate: bool` field is never read. On POSIX this already meant no truncation; Windows now matches. `Bun.file(path).writer()` on Windows is unaffected either way since it pre-opens via libuv before FileSink is constructed, so only the narrow `sink.start({path})` surface sees the alignment. The dead `truncate` field is pre-existing and cross-platform; fixing it here would flip the main POSIX writer entry, so it is left for a separate change. ## Verification `test/js/node/fs/fs.test.ts` gains a `writeFileSync numeric open-flag matrix` block that walks every `{O_WRONLY, O_RDWR} x {0, O_CREAT, O_TRUNC, O_CREAT|O_TRUNC, O_CREAT|O_EXCL, O_CREAT|O_EXCL|O_TRUNC}` combination plus the four `O_WRONLY|O_APPEND` variants, each against both an existing and a missing file (16 cases x 2), and asserts the exact resulting contents or error code against Node's behavior. `writeFileSync` opens via `bun_sys::openat` on Windows, so the matrix exercises the NtCreateFile disposition mapping directly; on POSIX it is the plain `openat(2)` behavior. Four rows fail on Windows before this change (`WRONLY` and `WRONLY|CREAT` with `"ZZ"` instead of `"ZZ23456789"`, and `WRONLY|APPEND|TRUNC` / `WRONLY|CREAT|APPEND|TRUNC` with `"0123456789ZZ"` instead of `"ZZ"`) and all 16 pass after on both platforms. The previously-`skipIf(isWindows)` `O_APPEND|O_TRUNC` test from #33355 is removed in favor of the matrix row. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/node/fs/fs.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Repro
flag: "r+"is the documented way to patch a region of an existing file in place. On Bun the rest of the file is silently destroyed, and the call succeeds. The same happens with"rs+","sr+", and a numericO_RDWR, acrosswriteFileSync,fs.writeFileandfs.promises.writeFile(including its iterable slow path).FileHandle.writeFilewas already correct.Two more data bugs turned up next to it.
Cause
NodeFS::write_file_with_path_bufferopens the path, writes, then runsftruncate(fd, written)(SetEndOfFileon Windows) on every non-append write. Theftruncateis how a truncating write actually truncates:open()is deliberately given noO_TRUNCso the file's existing blocks stay allocated, which makes repeatedly rewriting a large file cheaper. Three things went wrong with that:r+,rs+,sr+and numericO_RDWR, which are supposed to overwrite in place.ftruncateonly ran on the success path, so a write that died partway left the old tail sitting behind the bytes that did land.fallocate()preallocation (writes at or above 2 MB) grows the file, but anO_APPENDwrite takes its offset from the end of the file atwrite()time, so the data landed past the grown end with a hole of zeroes in front of it. This hitflag: "a"/"a+"/"as"on a path, andwriteFileSync(fd, ...)on a descriptor opened for append.fs.promises.writeFileroutes iterabledatato a separate JS slow path (writeFileAsyncIterator) that has its own copy of the truncate, gated on!flag.includes("a"). Same bug, same flags.Fix
FileSystemFlags::Wnow includesO_TRUNC, matching its own doc comment and the"w"entry inFILE_SYSTEM_FLAGS_MAP. It is the flag's meaning, not what reachesopen().write_file_with_path_buffermasksO_TRUNCout of the flags it passes toopen()explicitly, and resizes afterwards only when the flag carriesO_TRUNC. A caller-supplied descriptor is still never resized.O_APPENDkeeps itsO_TRUNC, since an append lands at EOF and the kernel has to empty the file at open for the offsets to come out right (the block-reuse win does not apply to an append anyway).flushfsync is still skipped on error.writeFileAsyncIteratorgates itsftruncateon the same rule, via the six flag spellings node maps toO_TRUNC.args.flaganswers that for a path,fcntl(F_GETFL)for a descriptor (theflagoption is not how the caller opened it).The syscalls for
ware unchanged;r+simply stops issuing theftruncate:Verification
test/js/node/fs/fs.test.tsgains 25 tests:r+/rs+/numericO_RDWRacrosswriteFileSync,fs.writeFile,promises.writeFileandpromises.writeFileof a sync/async iterable; the preallocate-sized append cases (path and fd); a write that fails partway underRLIMIT_FSIZE(Linux only: the 512-byte partial write beforeEFBIGisgeneric_write_checks()'s clamp, BSD rejects the whole write); and guards thatw,w+, numericO_APPEND|O_TRUNC, the default flag and a caller's descriptor keep their existing behaviour. 17 of them fail onmain.Also diffed against Node across a 62-case matrix (every flag string, six numeric flag combinations, path and fd, iterable and buffer data, writes above and below the 2 MB preallocate threshold, pre-existing files larger and smaller than the write).
maindiffers from Node in 19 of them; with this change all 62 match byte for byte.matrix diff, main vs node
Node's own
test-fs-write-file*,test-fs-append-file*andtest-fs-promises-writefile*parallel tests still pass, andbun run rust:check-allis green on all 10 targets so the WindowsSetEndOfFilebranch and thefcntlcall still compile everywhere.One case skipped on Windows
openaton Windows derives itsNtCreateFiledisposition fromO_WRONLY, never fromO_TRUNC:libuv keys it off
O_CREAT|O_EXCL|O_TRUNCinstead, so Bun diverges there in a few ways that have nothing to do with this writer: a numericO_APPEND|O_TRUNCopen never empties the file,fs.openSync(path, "w+")never truncates, and a numericO_WRONLY|O_CREATtruncates when it should not. TheO_APPEND|O_TRUNCtest isskipIf(isWindows)for that reason; the behaviour there is"0123456789ZZ"onmainand on this branch alike, so nothing regressed. Happy to fix the disposition mapping in a follow-up if that is wanted, it is a wider change than this PR.Known follow-up
preallocate_filecallsfallocate(fd, 0, offset, len)with mode 0, which grows the file. Ifwrite()then fails partway on a flag that does not truncate, nothing sizes the file back and the fallocate-grown zero tail survives.mainbehaves identically (its write error returned before the resize), so nothing regresses here, and the trigger is narrow:fallocateaccounts for space and quota up front, soENOSPC/EDQUOTcannot fire afterwards, andRLIMIT_FSIZEfails thefallocateitself before it can grow anything. That leavesEIOoff a bad block, which is not something a test can reach.The clean fix is
FALLOC_FL_KEEP_SIZE, which also covers the descriptor case (the resize never runs for a caller's fd, so gating preallocation onO_TRUNCwould only close half of it). It is left out of this PR becausepreallocate_filehas six callers across libarchive,Bun.write, copy_file, the transpiler cache and tarball extraction, and re-moding it deserves its own reasoning per caller.