Skip to content

Buffered file and stdout writes with a manual File.flush #2160

Open

Description

@nicolas-abril

Today

The two output paths behave differently:

C lane JS lane
IO.print / IO.write (stdout) buffered (stdio) buffered when stdout is not a terminal (64 KiB batches)
File.write / write_bytes / write_at a write/pwrite per call on a helper thread a fs.writeSync per call
IO.print_err direct direct

So many small file writes cost a syscall each, while stdout batches. The runtime orders the two by flushing stdout before a file or process job (#2155). Base has no flush effect, so a program can't do it itself.

Proposal

Buffer both, the same way, with a manual flush, as C's stdio and Python do:

  • File.stdout (and File.stderr) as File handles. IO.print is a write to File.stdout.
  • A per-handle write buffer for files on both lanes.
  • File.flush(h): flushes h's buffer, a no-op if it is empty.
  • The runtime still flushes:
    • at File.close and at exit, so the tail of the output is not lost;
    • before a read, size or positioned write on the same handle, so a handle sees its own writes (C requires this of stdio too);
    • nowhere else, so stderr stays unbuffered.
  • What stays manual is the case fix(io): flush stdout before native IO jobs #2155 handles today: output reaching one destination through two handles or a child process (stdout redirected to a file the program also writes or reads, or a Process.run child that reads that file; the child's own stdio is piped, not inherited). The program calls File.flush(File.stdout) first, like fflush in C. fix(io): flush stdout before native IO jobs #2155's automatic flush goes away.

To decide

  • Buffer size, and whether a terminal stdout is line-buffered (C) or unbuffered (the JS lane today).
  • Whether a flush error (EPIPE on a closed pipe) is a Result from File.flush or ends the program as a short write on a standard stream does now.
  • guide/EFFECTS.md and the guide on when to flush.

(File.sync(h), durability to disk with fsync, is a separate question.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions