Skip to content

vm: flush only what a stream wrote, and only into the file it opened - #978

Merged
tannevaled merged 9 commits into
mainfrom
path-identity
Nov 22, 2026
Merged

tannevaled merged 9 commits into
mainfrom
path-identity

Conversation

@tannevaled

@tannevaled tannevaled commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What

Two #974 items, stacked: a flush writes only what this stream wrote, and a stream writes only into the file it opened.

1. Flush only the byte ranges this stream wrote (eac0f2e2, 4efc544e, f570a420)

ioFlush wrote the stream's whole in-memory copy over the file with os.WriteFile. So the next flush overwrote another writer's bytes elsewhere in the file, an append from another process, or a truncation. MRI's io_fflush writes only fptr->wbuf, at the stream's offset.

  • Recorded spans. The stream records the [lo, hi) spans it wrote (internal/vm/io_dirty.go). Spans that touch or overlap merge. Past 256 separate spans the list collapses into its union, so scattered writes cannot grow it without bound.
  • How a flush writes. A flush writes each span at its offset, or appends it in append mode. #truncate clips the spans, and #pwrite's buffer fallback marks its range.
  • Errors. A refused flush raises the errno the system answered, as rb_io_flush_raw does through rb_sys_fail_on_write. Before, the error was flattened to ENOENT, so a flush to a directory raised ENOENT where EISDIR is the answer.

2. Write only into the file the stream opened (18964d02)

A File here holds no descriptor: flushes, #pwrite and #truncate reopen its path. MRI writes through the descriptor it opened, so it never touches a file renamed over the path or a symlink put in its place, and it never creates an unlinked file again.

Reopening by path did touch them. If the path was swapped for a symlink between the open and the flush, the stream's pending bytes went into the link's target. That is the TOCTOU item of #974.

  • Recorded identity. A file stream now records the identity of the file it opened (internal/vm/io_identity.go).
  • Two checks per write by path.
    • Before the open, rbgo checks the path, so a fifo or a device put in its place is not opened.
    • After the open, rbgo checks the descriptor, so a rename in between is caught.
  • When the path names another file. Nothing is written there. The bytes stay in the stream's buffer, where its own reads, #size and #pread still see them.
  • The owner-write bit. withOwnerWrite grants and restores the owner-write bit only on the opened file.

3. Keep the opened inode alive, so its number is not reused (8c290638, 705397ad, f21e4e64, 034a846a)

The Linux runner failed the row "deleted, then created again by another writer". ext4 gave the new file the old inode number, os.SameFile took it for the opened file, and the stream's byte went into it. MRI's open descriptor keeps the inode alive, so its number cannot be reused while the stream is open.

  • The pin. On Unix, a file stream now holds a descriptor on the file it opened (internal/vm/io_pin_unix.go). It is opened O_RDONLY, or O_WRONLY for a file whose mode refuses reading, with O_NONBLOCK|O_NOCTTY so that a fifo cannot block. The stream takes its identity from that descriptor.
  • Release and adoption. The pin is released on #close, #close_read/#close_write and #reopen. A stream adopting another's file (IO#reopen(io), IO.new on its descriptor) gets its own F_DUPFD_CLOEXEC dup.
  • AIX. AIX has no F_DUPFD_CLOEXEC in x/sys, so it uses dup(2) then FD_CLOEXEC under syscall.ForkLock. A cross-build found the break; no CI lane compiles AIX.
  • Fallback. A file whose mode refuses both opens keeps the plain stat identity, and with it the reuse window.

#truncate on a file made read-only after the open now lends the open's grant for the call, as a flush does. MRI 4.0.7 truncates through its descriptor ([2, 292]), where rbgo raised Errno::EACCES. The refusals it does meet are raised with their errno.

4. Map a Win32 error code before raising a flush (d49cec5f)

Item 1 made a flush raise the errno the system answered. On Windows that errno is the Win32 code itself, and reading it as a POSIX number picks an unrelated class. The Windows runner showed it: ERROR_PATH_NOT_FOUND (3) raised Errno::ENOTDIR where MRI raises Errno::ENOENT.

  • The table. internal/vm/errno_win32_windows.go ports the Win32 rows of MRI's errmap (win32/win32.c:145, v4.0.9), keyed by golang.org/x/sys/windows constants.
  • The lookup. mapHostErrno is rb_w32_map_errno: a code in the table gets its class, a code at or above WSABASEERR is kept, and any other code is EINVAL. Outside Windows it is the identity.
  • Scope. Only raiseFlushErr applies it here. The older raisers (sysFail and the others) still read a Win32 code as a POSIX number; that is Windows: Errno classes come from the raw Win32 code; MRI maps it through rb_w32_map_errno first #980.

