std.Io: introduce batching and operations API, satisfying the "poll" use case #30743
No reviewers
Labels
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/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
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
No milestone
No assignees
6 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
ziglang/zig!30743
Loading…
Reference in a new issue
No description provided.
Delete branch "poll"
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?
This branch introduces
Io.Operation,std.Io.operate,std.Io.Batch, and implements them forFileReadStreaming. Instd.Io.Threaded, the implementation is based on poll().The idea here is that every VTable function that makes sense to have
error{Canceled,Timeout}in its error set would be moved into thisOperationtagged union. Note that the higher level API, e.g.std.Io.File.readFileStreamingis unchanged. We expect this to be lowerable in a reasonable fashion using IoUring, Kqueue, and Windows.Motivation
poll()without causingerror.ConcurrencyUnavailableon-fsingle-threadedbuildsDemonstration
Using
std.process.runto collect both stdout and stderr in a single-threaded program usingstd.Threaded.Io. The point of this example is, if the parent naively reads from either stdout or stderr non-concurrently, it will deadlock.child.zig:
parent.zig
Followup Issues
closes https://github.com/ziglang/zig/issues/25753
+1 to the overall shape. Not only
collectOutputnow works with a single thread, I'd argue that its implementation is just more natural as a hand-coded state machine, and not as a pair ofasyncConcurrenttasks.Specific interface I am not happy with (but maybe I just misunderstand something). The issue I have with it is that it assumes readiness based IO, not completion based:
If
n_wait < operations.len, the interface needs to guarantee that each operation is "atomic" --- either it is completed, or otherwise not started. This works forpoll, but doesn't work forio_uring, and arguably, "real world".E.g, suppose I write low-level code that issues 5 write operations to an actual physical device. The way this works is that I ask the device to start the corresponding DMA operations, and then wait for interrupt which notifies me about completions.
I can wait for first 2 out of 5 operations to complete, but I still need to wait for other 3, I can't just drop them on the floor. The
operateinterface prevents this for two reasons:Oh, there's also the poll-vs-epoll big-O problem here: if
operations.lenis 10^6, but n_wait it 1, you still have to trawl though the million to find out which single op did complete.I agree with matklad's concerns, but can't really figure out a nice solution to them. While trying to find one, I realised that (IMO) the natural conclusion of this PR's line of thinking is to literally just expose an io_uring style API---it lets you handle completions as soon as they're available, it works with any primitive you can think of, and it allows you to reuse buffer memory. However, I strongly believe that would be a misstep: the whole point of the
IoAPI is to abstract over these low-level event loop mechanisms, so straight-up exposing an io_uring-esque API would seriously muddy the intention behind the interface (and, of course, introduces a lot of extra complexity).Also, I get the feeling that the use cases for this
operatefeature are actually pretty rare. I honestly am struggling to think of many cases where I just want to dispatch a bunch of IO operations and don't want non-trivial handling of their individual completions as they come in (if I do want that, then I should just have anasyncorconcurrenttask per operation---that's kinda the whole point of the future/group API!). However, I think that there is one very clear counterexample, which is exactly what you've done here: polling child process output streams. That's a real use case, which we really want to be able to use with a dumb single-threadedIoimplementation, and it's what every call tostd.Io.pollin the Zig repository is doing right now---but I think other use cases whereoperatewould be preferable toasync/concurrentare pretty damn rare. (Of course, if someone has a counterexample where they thinkoperateis clearly preferable for something else too, do bring that up! A counterexample might make me rethink my conclusions here).Having pondered this a little, my current feeling is that the
operateAPI sadly doesn't really fit. It feels like it's trying to bolt on toIoa completely different design for asynchronous operations, and tries to be useful for several things at once, therefore ending up kind of mediocre at them all. I believe that a small, focusedpollAPI (vaguely akin to the old one) would probably be a neater and simpler addition to the interface, which handles the key use case of child processes just as well; reflects the primitives actually available on OSes so that implementations don't have to do anything too complicated; and avoids muddying the waters wrt how you're "supposed" to do certain stuff asynchronously.I'm likely being naive as someone who's never used the current poller directly, but what benefit does this bring that wouldn't be better solved by making any higher level "poller" interface just use
io.concurrent, and then working down from there to support other use-cases: to meet a single-threaded requirement, caller can useIo.Evented, and for platforms that don't have a workingIo.Evented, implement possibly-somewhat-limitedIo.Eventedbackends for Windows and posixypoll(2)that suffice at least for this use-case, etc?35ec7b4da8f6b28ea244I think there might be two classes of objections here: performance and programming model.
For performance, I don't know an example, but that has to be something with hight natural concurrent
"width" with relatively few syscalls per unit of concurrency, so perhaps concurrent
du?For programming model, my central example would be compaction code (compaction.zig). Compaction is similar to merge,
where you turn sorted A and sorted B into sorted combined union C, except that all of A, B, and C
are on disk, and chunked. So the code here is a loop that reads chunk A, chunk B, merges them
in-memory, and writes new chunk C, with complications:
first: running out of chunk A, chunk B, or in-progress chunk C.
from C might be in flight, if in-memory merge is faster than chunk write latency.
for IO.
consumed faster.
and resume later.
This adds up to a ridiculous 2k lines choreographic dance around a 10-line hot loop that actually
does all the real work.
And it does seem to me that writing that in the explicit state machine style "I've read/merged/wrote
a chunk, what should I do next, given global constraints?" is the least bad approach. Filing each
individual read as a separate
asyncand than updating the state under mutex feels horrible. Havinga central "dispatch" async function with a mailbox where completions are posted is better, but feels
like an extra abstraction overhead over raw concurrent operations.
operatewon't help there though, because each individual "read_chunk" operation isn't a singleread syscall, but rather a
readAllloop.Which I guess is another issue with
operate--- not only its a separate way to expressconcurrency, it also is not composable, and works only for operations that IO deems "primitive". Hm,
I wonder if we can actually flip this around? Instead of
operationsbeeing structs, we couldsubmit arbitrary functions, and then IO is allowed to optimize certain operations? E.g.,
single_threaded could document that, if all ops are reads and writes, it goes via epoll without
spending concurrency budget. Not a sericous suggestion :)
Thank you, both of you, for taking a look!
Please have a look at the commit I just pushed. I simplified the interface and implementation to eliminate the
n_waitandtimeoutparameters. Timeout can maybe be brought back in the future but it's a separate concern.This is the main thing I addressed with the new commit. The
std.Io.Threadedimplementation based on poll() does up to 1 poll() and then always returns. With this API definition, completion-based implementations such as IoUring can send the operations to the event loop like normal and wait on them like normal, returning after all have completed. This is a valid definition of "nonblocking = true" in the operation (i.e. it does not block other operations).I'm not concerned about operations.len being very large. Applications suffering from this problem should be solved by using a more appropriate Io implementation. Meanwhile, if you're stuck with
std.Io.Threaded(i.e.poll), this batching interface is going to be strictly better than doing these operations in a loop. Much, much better, in fact, because it will prevent I/O operations from unnecessarily blocking other ones. Also the implementation has a fixed buffer for the poll set, so it's O(1) technically ;)@blblack - the problem statement is this:
In other words, if you use
io.concurrent()in single-threaded builds usingstd.Io.Threaded, you receiveerror.ConcurrencyUnavailable. Therefore, if users update their Zig code from using poll() to usingstd.Iounder these conditions, their software will now fail, when it worked perfectly fine before.I have to strong disagree with you there. If you're willing to take
error.ConcurrencyUnavailableinto the error set, then this is what you can write:This is sooo much nicer. The only reason to suffer through the other way is to avoid possibility of failure via
error.ConcurrencyUnavailable. Or, avoiding the tough question of, "after upgrading to Zig 0.16.0, why does my program spawn an extra thread now when it didn't before?"f6b28ea2445cd0c75a895cd0c75a89f5ed2d2d14d93db4c387078a19cf31Thanks for calling me out on this one!
Yeah, I like the new version, don't see any footguns, it solves the
read2use-case, and it feels like it might be useful more generally.078a19cf31139019739d139019739d0b4ad5b534std.Io: proof-of-concept "operations" API, satisfying the "poll" use caseto std.Io: introduce batching and operations API, satisfying the "poll" use case0b4ad5b5343b71c697abI was thinking about the approach taken here for a few days now. But is this approach really a good idea?
Polling is at its core a philosophy of a readiness based API, which maps quite badly to a completion based API (which not all operating systems have; same goes goes the other way around).
Let's take a step back and look at what actual uses across applications try to solve with polling:
All of that on a single thread.
Ok, one could technically say this about most single threaded programs, but I hope that people understand what I mean here.
In case of the second case, people practically build an ad-hoc event loop around it. Looking at what's in 0.15.2, that's an event loop. So if something special needs to be done, why not just use a proper event loop? Sure,
std.Io.Eventedisn't ready yet, but that won't stay the case long term. So I don't think that this should tackle the second problem and defer to an actual event loop. Especially because I don't think that one could properly solve this without the users passing in closures to the API ifIo.asyncand the like aren't wanted. And with the fact that closure aren't a thing in Zig, users would need to define their own or adapt the interface wanted here for it. Both aren't really nice from a usability standpoint.But the first use case could be solved quite easily (and is also what the
collectOutputfunction of the process API is supposed to do). It's pretty much always streaming some amount of data in parallel and Zig mostly already has the necessary means to define that.Here an example of how that could look like: A function like
fn streamMultiple(io: std.Io, links: []Link) ?usizewithIt stops when either an error occurred, in which case it returns the index of the failed link, or until every link is finished.
This would make it possible for each implementation to implement this in whatever way they think is the most performant while still being simple for the user.
But the MultiReader here looks kinda over complicated and overengineered and not something I would like to use (I would probably break out to
switch (builtin.target.os.tag)instead).I don't see how your example code addresses this problem:
or if you are suggesting to regress this use case, then I don't understand what purpose your example code serves?
It depends on what the user did in their
poll()event loop.If it's simply about getting bytes from a to b like I said in 1., it would be about as simple as with
std.process.Child.collectOutput, which I guess would be implemented something like this:On the other hand if they do something more complicated in the event loop, then they should use an event loop instead of using an ad-hoc one like it's often done.
Also, while writing this, I noticed that one could easily plug in giving stdin data (in which case the API would receive an
*std.Io.Readeras an additional parameter and link that up in the links array).It looks like you're describing a new VTable function that does not actually prevent
error.ConcurrencyUnavailable(how would it do that if it's based on streams), which is strictly worse than doing this diff, which requires no changes to the VTable. I don't mean to be rude, but if you want to be taken seriously I suggest making a working proof of concept for your idea.Ok, I just pushed two commits to my fork on codeberg (using my master branch for work).
ed632a022eb568af80b9cfe87540872af233afa6 introduces it. I only implemented it for posix and only applied the function to usage in child processes and also haven't applied it to the build system (or anywhere else, really).
But it's enough to build-exe for example this including with
-fsingle-threaded: da0fe722152b3c0bf9610d0061a71e97f6b6d1c6But I guess that's enough as a proof of concept.
Thanks, taking a look. I see that you changed it from
std.Io.Readertostd.Io.File.Readerso that you could access theFilein there. Then, there's no point in making Io aware of the streaming API, since it can be built above the VTable on top of the File based API.Not really, my idea is that the Io implementation can decide on HOW to reach the goal of moving the bytes around.
In case of a blocking IO implementation like Threaded on POSIX, that would be poll (or something else if an implementation wants to do that). In case of Windows, that would be an IO completion port (I think?) since I am not sure how else you would do that on Windows without too much overhead.
In case of a non-blocking implementation it would "just" plug into whatever event loop already exists (e.g. io_uring, IOCP, kqueue etc.).
Basically whatever would be most efficient on the platform while staying in the constraints of the overall implementation.
I'm sorry, I'm reading your code, and your prose, and I'm really trying to understand the point that you're making, but it is escaping me.
What I am trying to say is this: When it comes to single threaded reading from multiple things (files, sockets etc.), different operating systems follow different philosophies and paradigms.
But you can always build an event loop around that. That's what
std.Ioand especiallystd.Io.Eventedtry to do.But sometimes you don't want the overhead of an event loop encompassing your entire application or you use a different
std.Ioimplementation. That use case is what this PR (and related issue) is about.This use case can be divided into two subcategories:
std.process.Child.collectOutput.What I am saying is that this PR should only tackle subcategory (1), but not subcategory (2). (And from reading how MultiReader works, I think only tackles (1) too, although the Batch and Operation types seem to try to implement a way of doing an event loop, too.)
In case of (2), people build in practise a small ad-hoc event loop. So instead they should be directed towards an actual event loop implementation.
The code I wrote only tackles subcategory (1) because it's a necessary use case, without being too complex.
The reason why I propose to do this below the interface level instead of on top of it, is because (imo) this can be tackled a lot easier and efficiently by each implementation since they can take better advantage of the platform's abilities and constraints they want to work under.
The reason for why I started to chime in was because I think the currently proposed way of doing things with especially Batch and Operation is overly complicated for what it's trying to achieve. And I used my (incomplete) example here as a way to describe how this could look like instead.
In case that still hasn't cleared that up, you can keep asking what I mean and I can try explaining it differently again.
3b71c697ab33cfa2ef3eThank you for explaining it again. I think I understand the argument you're aiming to make, and I'm disagreeing on which code provides the simpler primitives to satisfy use case (1). Use case (2) is handled by futures API (
io.async()andio.concurrent()).I see the code in this branch as simpler because existing functionality is moved into operations. Batch and operate functions are added to the VTable, but in exchange, many functions are removed. Overall, the number of functions in the VTable decreases by a lot, while giving timeouts and batching capabilities consistently to most I/O operations. Meanwhile, high level APIs do not change.
By comparison this
streamMultiplefunction you proposed is brand new API. It's extra stuff on top of what's already there. It introduces unnecessary dependencies intostd.Ioonstd.Io.File.Readeras well asstd.Io.Writer. The tagged union StreamType is in an awkward position between being clumsy but lacking power. For instance, thisstreamMultiplecould be implemented on top of the Batch API in this branch. But the Batch API could not be implemented on top ofstreamMultiple.I do appreciate your input and patience while walking me through your perspective. At this point I think I am satisfied to move forward with the code in this branch.
33cfa2ef3e283d0c380d283d0c380dd04aeff053d04aeff05389050269768905026976dfd53c54b270d020edb1b3a007e29eb3a007e29e687ba00f7c687ba00f7c4c9d22bcb14c9d22bcb14f0754b42e9605d4450d7211bebbb9033968c98c9b92d122f49b92d122f40a5475e2f8e0514b8a57ae0a3c8635ae0a3c863505c071405d05c071405d5c735fff0e5c735fff0e203d75f792203d75f79232d91ab3fe32d91ab3fe546535c48f546535c48f9f6152ae939f6152ae939646801bedAlso closes https://github.com/ziglang/zig/issues/20952 and https://github.com/ziglang/zig/issues/22709 (
collectOutput()has been removed in this PR)K4 referenced this pull request2026-10-28 23:25:59 +01:00