Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
8a36cb5
Bun.file: do not cache a failed stat, stat on every exists()
robobun Aug 20, 2026
2920f8f
test: cover lastModified reset and a non-ENOENT stat failure
robobun Aug 20, 2026
b67b250
Shorten comments, assert the exact error code per platform
robobun Aug 20, 2026
e2280ba
test: check the copied content, not the byte count Windows does not r…
robobun Aug 20, 2026
e071cc2
Say failed stat, not missing file, in the two fallback comments
robobun Aug 20, 2026
ea18ccd
ci: retrigger
robobun Aug 20, 2026
d66c588
test: exists() on an existing file does not cap later reads, slice ke…
robobun Aug 20, 2026
5ca4525
test: cover the fd arm, the size reset after a failed stat, a slice o…
robobun Aug 21, 2026
5d6fc6a
test: close the fd on every exit path of the fd exists() test
robobun Aug 21, 2026
8c039e1
Merge remote-tracking branch 'origin/main' into farm/e27dc7cb/bunfile…
robobun Aug 21, 2026
09fb817
Merge origin/main into farm/e27dc7cb/bunfile-failed-stat-not-cached
robobun Aug 25, 2026
b85ecd7
Merge origin/main into farm/e27dc7cb/bunfile-failed-stat-not-cached
robobun Oct 10, 2026
ab0896c
Bun.file: a failed stat leaves the size unknown
robobun Oct 10, 2026
2b62cc1
Blob: one check for a file that could not be stat'd
robobun Oct 11, 2026
ffd326d
test: pin each reader of a handle that was asked while its file was m…
robobun Oct 11, 2026
4f37781
Merge origin/main into farm/e27dc7cb/bunfile-failed-stat-not-cached
robobun Oct 11, 2026
da20114
Merge origin/main into farm/e27dc7cb/bunfile-failed-stat-not-cached
robobun Oct 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 59 additions & 66 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1279,25 +1279,28 @@ impl BlobExt for Blob {
}

fn get_exists_sync(&self) -> JSValue {
if self.size.get() == MAX_SIZE {
self.resolve_size();
}

// If there's no store that means it's empty and we just return true
let Some(store) = self.store.get() else {
return JSValue::TRUE;
};

if matches!(store.data, store::Data::Bytes(_)) {
// Dispatch on the tag and re-read through `data_mut` after the stat;
// see `resolve_size` for why no `&Data` may be live across it.
Comment thread
robobun marked this conversation as resolved.
Resolved
match store.data_mut().tag() {
// Bytes will never error
return JSValue::TRUE;
store::DataTag::Bytes => JSValue::TRUE,
store::DataTag::S3 => JSValue::FALSE,
store::DataTag::File => {
// Stat on every call, so a file created or deleted since the
// last answer is seen. This refreshes only the store's stat
// cache. It must not resolve `self.size`: a size cached from
// here caps every later read and copy of this blob.
Comment thread
robobun marked this conversation as resolved.
Resolved
resolve_file_stat(store);
let mode = store.data_mut().as_file().mode;
// We say regular files and pipes exist.
JSValue::from(bun_sys::S::ISREG(mode) || bun_sys::S::ISFIFO(mode))
}
}

// We say regular files and pipes exist.
let store::Data::File(file) = &store.data else {
return JSValue::FALSE;
};
JSValue::from(bun_sys::S::ISREG(file.mode) || bun_sys::S::ISFIFO(file.mode))
}
fn do_write(&self, global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
// SAFETY: bun_vm() never returns null for a Bun-owned global.
Expand Down Expand Up @@ -2232,15 +2235,17 @@ impl BlobExt for Blob {
return JSValue::js_number(f64::NAN);
}
self.resolve_size();
if self.size.get() == MAX_SIZE && self.store.get().is_some() {
return JSValue::js_number(f64::INFINITY);
} else if self.size.get() == 0 && self.store.get().is_some() {
if let store::Data::File(file) =
&self.store().expect("infallible: store present").data
{
if !file.seekable.unwrap_or(true) && file.max_size == MAX_SIZE {
return JSValue::js_number(f64::INFINITY);
}
if self.size.get() == MAX_SIZE {
if let Some(store) = self.store.get() {
return match &store.data {
// The stat failed, so there is no file to size. Report
// 0 without caching it: the file may be created later.
Comment thread
robobun marked this conversation as resolved.
Resolved
store::Data::File(file) if file.seekable.is_none() => {
JSValue::js_number(0.0)
}
// A pipe or a tty has no end.
_ => JSValue::js_number(f64::INFINITY),
};
}
}
}
Expand All @@ -2258,9 +2263,9 @@ impl BlobExt for Blob {
// borrow is live across the arm body where `resolve_file_stat`
// materializes `&mut File` on the same memory via the raw
// `heap::alloc` pointer — Stacked Borrows UB, and under noalias the
// optimizer may legally cache the pre-call `seekable: None` and fall
// through to `self.size.get() = 0`. `StoreRef::data_mut` centralises
// the raw-ptr deref so each read here is a fresh, safe borrow.
// optimizer may legally cache the pre-call `seekable: None` and skip
// the freshly resolved size. `StoreRef::data_mut` centralises the
// raw-ptr deref so each read here is a fresh, safe borrow.
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
match store.data_mut().tag() {
store::DataTag::Bytes => {
let offset = self.offset.get();
Expand All @@ -2284,16 +2289,10 @@ impl BlobExt for Blob {
self.offset.set(store_size.min(offset));
let available = store_size - self.offset.get();
self.size.set(window_size(self.size.get(), available));
return;
}

// For non-seekable files (pipes, FIFOs), the size is genuinely
// unknown — leave it as max_size so that stream readers don't
// treat it as an empty file.
if file.seekable == Some(false) {
return;
}
self.size.set(0);
// Otherwise the size stays unresolved: a pipe has no size, and
// a file the stat did not find may be created later. Caching 0
// here would cap every later read of this blob at 0 bytes.
Comment thread
robobun marked this conversation as resolved.
Resolved
}
store::DataTag::S3 => self.size.set(0),
}
Expand Down Expand Up @@ -2333,10 +2332,7 @@ impl BlobExt for Blob {
let available = store_size - offset;
return (offset, window_size(self.size.get(), available));
}
if file.seekable == Some(false) {
return (self.offset.get(), self.size.get());
}
(self.offset.get(), 0)
(self.offset.get(), self.size.get())
}
store::DataTag::S3 => (self.offset.get(), 0),
}
Expand Down Expand Up @@ -6125,43 +6121,40 @@ fn window_size(current: SizeType, available: SizeType) -> SizeType {
}
}

/// resolve file stat like size, last_modified
/// Stat the file behind `store` and cache `max_size`, `mode`, `seekable` and
/// `last_modified` on it. The cache always describes the most recent stat:
/// when the stat fails (the file does not exist, or does not exist anymore)
/// the four fields go back to their unresolved defaults, so a later call
/// stats again instead of answering from a file that is gone.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn resolve_file_stat(store: &StoreRef) {
// `StoreRef::data_mut` encapsulates the raw-pointer deref under the
// `StoreRef` liveness invariant; the caller holds the only ref across
// this call, so an exclusive borrow is sound.
let file = store.data_mut().as_file_mut();
match &file.pathlike {
let stat = match &file.pathlike {
PathOrFileDescriptor::Path(path) => {
let mut buffer = bun_paths::PathBuffer::uninit();
match bun_sys::stat(path.slice_z(&mut buffer)) {
bun_sys::Result::Ok(stat) => {
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
}
// the file may not exist yet. That's okay.
_ => {}
}
bun_sys::stat(path.slice_z(&mut buffer))
}
PathOrFileDescriptor::Fd(fd) => bun_sys::fstat(*fd),
};
match stat {
Ok(stat) => {
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
}
Err(_) => {
file.max_size = MAX_SIZE;
file.mode = 0;
file.seekable = None;
file.last_modified = jsc::INIT_TIMESTAMP;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
PathOrFileDescriptor::Fd(fd) => match bun_sys::fstat(*fd) {
bun_sys::Result::Ok(stat) => {
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
}
_ => {}
},
}
}

Expand Down
102 changes: 101 additions & 1 deletion test/js/bun/util/bun-file.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test } from "bun:test";
import { describe, expect, test } from "bun:test";
import { unlinkSync } from "fs";
import fsPromises from "fs/promises";
import { bunEnv, bunExe, tempDir } from "harness";
import { join } from "path";
Expand Down Expand Up @@ -110,6 +111,105 @@ test("Bun.file().arrayBuffer() errors include async stack frames", async () => {
expect(caught.stack).toContain("at async caller");
});

// A BunFile stats lazily. A stat that fails (the file does not exist yet) must
// not be cached as "empty file" on the handle, and exists() must stat every
// time it is called.
describe.concurrent("BunFile does not cache a failed stat", () => {
test("exists() sees a file created after it answered false, and reads see the contents", async () => {
await using dir = tempDir("bun-file-created-later", {});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const path = join(dir, "f.txt");
const file = Bun.file(path);

expect(await file.exists()).toBe(false);

await Bun.write(path, "hello world");

expect(await file.exists()).toBe(true);
expect(await file.text()).toBe("hello world");
expect(await file.bytes()).toEqual(new TextEncoder().encode("hello world"));
expect(await new Response(file.stream()).text()).toBe("hello world");
expect(file.size).toBe(11);
});

test(".size of a missing file is 0 and does not cap reads once the file exists", async () => {
await using dir = tempDir("bun-file-size-before-create", {});
const path = join(dir, "f.txt");
const file = Bun.file(path);

expect(file.size).toBe(0);
expect(await file.exists()).toBe(false);

await Bun.write(path, "hello world");

expect(file.size).toBe(11);
expect(await file.text()).toBe("hello world");
expect(await file.slice(0, 5).text()).toBe("hello");
});

test("structuredClone() of a missing file does not empty the source handle or shrink a slice of it", async () => {
await using dir = tempDir("bun-file-clone-before-create", {});
const path = join(dir, "f.txt");
const whole = Bun.file(path);
const slice = Bun.file(path).slice(6, 11);

const clones = [structuredClone(whole), structuredClone(slice)];
expect([whole.size, slice.size]).toEqual([0, 5]);

await Bun.write(path, "hello world");

expect(await Promise.all([whole.text(), slice.text(), clones[0].text(), clones[1].text()])).toEqual([
"hello world",
"world",
"hello world",
"world",
]);
expect([whole.size, slice.size]).toEqual([11, 5]);
});

// https://github.com/oven-sh/bun/issues/4930
test("exists() on the destination does not make Bun.write(destination, Bun.file(source)) copy 0 bytes", async () => {
await using dir = tempDir("bun-file-copy-after-exists", {
"source.txt": "copied through Bun.write",
});
const destinationPath = join(dir, "destination.txt");
const destination = Bun.file(destinationPath);

expect(await destination.exists()).toBe(false);
expect(destination.size).toBe(0);

expect(await Bun.write(destination, Bun.file(join(dir, "source.txt")))).toBe("copied through Bun.write".length);

expect(await Bun.file(destinationPath).text()).toBe("copied through Bun.write");
expect(await destination.text()).toBe("copied through Bun.write");
expect(await destination.exists()).toBe(true);
});

// https://github.com/oven-sh/bun/issues/22484
test("exists() follows the file through create, delete and create again", async () => {
await using dir = tempDir("bun-file-exists-live", { "f.txt": "first" });
const path = join(dir, "f.txt");
const file = Bun.file(path);
const seen: boolean[] = [];

seen.push(await file.exists());
unlinkSync(path);
seen.push(await file.exists());
await Bun.write(path, "second");
seen.push(await file.exists());

expect(seen).toEqual([true, false, true]);
expect(await file.text()).toBe("second");
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

test("exists() on a slice stats the file", async () => {
await using dir = tempDir("bun-file-slice-exists", { "f.txt": "hello world" });
const path = join(dir, "f.txt");

expect(await Bun.file(path).slice(0, 5).exists()).toBe(true);
expect(await Bun.file(join(dir, "missing.txt")).slice(0, 5).exists()).toBe(false);
});
});

test("Bun.file().json() with UTF-8 BOM does not free an interior pointer", async () => {
// When a file starts with EF BB BF, the BOM is stripped before parsing and
// the temporary read buffer is freed. Previously the *post-strip* slice was
Expand Down
Loading