A side effect of item 2 fixes a divergence the suite had pinned (#635): #truncate on a file unlinked while open now succeeds, as MRI's ftruncate does, instead of raising Errno::ENOENT.

Measured

  • Oracle: rubydiff against MRI 4.0.7 (arm64-darwin25); reference source 4.0.9.
    • Flush probe: 7 of 8 rows diverged before; all 8 agree after.
    • Identity probes probe974t.rb and probe974t2.rb: the 12 rows that diverged now agree. The guard rows behave the same before and after: a file opened through a symlink, a read-only file written by the open's grant, and plain integer flags.
    • Truncate probe probe978t.rb (chmod 0444 after the open, then #truncate): diverged with Errno::EACCES, agrees now.
  • Tests:
    • TestAFlushWritesOnlyWhatThisStreamWrote holds the flush rows.
    • TestAWriteByPathReachesOnlyTheOpenedFile holds the 14 identity rows, each with MRI's output as the expected value.
    • Internal tests cover openOpenedFile, truncateOpenedFile, truncateOnDisk and withOwnerWrite. They include a rename injected between the path check and the open.
    • The pin and its dup have their own tests: a closed pin, a failed dup, and a dup reporting an error with a valid number.
  • Full suite: ok, internal/vm in 234 s. buildscan --vet passed under all 19 CI configurations. Outside CI, aix/ppc64 vets, and solaris, illumos, dragonfly, openbsd, netbsd, freebsd and plan9 build.
  • Coverage: every function in io_identity.go, pinFile, writeDirty, raiseFlushErr and withOwnerWrite is at 100 %.
  • mutsweep: every refusal in io_identity.go, file_mode.go and io_dirty.go, plus the changed lines in io.go and io_positional.go, is caught.
    • Two refusals were redundant: a nil-identity fast path, and an errNotTheOpenedFile check repeated in the caller. Both were removed.
    • ioFlush's gate only made the suite hang when deleted, so TestIOFlushWritesOnlyAWritableFileWithPendingBytes now asserts it directly.
    • io_pin_unix.go: dupPin's nil check doubled SyscallConn's own ErrInvalid and was removed. Its dup-error check is now held by an error that comes with a valid number. The dupPin(nil) row asserts its outcome instead of letting a panic answer for it.
    • The write-error refusal was held only on Linux, by /dev/full. TestAFlushPastTheFileSizeLimitRaises now holds it on darwin too, through RLIMIT_FSIZE, which makes write(2) answer EFBIG.

Remaining divergences (README rows updated)

  • Where the bytes go. MRI's bytes land on the orphaned inode; rbgo keeps them in the stream's buffer, so another process holding that inode does not see them.
  • Inode reuse without a pin. A file whose mode refuses both a read and a write open gets no pin, and keeps the reuse window that ext4 showed.
  • Fifo race. A fifo swapped in between rbgo's two checks can still make the open block. Closing that window needs a per-platform non-blocking open.
  • Span limit. Past 256 separate unflushed ranges, rbgo merges them into one span. A flush then rewrites the gaps between them with its own copy of those bytes.
  • Unchanged here. File#stat on a file unlinked while open still raises; same root as File::Stat: no atime/ctime on Windows, and File#stat cannot answer for an unlinked open file #635.

Refs #974
Refs #980 (the flush path maps Win32 codes; the other raisers stay open there)
Refs #635 (#truncate now agrees; File#stat on an unlinked file keeps it open)

🤖 Generated with Claude Code

tannevaled and others added 8 commits November 22, 2026 16:41
ioFlush wrote the stream's whole in-memory copy over the file with
os.WriteFile. Another writer's bytes elsewhere in the file, an append
made by another process, or a truncation were all overwritten by the
next flush. MRI flushes its write buffer at the stream's offset and
touches nothing else.

The stream now records the [lo, hi) spans it wrote (io_dirty.go):
touching or overlapping spans merge, and past 256 separate spans the
list collapses into its union so scattered writes cannot grow it
without bound. A flush writes each span at its offset with WriteAt, or
appends it in append mode. #truncate clips the spans and #pwrite's
fallback marks its range. The dirty list replaces the wbufDirty flag,
so there is one record of what is pending.

A refused flush now raises the errno the system answered, as
rb_io_flush_raw does through rb_sys_fail_on_write. It used to be
flattened to ENOENT (or EACCES), so a flush to a directory raised
ENOENT where EISDIR is the answer, and a full disk raised ENOENT where
ENOSPC is.

Measured against MRI 4.0.9 with rubydiff: 7 of 8 probe rows diverged
before, all 8 agree after. TestAFlushWritesOnlyWhatThisStreamWrote
carries the 8 rows. mutsweep over io_dirty.go: the empty-span refusal
and the open-error refusal are caught; the write-error refusal is held
by TestAFlushThatCannotWriteRaises, which needs /dev/full and so runs
on the Linux lane only.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestAFlushThatCannotWriteRaises needs /dev/full, which only the Linux
runner has, so on macOS nothing failed when writeDirty dropped a write
error (mutsweep: io_dirty.go's err != nil after WriteAt survived there).
A write past RLIMIT_FSIZE answers EFBIG once the open has succeeded,
and the Go runtime ignores SIGXFSZ, so the same assertion now holds on
darwin and linux both.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ging

ioFlush writes only a writable stream with a path and pending bytes.
Nothing asserted that directly: with the gate deleted, the suite hung on
a stream whose flush blocked (mutsweep: io.go's gate HUNG), which is no
verdict. Three rows now assert that a read-only stream, one with no
path and one with nothing pending leave the file as it was and raise
nothing.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…es now

A File holds no descriptor: flushes, #pwrite and #truncate reopen its
path. MRI writes through the descriptor it opened, so a file renamed
over the path, or a symlink put in its place, is never touched, and an
unlinked file is not created again. Reopening by path did touch them:
with the path swapped for a symlink between the open and the flush, the
stream's pending bytes were written into the link's target (#974, its
TOCTOU item).

A file stream now records the identity of the file it opened
(io_identity.go). Every write that goes back through the path checks
it on the path before the open, so a fifo or a device put in its place
is not opened, and on the descriptor after, so a rename in between is
caught. When the path names another file, nothing is written there and
the bytes stay in the stream's buffer, where its own reads, #size and
#pread still see them. withOwnerWrite grants and restores the
owner-write bit only on that file.

Measured against MRI 4.0.7 with rubydiff: the 12 rows of
probe974t.rb and probe974t2.rb that diverged now agree, and the guard
rows (a file opened through a symlink, a read-only file written by the
open's grant, plain integer flags) behaved the same before and after.
#truncate on an unlinked file now succeeds as MRI's ftruncate does,
where it raised Errno::ENOENT (#635); TestWave28TruncateFileOnDisk,
which pinned that divergence, now asserts MRI's answer.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…file

The Linux runner showed the row "deleted, then created again by another
writer" writing the stream's byte into the new file: ext4 gave the new
file the old inode number, and os.SameFile took it for the file the
stream opened. MRI's open descriptor keeps the inode alive, so its
number cannot be reused while the stream is open.

On Unix a file stream now holds a descriptor on the file it opened
(pin, opened O_RDONLY or else O_WRONLY, with O_NONBLOCK|O_NOCTTY so a
fifo cannot block it), takes its identity from that descriptor, and
releases it when it closes or moves to another file. A stream adopting
another's file (IO#reopen, IO.new on its descriptor) gets its own dup.
A file whose mode refuses both opens keeps the plain stat identity.

#truncate on a file made read-only after the open now lends the open's
grant for the call, as a flush does: MRI 4.0.7 truncates through its
descriptor ([2, 292]) where rbgo raised Errno::EACCES. Its refusals
are raised with their errno.

Tests: the pin and its dup; the truncate grant at the Ruby level and
its refusal; raiseFlushErr's three error shapes; a dirty span past the
content. rubydiff against MRI 4.0.7: probe978t, probe974t, probe974t2
agree.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mutsweep left four refusals that nothing held:

- dupPin's nil check doubled f.SyscallConn's own (os.ErrInvalid for a
  nil *os.File); it is gone, and the dupPin(nil) row now holds that
  error check.
- dupPin's check on the dup's error: the failing seam returned -1, and
  os.NewFile(-1) is nil anyway. A row now reports an error along with a
  valid descriptor number.
- rememberFile's stat fallback was never reached for a non-regular
  file. A mode-000 directory refuses both pin opens and reaches it.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
golang.org/x/sys defines no F_DUPFD_CLOEXEC for AIX, so the pin's dup
broke `GOOS=aix go build ./internal/vm`, which main builds. No CI lane
compiles AIX, so a cross-build found it.

The dup moves to dupCloexec, per platform: fcntl(F_DUPFD_CLOEXEC)
everywhere it exists, and on AIX dup(2) then FD_CLOEXEC under
syscall.ForkLock, as the os package does, so that no child forked
between the two calls inherits the descriptor.

Checked: aix/ppc64 vet; solaris, illumos, dragonfly, openbsd, netbsd,
freebsd, plan9 builds.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tannevaled added a commit to go-embedded-ruby/docs that referenced this pull request Nov 22, 2026
… keeps the open's grant

Follows go-embedded-ruby/ruby#978: on Unix a file stream holds a descriptor on the file it opened, so a reused inode number cannot pass for it, and #truncate on a file chmodded read-only after the open succeeds as in MRI 4.0.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…flush

The Windows runner failed TestIOFlushError: a flush under a missing
directory raised Errno::ENOTDIR where Errno::ENOENT is wanted. On
Windows a syscall.Errno carries the Win32 code itself:
ERROR_PATH_NOT_FOUND is 3. errnoClasses is keyed by the numbers Go
invented for the POSIX names, so 3 landed on an unrelated class. Before
this PR a flush flattened every error to ENOENT, which hid it.

MRI maps every Win32 code through errmap (win32/win32.c:145, v4.0.9,
rb_w32_map_errno): ERROR_PATH_NOT_FOUND and ERROR_FILE_NOT_FOUND are
ENOENT, ERROR_ACCESS_DENIED EACCES, ERROR_DISK_FULL ENOSPC, and so on;
a code at or above WSABASEERR is kept; any other is EINVAL.
errno_win32_windows.go ports the Win32 rows of that table, keyed by
golang.org/x/sys/windows constants so that no number is typed by hand,
and mapHostErrno applies it. It is the identity elsewhere.
raiseFlushErr maps the code before choosing the class.

The raisers that predate this PR (sysFail and the others) still read
a Win32 code as a POSIX number; that is filed separately.

TestRaiseFlushErrKeepsWhatTheErrorSays's "no class" row moves from 4093
to 9999999: on Windows 4093 is now an unknown Win32 code below
WSABASEERR, which MRI maps to EINVAL. TestMapHostErrnoIsRbW32MapErrno
holds the table's rows on Windows.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tannevaled
tannevaled merged commit 91a523d into main Nov 22, 2026
26 checks passed
@tannevaled
tannevaled deleted the path-identity branch November 22, 2026 21:56
tannevaled added a commit to go-embedded-ruby/docs that referenced this pull request Nov 22, 2026
…the opened file (#55)

* conformance: IO rows for #pwrite on disk, #ungetc, flush ranges, opened-file identity

The #pwrite row said its bytes are not on disk until a flush; since
go-embedded-ruby/ruby#975 they are, as with pwrite(2). It is rewritten
to the ruby README's current row, with the two deliberate bounds.

Three rows are added, each mirroring the ruby README:
- #ungetc keeps pushed-back bytes out of the file (go-embedded-ruby/ruby#977);
  the divergence left is MRI's 8192-byte read buffer.
- a flush writes only the ranges this stream wrote (go-embedded-ruby/ruby#978);
  the divergence left is the 256-range bound.
- a stream writes only into the file it opened, never into what its path
  names after an unlink, rename or symlink swap (go-embedded-ruby/ruby#978);
  the divergences left are the orphaned inode and the fifo window.

Refs go-embedded-ruby/ruby#974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* conformance: the opened-file row keeps its inode alive, and #truncate keeps the open's grant

Follows go-embedded-ruby/ruby#978: on Unix a file stream holds a descriptor on the file it opened, so a reused inode number cannot pass for it, and #truncate on a file chmodded read-only after the open succeeds as in MRI 4.0.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant