Skip to content

vm: keep #ungetc's bytes out of the file, and count them in #pos - #977

Merged
tannevaled merged 2 commits into
mainfrom
ungetc-write-position
Nov 22, 2026
Merged

tannevaled merged 2 commits into
mainfrom
ungetc-write-position

Conversation

@tannevaled

@tannevaled tannevaled commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What

IO#ungetc / #ungetbyte on a File now behave as MRI's read buffer does: the pushed-back bytes are never written to the file, and the position counts them. Refs #974 (its ungetc item; the pread flush item and the TOCTOU item stay open).

Why

A File holds its content in buf, and #ungetc spliced the bytes into it with no record of where they were. Two defects followed.

  • A later buffered write flushed buf whole, so the pushed-back bytes reached the disk. getc; ungetc "Z"; seek(0, :END); write "x" left "0Z123…x" in the file.
  • The cursor ignored them. MRI's position is the descriptor's offset minus what the read buffer still holds (rb_io_tell: pos -= fptr->rbuf.len), so every write after an ungetc landed late. getc; ungetc "Z"; write "AB" gave "0AB23456789", where MRI 4.0.7 gives "AB23456789".

How

internal/vm/io_pushback.go records the region [ungetLo, ungetHi) the bytes occupy and implements io_unread from io.c:

  • Writes (rb_io_check_writable), #flush, #seek, #rewind, #pos=, #truncate, #syswrite and #pwrite drop the pushback. The cursor then moves to the logical position. When that position is negative, it moves to where the read-ahead stopped.
  • #pos (io_tell, discard_rbuf = false) drops the pushback only when the position is valid. Otherwise it keeps the pushback and answers the negative position, as MRI does.
  • #sysread and #sysseek raise IOError … for buffered IO (READ_DATA_BUFFERED).
  • Flushes, #pread's buffer fallback and File#size see the file without the pushback.
  • #reopen and set_encoding_by_bom replace the buffer, so they reset the region. reopen(io) adopts the file's bytes, not the other stream's pushback.

StringIO keeps its own semantics, and those are now MRI's. ext/stringio strio_unget_bytes writes the pushback into the string, over the bytes just read. rbgo had spliced it in like a file's: StringIO.new("0123"), then getc, ungetc "Z", write "AB" gave "0AB23" at pos 1 instead of "AB23" at pos 0.

Measured

  • Differential against MRI 4.0.7: rubydiff on 44 probe rows (33 File, 8 StringIO, 3 reopen/empty), all AGREE. One exception, documented in the README divergences table: on a file larger than 8192 bytes, MRI refuses pushback beyond what was read (IOError: ungetbyte failed, io_ungetbyte's capacity check). rbgo accepts it.
  • Tests: TestUngetcOnAFileIsNotTheFiles (22 rows), TestStringIOUngetcWritesIntoTheString (9), TestReopenDropsThePushback, plus two internal tests. One holds the defensive guard in compactPushback, the other asserts diskBytes does not allocate without pushback.
  • internal/vm suite: ok, 286 s.
  • Mutation sweep, io_pushback.go: mutsweep caught 7/7. The first sweep's five survivors were read one by one: two redundant guards were removed, and three got tests.
  • Mutation sweep, the two for buffered IO refusals: mutsweep does not list them as refusals (body is a raise(...) call). A hand-made false && mutant of each turned exactly its own subtest red.
  • Cross-platform: buildscan --vet: go vet passed under all 19 CI configurations.

Second commit: where a failed unread leaves the stream

The first CI run was red on the coverage ratchet: no test reached diskBytes's copy branch. Writing a test for that branch exposed a defect in the first commit. When the logical position is negative, io_unread's lseek fails and the stream stays where its descriptor is. The first commit put that at end-of-file whenever anything had been read. That holds only after a buffered read (getc, gets, getbyte, readchar), which fills rbuf ahead of the cursor. IO#read and #readpartial on an empty rbuf read straight into the string (io_bufread, io_getpartial), so the descriptor is at the cursor. With f.read(1); f.ungetc("XYZ"); f.write("Q"), MRI writes Q at offset 1, and rbgo appended it.

  • The stream keeps fdAt, the descriptor's offset while rbuf holds nothing. A discarding unread, a seek, #pos=, #rewind, a write and a direct read set it to the cursor. A read that starts with pushback in rbuf is not direct: io_bufread takes the pushback, then refills with io_fillbuf.
  • File#size on a writable stream drops the pushback (rb_file_size → flush_before_seek → io_unread).
  • #readpartial and #read_nonblock return no more than the pushback while some is left (io_getpartial).

Measured: rubydiff agrees with MRI 4.0.7 on 48 new probe rows (16 sequences × flush, write and SEEK_CUR). Every earlier probe still agrees, apart from the known 8192-byte capacity row. TestUngetcOnAFileIsNotTheFiles has 11 new rows, and every function in io_pushback.go is at 100 % coverage. mutsweep caught 8/8. A hand-made if true || wasAt mutant in readThrough turned exactly its row red. The internal/vm suite is ok (457 s), and buildscan --vet passed.

🤖 Generated with Claude Code

tannevaled and others added 2 commits November 22, 2026 11:58
A File holds its content in buf, and #ungetc spliced the pushed-back
bytes into it with no record of where they were. A later buffered
write flushed buf whole, so the bytes reached the disk, and the cursor
ignored them: MRI's position is the descriptor's offset minus what the
read buffer still holds, so every write after an ungetc landed late.

io_pushback.go records the region the bytes occupy and implements
io.c's io_unread: writes, #flush, #seek, #rewind, #pos=, #truncate,
#syswrite and #pwrite drop the pushback and move to the logical
position; #pos (io_tell) drops it when that position is valid and
answers it negative otherwise; #sysread and #sysseek refuse "for
buffered IO"; flushes, #pread's fallback and File#size see the file
without it. IO#reopen and set_encoding_by_bom, which replace the
buffer, reset the region, and reopen(io) adopts the file's bytes, not
the other stream's pushback.

StringIO keeps its own semantics, now MRI's: strio_unget_bytes writes
the pushback into the string over the bytes just read, where it was
spliced in like a file's.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When more is pushed back than was read, io_unread's lseek fails and the
stream stays where its descriptor is. #977's first commit put that at
end-of-file whenever anything had been read, which holds only after a
buffered read (getc, gets, getbyte, readchar): those fill rbuf ahead,
and MRI reads a file of up to 8192 bytes whole. IO#read and
#readpartial on an empty rbuf read straight into the string
(io_bufread, io_getpartial), so the descriptor is at the cursor:

    f.read(1); f.ungetc("XYZ"); f.write("Q")

writes Q at offset 1 under MRI 4.0.7; rbgo appended it. The stream now
keeps fdAt, the descriptor's offset while rbuf holds nothing. Every
operation that empties rbuf sets it to the cursor: a discarding unread,
a seek, #pos=, #rewind, a write, and a direct read. A buffered read
moves the cursor past it, and then the descriptor is at end-of-file.
A read that starts with pushback in rbuf is not direct: io_bufread
takes the pushback and refills with io_fillbuf.

Two neighbours found by the same probes:
- File#size on a writable stream runs flush_before_seek, whose
  io_unread drops the pushback (rb_file_size); rbgo kept it.
- #readpartial and #read_nonblock return only what rbuf holds while
  pushback is left (io_getpartial); rbgo read on into the file.

Also the coverage gate that failed #977 on ubuntu and macOS: diskBytes'
copy branch was reached by no test. "a pending write is flushed without
the pushback" reaches it through #flush.

Measured with rubydiff against MRI 4.0.7 (the installed one; the
io_unread read is from the 4.0.9 source): 48 new probe rows across 16
read/seek/write sequences, plus the earlier #974 probes, all agree
except the known 8192-byte capacity row. 11 rows added to
TestUngetcOnAFileIsNotTheFiles.

Refs #974

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tannevaled
tannevaled merged commit 4b7081c into main Nov 22, 2026
26 checks passed
@tannevaled
tannevaled deleted the ungetc-write-position branch November 22, 2026 14:54
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