ziglang/zig
261
5.9k
Fork
You've already forked zig
764

Io.Threaded: detecting non-blocking IO with poll is unsound #31718

Open
opened 2026年03月31日 02:04:33 +02:00 by gooncreeper · 4 comments
Contributor
Copy link

Zig Version

0.16.0-dev.2987+1311880ee

Steps to Reproduce and Observed Behavior

Below are two examples of where Io.Batch.awaitConcurrent does not work properly using Io.Threaded.


This first example combines data from two streams and writes it to stdout:

conststd=@import("std");pubfnmain(init:std.process.Init)!void{constio=init.io;constargs=tryinit.minimal.args.toSlice(init.arena.allocator());if(args.len<3)returnerror.BadArgs;conststdout:std.Io.File=.stdout();constcwd:std.Io.Dir=.cwd();varstorage:[2]std.Io.Operation.Storage=undefined;varbatch:std.Io.Batch=.init(&storage);varstreams:[2]struct{file:std.Io.File,buf:[4096]u8,vec:[1][]u8,}=undefined;for(0..,args[1..][0..2],&streams)|i,path,*stream|{errdeferfor(streams[0..i])|s|s.file.close(io);stream.*=.{.file=trycwd.openFile(io,path,.{}),.buf=undefined,.vec=.{&stream.buf},};batch.addAt(@intCast(i),.{.file_read_streaming=.{.file=stream.file,.data=&stream.vec,}});}defer{for(streams)|s|s.file.close(io);batch.cancel(io);}varremaining:usize=streams.len;while(remaining!=0){trybatch.awaitConcurrent(io,.none);while(batch.next())|completion|{constn=completion.result.file_read_streamingcatch|e|switch(e){error.EndOfStream=>{remaining-=1;continue;},else=>returne,};consts=streams[completion.index];stdout.writeStreamingAll(io,s.buf[0..n])catch|e|switch(e){error.BrokenPipe=>return,else=>returne,};batch.addAt(completion.index,.{.file_read_streaming=.{.file=s.file,.data=&s.vec,}});}}}

Build the executable and create two pipes:

zig build-exe stream-combine.zig
mkfifo a b

When the below is run it should output 1 and 2 at about the same time, however it (usually) waits until the first pipe is closed to output 2 for reasons explained in the comments.

./stream-combine a b &
cat a &
# Open the write-end of both pipes so the program can open them and
# begin polling.
sleep 4 >> a &
sleep 1 >> b &
sleep 0.5 # Give the program a moment to open and start polling them
# Write data to both pipes 
echo 1 >> a # cat will almost always read this before the program,
# however the program will still see POLLIN and block on a read from
# the pipe until it is closed and EndOfStream is indicated.
echo 2 >> b
wait

The following code should finish (on a unix-based system):

This next example creates a child process which performs a blocking write to stdout and then reads from stdin. The main process concurrently reads the child's stdout and writes to stdin.

When run, the program gets deadlocked by both processes blocking on writes since pipes do not support short writes; POLLOUT only indicates one byte of data can written without blocking, and also has the same race-condition demonstrated above.

conststd=@import("std");pubfnmain(init:std.process.Init)!void{constargs=tryinit.minimal.args.toSlice(init.arena.allocator());if(args.len<1)returnerror.BadArgs;constblocking_write_size:usize=65537;// (for an empty pipe on x86_64 linux;// can be less if there is data already buffered)constblocking_write_data:[blocking_write_size]u8=@splat(0);if(args.len==1){// main processvarchild=trystd.process.spawn(init.io,.{.argv=&.{args[0],"options"},.stdin=.pipe,.stdout=.pipe,});errdeferchild.kill(init.io);conststdin=child.stdin.?;conststdout=child.stdout.?;varsend_vec:[1][]constu8=.{&blocking_write_data};varrecv_buf:[4096]u8=undefined;constrecv_vec:[1][]u8=.{&recv_buf};varrecieved:usize=0;varstorage:[2]std.Io.Operation.Storage=undefined;varbatch:std.Io.Batch=.init(&storage);deferbatch.cancel(init.io);batch.addAt(0,.{.file_write_streaming=.{.file=stdin,.data=&send_vec}});batch.addAt(1,.{.file_read_streaming=.{.file=stdout,.data=&recv_vec}});while(send_vec[0].len!=0orrecieved!=blocking_write_size){trybatch.awaitConcurrent(init.io,.none);while(batch.next())|completion|switch(completion.index){0=>{send_vec[0]=send_vec[0][trycompletion.result.file_write_streaming..];if(send_vec[0].len==0)continue;batch.addAt(0,.{.file_write_streaming=.{.file=stdin,.data=&send_vec}});},1=>{recieved+=trycompletion.result.file_read_streaming;if(recieved==blocking_write_size)continue;batch.addAt(1,.{.file_read_streaming=.{.file=stdout,.data=&recv_vec}});},else=>unreachable,};}stdin.close(init.io);child.stdin=null;_=trychild.wait(init.io);}else{// sub processconststdin=std.Io.File.stdin();conststdout=std.Io.File.stdout();trystdout.writeStreamingAll(init.io,&blocking_write_data);varstdin_buf:[4096]u8=undefined;varstdin_r=stdin.readerStreaming(init.io,&stdin_buf);_=stdin_r.interface.discardRemaining()catch|e|switch(e){error.ReadFailed=>returnstdin_r.err.?,};}}
### Zig Version 0.16.0-dev.2987+1311880ee ### Steps to Reproduce and Observed Behavior Below are two examples of where `Io.Batch.awaitConcurrent` does not work properly using `Io.Threaded`. --- This first example combines data from two streams and writes it to stdout: ```zig const std = @import("std"); pub fn main(init: std.process.Init) !void { const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len < 3) return error.BadArgs; const stdout: std.Io.File = .stdout(); const cwd: std.Io.Dir = .cwd(); var storage: [2]std.Io.Operation.Storage = undefined; var batch: std.Io.Batch = .init(&storage); var streams: [2]struct { file: std.Io.File, buf: [4096]u8, vec: [1][]u8, } = undefined; for (0.., args[1..][0..2], &streams) |i, path, *stream| { errdefer for (streams[0..i]) |s| s.file.close(io); stream.* = .{ .file = try cwd.openFile(io, path, .{}), .buf = undefined, .vec = .{&stream.buf}, }; batch.addAt(@intCast(i), .{ .file_read_streaming = .{ .file = stream.file, .data = &stream.vec, } }); } defer { for (streams) |s| s.file.close(io); batch.cancel(io); } var remaining: usize = streams.len; while (remaining != 0) { try batch.awaitConcurrent(io, .none); while (batch.next()) |completion| { const n = completion.result.file_read_streaming catch |e| switch (e) { error.EndOfStream => { remaining -= 1; continue; }, else => return e, }; const s = streams[completion.index]; stdout.writeStreamingAll(io, s.buf[0..n]) catch |e| switch (e) { error.BrokenPipe => return, else => return e, }; batch.addAt(completion.index, .{ .file_read_streaming = .{ .file = s.file, .data = &s.vec, } }); } } } ``` Build the executable and create two pipes: ```sh zig build-exe stream-combine.zig mkfifo a b ``` When the below is run it should output 1 and 2 at about the same time, however it (usually) waits until the first pipe is closed to output 2 for reasons explained in the comments. ```sh ./stream-combine a b & cat a & # Open the write-end of both pipes so the program can open them and # begin polling. sleep 4 >> a & sleep 1 >> b & sleep 0.5 # Give the program a moment to open and start polling them # Write data to both pipes echo 1 >> a # cat will almost always read this before the program, # however the program will still see POLLIN and block on a read from # the pipe until it is closed and EndOfStream is indicated. echo 2 >> b wait ``` --- The following code should finish (on a unix-based system): This next example creates a child process which performs a blocking write to stdout and then reads from stdin. The main process concurrently reads the child's stdout and writes to stdin. When run, the program gets deadlocked by both processes blocking on writes since pipes do not support short writes; POLLOUT only indicates one byte of data can written without blocking, and also has the same race-condition demonstrated above. ```zig const std = @import("std"); pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len < 1) return error.BadArgs; const blocking_write_size: usize = 65537; // (for an empty pipe on x86_64 linux; // can be less if there is data already buffered) const blocking_write_data: [blocking_write_size]u8 = @splat(0); if (args.len == 1) { // main process var child = try std.process.spawn(init.io, .{ .argv = &.{ args[0], "options" }, .stdin = .pipe, .stdout = .pipe, }); errdefer child.kill(init.io); const stdin = child.stdin.?; const stdout = child.stdout.?; var send_vec: [1][]const u8 = .{&blocking_write_data}; var recv_buf: [4096]u8 = undefined; const recv_vec: [1][]u8 = .{&recv_buf}; var recieved: usize = 0; var storage: [2]std.Io.Operation.Storage = undefined; var batch: std.Io.Batch = .init(&storage); defer batch.cancel(init.io); batch.addAt(0, .{ .file_write_streaming = .{ .file = stdin, .data = &send_vec } }); batch.addAt(1, .{ .file_read_streaming = .{ .file = stdout, .data = &recv_vec } }); while (send_vec[0].len != 0 or recieved != blocking_write_size) { try batch.awaitConcurrent(init.io, .none); while (batch.next()) |completion| switch (completion.index) { 0 => { send_vec[0] = send_vec[0][try completion.result.file_write_streaming..]; if (send_vec[0].len == 0) continue; batch.addAt(0, .{ .file_write_streaming = .{ .file = stdin, .data = &send_vec } }); }, 1 => { recieved += try completion.result.file_read_streaming; if (recieved == blocking_write_size) continue; batch.addAt(1, .{ .file_read_streaming = .{ .file = stdout, .data = &recv_vec } }); }, else => unreachable, }; } stdin.close(init.io); child.stdin = null; _ = try child.wait(init.io); } else { // sub process const stdin = std.Io.File.stdin(); const stdout = std.Io.File.stdout(); try stdout.writeStreamingAll(init.io, &blocking_write_data); var stdin_buf: [4096]u8 = undefined; var stdin_r = stdin.readerStreaming(init.io, &stdin_buf); _ = stdin_r.interface.discardRemaining() catch |e| switch (e) { error.ReadFailed => return stdin_r.err.?, }; } } ```
gooncreeper changed title from (削除) Io.Threaded.batchAwaitConcurrent blocking on pipe writes that do not fit (削除ここまで) to Io.Threaded: detecting non-blocking IO with poll is unsound 2026年04月01日 17:59:38 +02:00
Author
Contributor
Copy link

Updated the issue to be more broad. I have been looking for ways to fix this, but it seems like the only solution (besides using some evented solution, which does not seem to be in line with Io.Threaded) would be to dispatch the syscalls to other threads. This would regress single-threaded polling with Io.Threaded, but the current behavior is incorrect and an evented implementation should just be used instead.

Updated the issue to be more broad. I have been looking for ways to fix this, but it seems like the only solution (besides using some evented solution, which does not seem to be in line with `Io.Threaded`) would be to dispatch the syscalls to other threads. This would regress single-threaded polling with `Io.Threaded`, but the current behavior is incorrect and an evented implementation should just be used instead.
andrewrk added this to the Urgent milestone 2026年04月01日 18:29:27 +02:00

Small reminder since it's somewhat related: Calling poll for POLLIN or POLLOUT on regular files, block devices and "other files with no reasonable polling semantic" always returns instantly (see poll(2) documentation for Linux), even for files on network filesystems.

So yeah, you could have poll (or select, or epoll) return immediately with ready for read and still block for an extended period of time when you actually want to read.

Small reminder since it's somewhat related: Calling poll for POLLIN or POLLOUT on regular files, block devices and "other files with no reasonable polling semantic" always returns instantly (see poll(2) documentation for Linux), even for files on network filesystems. So yeah, you could have poll (or select, or epoll) return immediately with ready for read and still block for an extended period of time when you actually want to read.

I think this can be fixed by observing the nonblocking flag on File. In the case of batchAwaitAsync and Io.operate it's acceptable for some of the operations to run blocking, while in the case of batchAwaitConcurrent and operateTimeout it should return error.ConcurrencyUnavailable if the file flag is marked blocking.

Alternately, these operations can take a *File and make changes to the file descriptor as needed:

  • When Batch API is used or operateTimeout, and the file is blocking, do the F_SETFL, O_NONBLOCK on the fd and change the File flag
  • When a normal, synchronous operation returns EAGAIN either remove the O_NONBLOCK on the fd and change the File flag and try again, or use poll to wait and try again.
I think this can be fixed by observing the nonblocking flag on File. In the case of `batchAwaitAsync` and `Io.operate` it's acceptable for some of the operations to run blocking, while in the case of `batchAwaitConcurrent` and `operateTimeout` it should return `error.ConcurrencyUnavailable` if the file flag is marked blocking. Alternately, these operations can take a `*File` and make changes to the file descriptor as needed: * When `Batch` API is used or `operateTimeout`, and the file is blocking, do the `F_SETFL, O_NONBLOCK` on the fd and change the File flag * When a normal, synchronous operation returns `EAGAIN` either remove the `O_NONBLOCK` on the fd and change the File flag and try again, or use `poll` to wait and try again.
Author
Contributor
Copy link

it should return error.ConcurrencyUnavailable if the file flag is marked blocking.

It seems that Io.Threaded currently opens all files with O.NONBLOCK = false so wouldn't this mean every concurrent batch write would fail?

Alternately, these operations can take a *File and make changes to the file descriptor as needed:

  • When Batch API is used or operateTimeout, and the file is blocking, do the F_SETFL, O_NONBLOCK on the fd and change the File flag

  • When a normal, synchronous operation returns EAGAIN either remove the O_NONBLOCK on the fd and change the File flag and try again, or use poll to wait and try again.

Based off the manpage for write, O_NONBLOCK has special semantics for pipe writes. Writes smaller than PIPE_BUF which don't fit in the pipe's buffer return EAGAIN even if part of it would fit. Writes larger than PIPE_BUF will write at least one byte when possible. So, there is no guarantee data is written even when there is space, even though poll will continue to set POLLOUT for the file. Perhaps a binary search with O_NONBLOCK could be used to find how many bytes can actually be written, but that seems a bit clumsy and would take several syscalls.

> it should return `error.ConcurrencyUnavailable` if the file flag is marked blocking. It seems that `Io.Threaded` currently opens all files with `O.NONBLOCK = false` so wouldn't this mean every concurrent batch write would fail? > Alternately, these operations can take a `*File` and make changes to the file descriptor as needed: > > * When `Batch` API is used or `operateTimeout`, and the file is blocking, do the `F_SETFL, O_NONBLOCK` on the fd and change the File flag > > * When a normal, synchronous operation returns `EAGAIN` either remove the `O_NONBLOCK` on the fd and change the File flag and try again, or use `poll` to wait and try again. Based off the manpage for write, `O_NONBLOCK` has special semantics for pipe writes. Writes smaller than `PIPE_BUF` which don't fit in the pipe's buffer return `EAGAIN` even if part of it would fit. Writes larger than `PIPE_BUF` will write at least one byte when possible. So, there is no guarantee data is written even when there is space, even though poll will continue to set `POLLOUT` for the file. Perhaps a binary search with `O_NONBLOCK` could be used to find how many bytes can actually be written, but that seems a bit clumsy and would take several syscalls.
Sign in to join this conversation.
No Branch/Tag specified
master
elfv2
spork8
restricted
0.16.x
panic-rewrite
parking-futex-lockfree
windows-Io-cleanup
Io-watch
ParseCommandLineOptions
windows-async-files
poll-ring
debug-file-leaks-differently
debug-file-leaks
ProcessPrng
elfv2-dyn
jobserver
threadtheft
io-threaded-no-queue
0.15.x
Io.net
comptime-allocator
restricted-function-pointers
cli
wasm-linker-writer
wrangle-writer-buffering
sha1-stream
async-await-demo
fixes
0.14.x
ast-node-methods
macos-debug-info
make-vs-configure
fuzz-macos
sans-aro
ArrayList-reserve
incr-bug
llvm-ir-nosanitize-metadata
ci-tarballs
ci-scripts
threadpool
0.12.x
new-pkg-hash
json-diagnostics
more-doctests
rework-comptime-mutation
0.11.x
ci-perf-comment
stage2-async
0.10.x
autofix
0.9.x
aro
hcs
0.8.x
0.7.x
0.16.0
0.15.2
0.15.1
0.15.0
0.14.1
0.14.0
0.12.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.0
0.2.0
0.1.1
0.1.0
Labels
Clear labels
abi/f32
abi/ilp32
abi/sf
accepted
This proposal is planned.
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
The web application for interactive documentation and generation of its assets.
backend/c
The C backend outputs C source code.
backend/llvm
The LLVM backend outputs an LLVM bitcode module.
backend/self-hosted
The self-hosted backends produce machine code directly.
binutils
Zig's included binary utilities: zig ar, zig dlltool, zig lib, zig ranlib, zig objcopy, and zig rc.
breaking
Implementing this issue could cause existing code to no longer compile or have different behavior.
build system
The Zig build system - zig build, std.Build, the build runner, and package management.
debug info
An issue related to debug information (e.g. DWARF) produced by the Zig compiler.
docs
An issue with documentation, e.g. the language reference or standard library doc comments.
error message
This issue points out an error message that is unhelpful and should be improved.
frontend
Tokenization, parsing, AstGen, ZonGen, Sema, Legalize, and Liveness.
fuzzing
An issue related to Zig's integrated fuzz testing.
incremental
Reuse of internal compiler state for faster compilation.
lib/c
This issue relates to Zig's libc implementation and/or vendored libcs.
lib/compiler-rt
This issue relates to Zig's compiler-rt library.
lib/cxx
This issue relates to Zig's vendored libc++ and/or libc++abi.
lib/std
This issue relates to Zig's standard library.
lib/tsan
This issue relates to Zig's vendored libtsan.
lib/ubsan-rt
This issue relates to Zig's ubsan-rt library.
lib/unwind
This issue relates to Zig's vendored libunwind.
linking
Zig's integrated object file and incremental linker.
miscompilation
The compiler reports success but produces semantically incorrect code.
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
This issue suggests language modifications. If it also has the "accepted" label then it is planned.
release notes
This issue or pull request should be mentioned in the release notes.
testing
This issue is related to testing the compiler, standard library, or other parts of Zig.
zig cc
Zig as a drop-in C-family compiler.
zig fmt
The Zig source code formatter.
zig reduce
The Zig source code reduction tool.
bounty
https://ziglang.org/news/announcing-donor-bounties
bug
Observed behavior contradicts documented or intended behavior.
contributor-friendly
This issue is limited in scope and/or knowledge of project internals.
downstream
An issue with a third-party project that uses this project.
enhancement
Solving this issue will likely involve adding new logic or components to the codebase.
infra
An issue related to project infrastructure, e.g. continuous integration.
optimization
A task to improve performance and/or resource usage.
question
No questions on the issue tracker; use a community space instead.
regression
Something that used to work in a previous version stopped working
upstream
An issue with a third-party project that this project uses.
use case
Describes a real use case that is difficult or impossible, but does not propose a solution.
No labels
abi/f32
abi/ilp32
abi/sf
accepted
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
backend/c
backend/llvm
backend/self-hosted
binutils
breaking
build system
debug info
docs
error message
frontend
fuzzing
incremental
lib/c
lib/compiler-rt
lib/cxx
lib/std
lib/tsan
lib/ubsan-rt
lib/unwind
linking
miscompilation
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
release notes
testing
zig cc
zig fmt
zig reduce
bounty
bug
contributor-friendly
downstream
enhancement
infra
optimization
question
regression
upstream
use case
Milestone
Clear milestone
No items
No milestone
Projects
Clear projects
No items
No project
Assignees
Clear assignees
No assignees
3 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
ziglang/zig#31718
Reference in a new issue
ziglang/zig
No description provided.
Delete branch "%!s()"

Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?