Skip to content

node:fs: stop writeFile from truncating files opened with a non-truncating flag - #33355

Merged
Jarred-Sumner merged 5 commits into
mainfrom
farm/3ba375be/writefile-non-truncating-flags
Jul 6, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
farm/3ba375be/writefile-non-truncating-flags

Conversation

@robobun

@robobun robobun commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

const fs = require("fs");
fs.writeFileSync("f.txt", "0123456789");
fs.writeFileSync("f.txt", "ZZ", { flag: "r+" }); // r+ = read/write, no truncation
fs.readFileSync("f.txt", "utf8");
// node: "ZZ23456789"      bun: "ZZ"

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 numeric O_RDWR, across writeFileSync, fs.writeFile and fs.promises.writeFile (including its iterable slow path). FileHandle.writeFile was already correct.

Two more data bugs turned up next to it.

// 1. append + preallocate, linux
fs.writeFileSync("f.bin", "HEADER");
fs.writeFileSync("f.bin", Buffer.alloc(3 * 1024 * 1024, "A"), { flag: "a" });
// node: 3145734 bytes, no zeroes
// bun:  6291456 bytes, 3145722 zeroes between HEADER and the data

// 2. a write that fails partway (here via RLIMIT_FSIZE; ENOSPC/EIO do the same)
fs.writeFileSync("f.txt", Buffer.alloc(2000, "B"));
fs.writeFileSync("f.txt", Buffer.alloc(1000, "A")); // dies at 512 bytes with EFBIG
// node: 512 bytes, all new
// bun:  2000 bytes, 512 new + 1488 stale

Cause

NodeFS::write_file_with_path_buffer opens the path, writes, then runs ftruncate(fd, written) (SetEndOfFile on Windows) on every non-append write. The ftruncate is how a truncating write actually truncates: open() is deliberately given no O_TRUNC so the file's existing blocks stay allocated, which makes repeatedly rewriting a large file cheaper. Three things went wrong with that:

  • The guard was "not appending", so it also fired for r+, rs+, sr+ and numeric O_RDWR, which are supposed to overwrite in place.
  • The ftruncate only 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 an O_APPEND write takes its offset from the end of the file at write() time, so the data landed past the grown end with a hole of zeroes in front of it. This hit flag: "a"/"a+"/"as" on a path, and writeFileSync(fd, ...) on a descriptor opened for append.

fs.promises.writeFile routes iterable data to 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::W now includes O_TRUNC, matching its own doc comment and the "w" entry in FILE_SYSTEM_FLAGS_MAP. It is the flag's meaning, not what reaches open().
  • write_file_with_path_buffer masks O_TRUNC out of the flags it passes to open() explicitly, and resizes afterwards only when the flag carries O_TRUNC. A caller-supplied descriptor is still never resized. O_APPEND keeps its O_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).
  • The write loop's error is held back until after the resize, so a partial write leaves only what it wrote. The flush fsync is still skipped on error.
  • writeFileAsyncIterator gates its ftruncate on the same rule, via the six flag spellings node maps to O_TRUNC.
  • Preallocation is skipped when the kernel picks the write offset: args.flag answers that for a path, fcntl(F_GETFL) for a descriptor (the flag option is not how the caller opened it).

The syscalls for w are unchanged; r+ simply stops issuing the ftruncate:

          w                 w+                r+
main      ftruncate(2)      ftruncate(2)      ftruncate(2)   <- data loss
this PR   ftruncate(2)      ftruncate(2)      -
node      - (O_TRUNC)       - (O_TRUNC)       -

Verification

test/js/node/fs/fs.test.ts gains 25 tests: r+/rs+/numeric O_RDWR across writeFileSync, fs.writeFile, promises.writeFile and promises.writeFile of a sync/async iterable; the preallocate-sized append cases (path and fd); a write that fails partway under RLIMIT_FSIZE (Linux only: the 512-byte partial write before EFBIG is generic_write_checks()'s clamp, BSD rejects the whole write); and guards that w, w+, numeric O_APPEND|O_TRUNC, the default flag and a caller's descriptor keep their existing behaviour. 17 of them fail on main.

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). main differs from Node in 19 of them; with this change all 62 match byte for byte.

matrix diff, main vs node
< small flag=r+: len=10 head="ZZ23456789"       > small flag=r+: len=2 head="ZZ"
< small flag=rs+: len=10 head="ZZ23456789"      > small flag=rs+: len=2 head="ZZ"
< small flag=sr+: len=10 head="ZZ23456789"      > small flag=sr+: len=2 head="ZZ"
< big flag=r+: len=4194304                      > big flag=r+: len=3145728
< bigOnSmall flag=a: len=3145734 zeros=0        > bigOnSmall flag=a: len=6291456 zeros=3145722
< bigOnSmall flag=a+: len=3145734 zeros=0       > bigOnSmall flag=a+: len=6291456 zeros=3145722
< bigOnSmall flag=as: len=3145734 zeros=0       > bigOnSmall flag=as: len=6291456 zeros=3145722
< fd bigOnSmall open=a: len=3145734 zeros=0     > fd bigOnSmall open=a: len=6291456 zeros=3145722
< fd bigOnSmall open=a+: len=3145734 zeros=0    > fd bigOnSmall open=a+: len=6291456 zeros=3145722
< numeric O_RDWR: len=10 head="ZZ23456789"      > numeric O_RDWR: len=2 head="ZZ"
< numeric O_WRONLY|O_CREAT: len=10              > numeric O_WRONLY|O_CREAT: len=2
< numeric-big O_WRONLY|O_CREAT|O_APPEND: zeros=0          > ...: len=6291456 zeros=3145722
< numeric-big O_WRONLY|O_CREAT|O_APPEND|O_TRUNC: zeros=0  > ...: len=6291456 zeros=3145728
< async iterable flag=r+: "ZZ23456789"          > async iterable flag=r+: "ZZ"
< async iterable flag=rs+: "ZZ23456789"         > async iterable flag=rs+: "ZZ"
< async iterable flag=sr+: "ZZ23456789"         > async iterable flag=sr+: "ZZ"
< sync iterable flag=r+: "ZZ23456789"           > sync iterable flag=r+: "ZZ"
< sync iterable flag=rs+: "ZZ23456789"          > sync iterable flag=rs+: "ZZ"
< sync iterable flag=sr+: "ZZ23456789"          > sync iterable flag=sr+: "ZZ"

Node's own test-fs-write-file*, test-fs-append-file* and test-fs-promises-writefile* parallel tests still pass, and bun run rust:check-all is green on all 10 targets so the Windows SetEndOfFile branch and the fcntl call still compile everywhere.

One case skipped on Windows

openat on Windows derives its NtCreateFile disposition from O_WRONLY, never from O_TRUNC:

let overwrite = (flags & O::WRONLY) != 0 && (flags & O::APPEND) == 0;

libuv keys it off O_CREAT|O_EXCL|O_TRUNC instead, so Bun diverges there in a few ways that have nothing to do with this writer: a numeric O_APPEND|O_TRUNC open never empties the file, fs.openSync(path, "w+") never truncates, and a numeric O_WRONLY|O_CREAT truncates when it should not. The O_APPEND|O_TRUNC test is skipIf(isWindows) for that reason; the behaviour there is "0123456789ZZ" on main and 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_file calls fallocate(fd, 0, offset, len) with mode 0, which grows the file. If write() then fails partway on a flag that does not truncate, nothing sizes the file back and the fallocate-grown zero tail survives. main behaves identically (its write error returned before the resize), so nothing regresses here, and the trigger is narrow: fallocate accounts for space and quota up front, so ENOSPC/EDQUOT cannot fire afterwards, and RLIMIT_FSIZE fails the fallocate itself before it can grow anything. That leaves EIO off 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 on O_TRUNC would only close half of it). It is left out of this PR because preallocate_file has six callers across libarchive, Bun.write, copy_file, the transpiler cache and tarball extraction, and re-moding it deserves its own reasoning per caller.

@github-actions github-actions Bot added the claude label Jul 5, 2026
@robobun

robobun commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:07 AM PT - Jul 5th, 2026

❌ @robobun, your commit 9f1dea9 has 1 failures in Build #68504 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33355

That installs a local version of the PR into your bun-33355 executable, so you can run:

bun-33355 --bun

@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This 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.

Changes

Node fs write semantics

Layer / File(s) Summary
Flag truncation mapping
src/runtime/node/types.rs, src/js/node/fs.promises.ts
FileSystemFlags::W now includes O::TRUNC, and writeFileAsyncIterator() truncates only for flags that explicitly truncate.
Write path truncation and preallocation
src/runtime/node/node_fs.rs
Path writes remove O::TRUNC from the open flags, skip preallocation for append semantics, defer truncation to the post-write resize path, and return a stored write error after resizing.
Partial write failure coverage
test/js/node/fs/fs-writeFile-write-error-fixture.js, test/js/node/fs/fs.test.ts
Adds a fixture and test coverage for mid-write failures, including file size and tail-byte assertions after forced write errors.
Non-truncating and large-buffer write coverage
test/js/node/fs/fs.test.ts
Adds coverage for non-truncating flags, iterable inputs, file-descriptor writes, append behavior, and large-buffer preallocation cases.

Possibly related PRs

  • oven-sh/bun#32966: Touches Node fs flag handling in the same area, including how write flags map into truncation and overwrite behavior.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and accurately describes the main change: preventing writeFile from truncating non-truncating flags.
Description check ✅ Passed The description covers the change, cause, fix, and verification, even though it uses custom headings instead of the template.

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

Comment thread src/runtime/node/node_fs.rs Resolved
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed ade1a49 addressing both points.

Keeping the ftruncate-based truncation. Right, the missing O_TRUNC was the point, not an oversight: leaving the blocks allocated is what makes repeatedly rewriting a large file cheap. I'd accidentally undone that by handing the new O_TRUNC to open(). Now the mask is explicit at the call site, so the optimization is stated rather than implied by a wrong constant:

// 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;

FileSystemFlags::W still gains O_TRUNC so the flag's meaning is right (the "w" entry in FILE_SYSTEM_FLAGS_MAP already had it), and that bit is what the resize now keys off. Net syscalls, traced with an LD_PRELOAD shim:

          w                 w+                r+
main      ftruncate(2)      ftruncate(2)      ftruncate(2)
this PR   ftruncate(2)      ftruncate(2)      -

Same for w, the ftruncate still does the truncating, and r+ stops losing the tail. This also extends the optimization to explicit w+ and numeric O_TRUNC, which previously did pass O_TRUNC to open().

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"

writeFileAsyncIterator gated its own ftruncate on !flag.includes("a"), which lets r+/rs+/sr+ through. Replaced with the same rule as the native side (the six spellings node maps to O_TRUNC) rather than dropping it outright, because on Windows openat picks its disposition from O_WRONLY, not O_TRUNC, so fs.open(path, "w+") does not truncate there and the ftruncate is load-bearing.

Tests now cover promises.writeFile of a sync and async iterable for r+/rs+, plus w/w+ truncation guards. The node-parity matrix grew to 53 cases (added iterable data); main differs in 17, this branch matches all 53.

@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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35211b3 and ade1a49.

📒 Files selected for processing (3)
  • src/js/node/fs.promises.ts
  • src/runtime/node/node_fs.rs
  • test/js/node/fs/fs.test.ts

Comment thread src/runtime/node/node_fs.rs Resolved
Comment thread src/runtime/node/node_fs.rs Resolved
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

415cd87 closes two holes the bot reviews found in the deferred truncation. Both are the same shape: the resize only works when the write starts at offset 0 and the resize actually runs.

O_APPEND | O_TRUNC. My regression. Dropping O_TRUNC from the open left the old content in place, the append landed at EOF behind it, and ftruncate(written) then kept the head of the old file and discarded the write:

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"

O_TRUNC now stays in the open whenever O_APPEND is set. The kernel has to empty the file at open for the append offsets to come out right, and the block-reuse win never applied to an append anyway.

Write fails partway. The resize only ran on the success path. This one predates the PR: FileSystemFlags::W never carried O_TRUNC, so fs.writeFileSync(path, data) with no flag: option already opened without truncating and already skipped the resize on error. Forced it with RLIMIT_FSIZE (a 2000 byte file, a 1000 byte write, ulimit -f 1, so write() dies with EFBIG at 512 bytes):

            node          main
default     512, clean    2000, 512 new + 1488 stale   <- already broken
flag w      512, clean    512, clean
flag r+     2000, tail    2000, tail                   (correct, no truncation asked)

The write loop's error is now held in an Option and returned after the resize, keeping the order write → resize → error. Not a scopeguard: it drops at the end of the function, which would put the resize after the flush fsync and leave the truncation unflushed. The fsync is still skipped on failure, as in Node.

The parity matrix grew to 62 cases (six numeric flag combinations, plus the iterable slow path). main differs from Node in 19; this branch matches all 62. It turned up one more: a 3 MB writeFileSync with numeric O_WRONLY|O_CREAT|O_APPEND|O_TRUNC produces 6291456 bytes of zeroes on main.

robobun added 4 commits July 5, 2026 07:57
…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.
@robobun
robobun force-pushed the farm/3ba375be/writefile-non-truncating-flags branch from 415cd87 to 416262a Compare July 5, 2026 08:05
@robobun

robobun commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto fb50cce and pushed 416262a.

CI on 415cd87 had one real failure, on the two Windows lanes: the new O_APPEND|O_TRUNC test got "0123456789ZZ" instead of "ZZ". That is not a regression from this PR, it is a gap in Bun's Windows openat, which derives its NtCreateFile disposition from O_WRONLY and never looks at O_TRUNC:

let overwrite = (flags & O::WRONLY) != 0 && (flags & O::APPEND) == 0;

libuv keys it off O_CREAT|O_EXCL|O_TRUNC. So on Windows an O_APPEND|O_TRUNC open does not empty the file, and main produces the same "0123456789ZZ": the open does not truncate, and the old resize gate excluded appends, so nothing resized. On this branch the open still does not truncate and the SetEndOfFile lands at EOF, which is a no-op. Identical output either way.

That mapping also means fs.openSync(path, "w+") never truncates on Windows, and a numeric O_WRONLY|O_CREAT truncates when it should not. Fixing it is a wider change than this PR and touches every open on Windows, so the test is skipIf(isWindows) with the reason inline, and the PR body records the gap. Glad to do the disposition mapping as a follow-up.

The other red lanes were a stale base (color.test.ts's .failing marker, removed on main in #33351, picked up by the rebase) and two unrelated flakes (complex-workspace.test.ts, already annotated flaky with a retry, and an ASAN OOM in tls-syscall-fault.test.ts).

Comment thread test/js/node/fs/fs.test.ts Resolved
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.
Comment thread src/runtime/node/node_fs.rs Resolved
@robobun

robobun commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: diff is green, CI red on two unrelated darwin failures

Build 68504 on 9f1dea9 finished: 283 jobs passed, 3 failed. All three are darwin, neither is this diff.

1. Two shards never ran a test (:darwin: 26 aarch64 - test-bun):

Error: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'.
       Refusing to continue with a partial download (would silently fall back to the wrong binary).

darwin-aarch64-build-bun itself passed, so the artifact exists, the test lane just could not fetch it inside the 120s window. This same step has now timed out on 68486, 68496 and 68504, three builds in a row, so it reads as an infra condition rather than a one-off. Nothing in this diff can influence an artifact download.

2. One shard hit a node:net race (:darwin: 14 aarch64):

test/js/node/test/parallel/test-net-write-slow.js
error: stream.push() after EOF   code: "ERR_STREAM_PUSH_AFTER_EOF"
  at readableAddChunkPushByteMode (internal:streams/readable:238:53)
  at data (node:net:527:72)

That test touches no fs API at all, and there is no path from a socket's EOF handling to write_file_with_path_buffer, FileSystemFlags::W (two consumers, both fs writers) or writeFileAsyncIterator. It passed on every Linux and Windows shard in this build, and 20/20 locally against this branch's build. A macOS-specific socket/EOF ordering race.

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 fs.test.ts failure on any lane, all 24 Windows test-bun shards pass (that is where fs.test.ts was red before the O_APPEND|O_TRUNC skip), and color.test.ts is fixed by the rebase onto fb50cce.

Recap of the diff

Three bug classes in writeFile, all data-destroying, verified against Node across a 62-case matrix (main differs in 19, this branch matches all 62):

  1. Non-truncating flags (r+, rs+, sr+, numeric O_RDWR) truncated the file, in the native writer and in fs.promises.writeFile's iterable slow path.
  2. fallocate() grew the file before an O_APPEND write, which then landed past the new end behind a hole of zeroes.
  3. The resize skipped O_APPEND|O_TRUNC, and skipped the write-error path entirely, leaving the old tail behind the bytes that landed.

25 tests in test/js/node/fs/fs.test.ts, 17 of which fail on main. bun run rust:check-all green on all 10 targets.

@Jarred-Sumner
Jarred-Sumner merged commit 4ca9ebc into main Jul 6, 2026
75 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/3ba375be/writefile-non-truncating-flags branch July 6, 2026 03:31
dylan-conway pushed a commit that referenced this pull request Jul 20, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants