Skip to content

IO.poll: run an act until it answers or would wait - #1172

Closed
nicolas-abril wants to merge 13 commits into
mainfrom
io-poll
Closed

nicolas-abril wants to merge 13 commits into
mainfrom
io-poll

Conversation

@nicolas-abril

@nicolas-abril nicolas-abril commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Base has one non-blocking API per type (TCP.poll, UDP.poll, and #1162's Chan.try_send/try_recv); this is one mechanism for every effect.

API

type IO.Poll<-A: Type> is Type:
  Ready{value: A}
  Late{value: A}

def IO.poll(-A: Type, ms: U32, act: IO(A)) -> IO(IO.Poll<A>)

IO.poll(ms, act) runs act, but any effect in act that would wait more than ms before it starts is cancelled instead. It answers at once without running, and act goes on with that answer:

  • a channel send answers False (its value dropped), a receive None;
  • a sleep answers at once;
  • an effect on a socket answers (socket, Fail{ECANCELED}), so the socket comes back to be closed.

IO.poll answers Ready{x} if act answered x with nothing cancelled, else Late{x}.

  • Nothing is left behind. A cancelled receive took nothing, a cancelled send delivered nothing, and no waiter or timer stays on the channel. So a loop simply issues the call again next turn.

  • IO.poll(0, act) never waits and reads no clock.

  • A cancel yields to the other computations, as a wait would. Every 64 cancels also give the loop a non-blocking turn to see its timers and sockets, so a computation spinning on IO.poll(0, _) can't starve sleepers or socket readers.

  • A poll inside act waits no longer than the enclosing one.

  • Runs to its end, past ms:

    • an effect that has already started (a send half written, a connect, work on the IO threads);
    • a read the OS reported ready and then found empty;
    • an effect that declares no wait.
  • Chan.try_send and Chan.try_recv answer at once: the send and receive that do not wait, shared with Chan.send and Chan.recv #1162's cases:

    • IO.poll(0, Chan.recv(c)): Ready{Some{v}} got a value, Ready{None} closed, Late{None} nothing yet;
    • IO.poll(0, Chan.send(c, v)): Ready{True} sent, Ready{False} closed, Late{False} full.

    A receive with a timeout is IO.poll(ms, Chan.recv(c)).

  • TCP.poll and UDP.poll are now Bend definitions over IO.poll, with the same behavior, sharing Socket.polled. Their effect files are gone.

An earlier version held the waiting effect in a Wait{rest} with IO.resume/IO.cancel (df031d6 replaced it). The cost of cancelling on the spot:

How

  • Frames: each computation keeps a stack of poll frames, (k, until, late, own).
    • A nested frame's until is clipped to the enclosing frame's when that one is earlier, and own is the frame whose deadline it is. A cancel turns late every frame up to that one; on a tie, the cancel is the inner poll's own.
    • A polled act runs in place with the loop's own Emit continuation, on both lanes, so the Emit that ends it pops its frame.
    • A request whose continuation is that end answers the frame directly, whether it ran or was cancelled.
  • Cancelling before it starts: under a frame, a request is checked before it runs. It can be cancelled if it's a channel step or a sleep, or if its effect declares IO_IN/IO_OUT in C or { fd: "in" | "out" } in JS: its handle first, (handle, Result) back.
    • Readiness is checked with select, as io_wait does.
    • Past the deadline, the request is answered cancelled and the computation is requeued. Every 64 cancels, the loop gets a non-blocking turn (io_wait's peek).
  • Before the deadline:
    • a socket request waits on its fd and the clock together. If it's woken but its fd is no longer ready, it waits again until the deadline;
    • a sleep either ends in time or is cancelled at the deadline;
    • a channel step parks on its row, with a deadline timer owned by the waiter. Waking the waiter disarms the timer right away, and at the deadline the timer finds its waiter by identity.
  • User effects opt in the same way. guide/EFFECTS.md's section "A pollable effect" has the contract, the declaration on each lane, and what a wrong declaration breaks. Nothing checks a declaration against the def's type yet.
  • Size: the core has only hooks. comp.ts is 63987 / 64000 on the branch, and 63958 / 64000 merged with current main. The rest is effs/io_poll.c and effs/io_poll.js, plus a waiter's timer in chan.c/chan.js.

Cost

1M loops on an M-series Mac, median of 7, interleaved:

loop C JS
Chan.send + Chan.recv, unpolled 56 ms 300 ms
both polled with 0 ms, both ready 93 ms 414 ms
IO.poll(0, _) that answers Late 67–73 ms 372–399 ms

Checks

  • Tests, passing on the check, interpreted, JS and C lanes:

    • io_poll.bend: channels, sleep with deadlines, several effects in one act;
    • io_poll_tcp.bend: accept and receive;
    • io_poll_deadline.bend: receive in time; receive late, with the late value still there; send drained in time;
    • io_poll_cancel.bend: sockets come back from a cancel; a composite act goes on after one;
    • io_poll_drop.bend: a cancelled send is never delivered, and a cancelled receive leaves no waiter;
    • io_poll_timers.bend: an early-answered timed poll followed by a plain receive, a second timed poll, and another computation's poll;
    • io_poll_yield.bend: a 0 ms polling loop lets its sender run, including a sender that sleeps first;
    • io_poll_nested.bend: an inner poll is limited by the outer one's deadline, and a tie is the inner poll's own;
    • io_poll_order.bend: a poll runs its act in place, so both lanes interleave computations alike;
    • io_poll_try.bend and io_poll_writer.bend, by @aldeni;
    • io_poll_foreign.bend (+ .c, .js): a foreign effect written from EFFECTS.md's section.

    io_poll_timers, io_poll_yield and io_poll_nested come from @Lorenzobattistela's review, and each fails on the head before f605c67. The sleeping sender, the tie and io_poll_order come from a later code review; each fails on the head before ae09226 (io_poll_order on JS).

  • Existing tests: the full suite answers as on main on both lanes, tcp_poll, udp_poll and tcp_recv_max_zero included.

  • Memory (C): 1M polls stay at 1 MB. 300k early-answered timed polls: 1 MB (75 MB before f605c67).

  • tsc is clean, and gates/repo.ts passes 49/49.

Open

  • Linux and the GPU binaries are not re-run on this version.
  • A deadline above 0 waits on the loop's clock, so it's subject to IO.within's deadline, and every timer, waits while two computations talk over a channel #1122.
  • Nothing checks a pollable declaration (IO_IN/IO_OUT, { fd }) against the def's type.
  • GUIDE.md doesn't mention IO.poll. The guide is at 7968 / 8000 ttok.
  • Waking a channel waiter that a timed poll armed scans the park list to disarm its timer, which is O(parked items).
  • io_poll_cancel takes a request apart the way io_exec does, as a second copy of that logic. A shared helper would cost 55 ttok in comp.ts, which has no room for it.

🤖 Generated with Claude Code

IO.poll(act) answers Ready{x} if act answers x without waiting, or
Wait{rest} where it would park: a channel full or empty, a socket not
ready, a sleep. rest (IO.Rest) is act from there on, its waiting effect
not yet started: IO.resume(rest) waits as act would have,
IO.poll(IO.resume(rest)) polls it again, and IO.cancel(rest) answers the
held effect cancelled and goes on (channels only so far: a send False, a
recv None). One mechanism for every effect, where Chan.try_send and
try_recv (#1162), TCP.poll and UDP.poll are one API per type.

Each computation keeps a stack of poll frames; a park under a poll frame
is held rather than registered, and the poll answers at once. The core
only has the hooks (io_holds, io_hold, the frames on a request or run);
the rest is effs/io_poll.c and .js. Draft: a dropped rest leaks its held
request on the C lane, and cancel does not cover sockets yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
IO.poll(ms, act) holds an effect only before it starts: under a poll, a
request whose effect declares its wait and can be cancelled is checked
before it runs, and if it would wait past ms the poll answers
Wait{rest}, rest being the untouched request (and any frames above the
poll's) as terms. Dropping a rest is an ordinary drop, with nothing left
in the runtime; an effect that starts, or that declares no wait, runs to
its end. Before the deadline the request waits for its handle or the
clock, a sleep ends in time or is held, and a channel step parks on its
row with a timer that takes it back out.

IO.cancel answers a held request cancelled: a send False, a recv None, a
sleep Unit, and an effect on a handle (IO_HAND in C, an fd entry in JS)
(handle, Fail{ECANCELED}), so a socket comes back to be closed. A polled
act ends in the loop's own Emit, so IO.poll(ms, IO.resume(rest)) adds no
frame. TCP.poll and UDP.poll are now IO.poll over TCP.recv and
UDP.recv_from; their effect files go.

C: 1M polls that drop rest, and 1M re-polls of one rest, stay at 1 MB; a
1M channel ping-pong takes as long as on main on both lanes. comp.ts +159
ttok.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@LucasGois1

Copy link
Copy Markdown

I opened #1147 for a tracer that follows OpenTelemetry. Here is how its batch span processor maps onto #1172, going by the API as described here; I have not run the branch.

So it covers all three cases. Two things would make them easy to rely on:

  1. Say that IO.poll(0, act) answers at once without waiting on a timer. IO.within's deadline, and every timer, waits while two computations talk over a channel #1122 shows timers can be held back while channels are busy, and the zero-deadline poll is the hot path here: one per finished span.

  2. Pin the two properties a bounded queue depends on with tests.

    • A dropped Wait{rest} of a send never delivers its value: once the queue is drained, a receive finds nothing.
    • A dropped Wait{rest} of a receive leaves no waiter: the next send reaches the next receiver.

    Both follow from "not started", and both are what separates this from IO.within.

…hind

IO.poll's comment says IO.poll(0, act) never waits (an effect that would
wait answers Wait at once, with no timer), that a dropped rest never
sends its value nor takes one, and that an effect IO.poll cannot hold
runs to its end past ms. tests/io/io_poll_drop.bend pins the two
properties a bounded queue relies on: a send dropped on a full queue is
never delivered, and a recv dropped on an empty channel leaves no waiter,
so the next send reaches the next receiver.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Thanks, this is a very useful check against a real use case. Your three mappings match what the branch does.

Both points are in 06fd74c:

  1. IO.poll(0, act) answers at once. IO.poll's comment now says so: an effect that would wait answers Wait right away, and no timer is involved. The code does it that way on both lanes: with ms = 0 the poll answers before anything is registered, so IO.within's deadline, and every timer, waits while two computations talk over a channel #1122 can't hold it back. A deadline above 0 does wait on the loop's clock, so that case is still subject to IO.within's deadline, and every timer, waits while two computations talk over a channel #1122.
  2. The two bounded-queue properties are pinned in tests/io/io_poll_drop.bend, which passes on the check, interpreted, JS and C lanes:
    • a send polled on a full queue and dropped is never delivered: after the queue is drained, a polled receive finds nothing;
    • a receive polled on an empty channel and dropped leaves no waiter: the next send reaches the next receiver. The channel has no room, so if a dropped receive had left a waiter, the send would hand its value to it and the real receiver would never finish.

One caveat for the tracer: IO.poll only holds effects that declare their wait. For channels, sockets and sleep that's covered, but an effect it can't hold, such as TCP.connect, runs to its end past ms. The comment on IO.poll spells this out.

The design is still a draft, so the API may change before this lands.

Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself.

@aldeni

aldeni commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Yes, it covers both, and the third case #1162 was for. I ran #1162's cases against the draft (06fd74c) on Linux x86-64. Below: a case the tests leave out, what a poll costs, and numbers for the #1122 case you mention above.

#1162's cases on the draft

  • Drop when full. IO.poll(0, Chan.send(c, x)) answers Wait{rest} on a full channel, and a dropped rest never delivers (io_poll_drop, which also pins @LucasGois1's two properties). It also tells full (Wait) from closed (Ready{False}), which try_send's Bool could not.
  • The writer. It drains what is queued into one transaction, then blocks for the next value. With the draft it polls recv with 0 ms until Wait{rest}, commits, then runs IO.resume(rest). The receive that blocks is the one held in rest, so nothing is taken between the drain and the wait. The file below prints commit 1 2 3, commit 4, commit 5 6, commit, closed on the interpreted, JS and C lanes.
  • Closed vs. nothing yet. Ready{Some{x}}, Wait{rest} and Ready{None} are Chan.Poll's Got, Wait and Closed.

A case the tests leave out. In the tests, a poll never finds a partner already parked on a channel with no room: each spawns its partner after the poll. I ported the rendezvous half of #1162's chan_try.bend, and it answers as try_recv/try_send did on all three lanes:

  • poll(0, recv) takes a parked sender's value;
  • poll(0, send) hands its value to a parked receiver;
  • poll(0, send) with nobody there waits.

The only difference is the interleaving: the woken partner prints before the poller goes on. Polls with deadlines on both ends also meet, in both directions: a send polled for 200 ms with a receive polled for 200 ms or 0 ms, and the reverse. The file is below if you want it as a test.

Cost. 1M operations, Linux x86-64, 3 runs each (within 3% of each other):

1M × try_* (#1162) IO.poll(0, _) (#1172)
send + recv, both ready C 108 ms, JS 575 ms C 345 ms, JS 1690 ms
send on a full channel C 57 ms, JS 273 ms C 159 ms, JS 730 ms
recv on an empty channel C 50 ms, JS 298 ms C 157 ms, JS 730 ms

A loop of plain Chan.send and Chan.recv takes 108 ms on both branches, so a program that never polls pays nothing, as you measured. A poll costs about 100 to 120 ns more than a try_* on C, whether it answers Ready or Wait. That is small beside a span export or a commit, but about 3x on a loop whose only work is the channel.

#1122 and a deadline past 0. As you say above, a deadline past 0 is still subject to #1122. The numbers, beside #1122's pipeline (2M values over a channel): IO.poll(0, recv) answers Wait after 0 ms on C and 2 ms on JS, while IO.poll(10, recv) answers only when the pipeline ends, after 202 to 206 ms on C and 1279 ms on JS, together with the 10 ms timer and IO.within(10). So a ForceFlush with a deadline waits for whatever channel traffic runs beside it. The deadline waits in the loop like the others, so the glance in #1122 should move it too; I have not tried that on this branch.

Linux, your open box. On Linux x86-64, these print their lines on the check, interpreted, JS and C lanes:

  • io_poll, io_poll_cancel, io_poll_deadline, io_poll_drop, io_poll_tcp;
  • tcp_poll, udp_poll, tcp_recv_max_zero;
  • the channel tests, except channel_send_recv, which fails as on main.

Also, +r = rest is refused ("+r can be used many times, so its type must be Data"), so a rest cannot be resumed twice. GPU not run.

#1162 stays open, as you asked. If #1172 lands, it has nothing left to do.

The writer: commit 1 2 3, commit 4, commit 5 6, commit, closed on every lane
import Base

def producer(+c: Chan(U32)) -> IO(Unit):
  do IO<Unit>:
    Unit <- IO.sleep(20)
    Bool <- Chan.send(U32, c, 4)
    Unit <- IO.sleep(20)
    Bool <- Chan.send(U32, c, 5)
    Bool <- Chan.send(U32, c, 6)
    Unit <- IO.sleep(20)
    Chan.close(U32, c)

def writer(fuel: Nat, +c: Chan(U32), batch: String, s: IO.Step<Maybe<&1, U32>>) -> IO(Unit):
  match fuel:
    case 0n:
      IO.print("out of fuel")
    case 1n+p:
      match s:
        case Ready{Some{x}}:
          IO.bind(IO.Step<Maybe<&1, U32>>, Unit,
            IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, c)),
            writer(p, c, batch ++ " " ++ U32.show(x)))
        case Ready{None{}}:
          IO.print("commit" ++ batch ++ ", closed")
        case Wait{rest}:
          IO.bind(Unit, Unit, IO.print("commit" ++ batch), u =>
            IO.bind(Maybe<&1, U32>, Unit, IO.resume(Maybe<&1, U32>, rest),
              m => writer(p, c, "", Ready{m})))

def run(c: Chan(U32)) -> IO(Unit):
  +ch = c
  do IO<Unit>:
    Bool <- Chan.send(U32, ch, 1)
    Bool <- Chan.send(U32, ch, 2)
    Bool <- Chan.send(U32, ch, 3)
    Unit <- IO.spawn(Unit, producer(ch))
    s : IO.Step<Maybe<&1, U32>> <- IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, ch))
    writer(100n, ch, "", s)

def main() -> IO(Unit):
  IO.bind(Chan(U32), Unit, Chan.new(U32, 8), run)

#|commit 1 2 3
#|commit 4
#|commit 5 6
#|commit, closed
#1162's chan_try.bend through IO.poll(0, _), parked partners included: every lane prints its lines
# #1162's chan_try cases through IO.poll(0, _): on a channel with room for
# one, a send goes, a second one waits (full), and after the close a send
# answers False (closed, told apart from full); a recv takes the value,
# then waits, then answers None once closed. On a channel with no room, a
# sender parked on send hands its value to a polled recv, a receiver
# parked on recv takes a polled send's value, and a polled send with
# nobody waiting waits.
import Base

def step(-A: Type, s: IO.Step<A>, show: A -> String) -> String:
  match s:
    case Ready{value}:
      "ready " ++ show(value)
    case Wait{rest}:
      "wait"

def got(m: Maybe<&1, U32>) -> String:
  match m:
    case None{}:
      "none"
    case Some{value}:
      U32.show(value)

def sender(+c: Chan(U32)) -> IO(Unit):
  do IO<Unit>:
    Bool <- Chan.send(U32, c, 9)
    IO.print("sender: 9 went")

def receiver(+c: Chan(U32)) -> IO(Unit):
  do IO<Unit>:
    m : Maybe<&1, U32> <- Chan.recv(U32, c)
    IO.print("receiver: " ++ got(m))

def rendezvous(c: Chan(U32)) -> IO(U32):
  +ch = c
  do IO<U32>:
    Unit <- IO.spawn(Unit, sender(ch))
    Unit <- IO.sleep(0)
    p : IO.Step<Maybe<&1, U32>> <- IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, ch))
    Unit <- IO.print("recv from a parked sender: " ++ step(Maybe<&1, U32>, p, got))
    Unit <- IO.spawn(Unit, receiver(ch))
    Unit <- IO.sleep(0)
    a : IO.Step<Bool> <- IO.poll(Bool, 0, Chan.send(U32, ch, 7))
    b : IO.Step<Bool> <- IO.poll(Bool, 0, Chan.send(U32, ch, 8))
    Unit <- IO.print("send to a parked receiver, then to nobody: " ++ step(Bool, a, Bool.show) ++ ", " ++ step(Bool, b, Bool.show))
    return 0

def buffered(c: Chan(U32)) -> IO(U32):
  +ch = c
  do IO<U32>:
    a : IO.Step<Bool> <- IO.poll(Bool, 0, Chan.send(U32, ch, 1))
    b : IO.Step<Bool> <- IO.poll(Bool, 0, Chan.send(U32, ch, 2))
    Unit <- IO.print("send with room for one: " ++ step(Bool, a, Bool.show) ++ ", " ++ step(Bool, b, Bool.show))
    p : IO.Step<Maybe<&1, U32>> <- IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, ch))
    q : IO.Step<Maybe<&1, U32>> <- IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, ch))
    Unit <- Chan.close(U32, ch)
    r : IO.Step<Maybe<&1, U32>> <- IO.poll(Maybe<&1, U32>, 0, Chan.recv(U32, ch))
    d : IO.Step<Bool> <- IO.poll(Bool, 0, Chan.send(U32, ch, 3))
    Unit <- IO.print("recv: " ++ step(Maybe<&1, U32>, p, got) ++ ", " ++ step(Maybe<&1, U32>, q, got) ++ ", " ++ step(Maybe<&1, U32>, r, got))
    Unit <- IO.print("send once closed: " ++ step(Bool, d, Bool.show))
    IO.bind(Chan(U32), U32, Chan.new(U32, 0), rendezvous)

def main() -> IO(U32):
  IO.bind(Chan(U32), U32, Chan.new(U32, 1), buffered)

#|send with room for one: ready True, wait
#|recv: ready 1, wait, ready none
#|send once closed: ready False
#|sender: 9 went
#|recv from a parked sender: ready 9
#|receiver: 7
#|send to a parked receiver, then to nobody: ready True, wait

nicolas-abril and others added 3 commits September 29, 2026 15:44
IO.poll is the effect itself and answers Ready or Wait, with no Or and no
IO.poll.step between. io_poll_step answers io_step 1 to go on in place
(a popped frame, a hold) rather than queueing the computation again,
frames are recycled, and a polled act's last request (its continuation
the act's end, as in IO.poll(0, Chan.recv(c))) answers its frame itself,
with no Emit. On an M-series Mac, 1M loops of a send and a recv both
polled take C 90 ms (was 160), JS 350 ms (was 610), beside 50 and 230 ms
unpolled; a poll that answers Wait takes C 60 ms per 1M (was 90 to 100).

tests/io/io_poll_writer.bend and io_poll_try.bend are @aldeni's: the
writer that drains, commits and blocks on the rest, and #1162's chan_try
cases with partners already parked. The poller now goes on before a
partner it woke, as try_* did.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A poll holds a request only when its frame is the innermost. A rest
resumed inside a polled act with more of the act after it (IO.poll(ms,
IO.bind(IO.resume(rest), f))) runs to its end, as an effect IO.poll
cannot hold does; polled on its own, IO.poll(ms, IO.resume(rest)), it is
held as before. So a rest never carries frames: it is the untouched
request, with no node chain in C nor top list in JS, and resume and
cancel only push the raw frame for their continuation. io_poll.c and
io_poll.js lose 50 lines; the loops cost the same.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A loop keeps the pending action, an IO, as its state, not the Step: it
polls that action, then on Ready uses the value and polls a fresh action,
and on Wait{rest} polls IO.resume(rest) next. A loop that drains and then
blocks hands Ready's value and IO.resume(rest)'s to one handler, so it
never rebuilds a Step; io_poll_writer is now written so. The comment also
says such a loop needs a tick of its own or a blocking resume, and that
waiting for whichever of several comes first is a channel fed by one
spawned computation per source.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

@aldeni Thank you for this, it's a very thorough pass. The Linux run takes care of that open box, and both of your files are now tests, credited to you: tests/io/io_poll_try.bend and tests/io/io_poll_writer.bend.

Cost. You were right that it was too high, so I went after it (e1e838d):

  • IO.poll is now itself the effect. It answers Ready/Wait directly, without the Or and the Bend-side mapping in between.
  • The loop goes on in place after a poll ends or holds, instead of requeueing the computation.
  • Frames are recycled.
  • A polled act's last request (IO.poll(0, Chan.recv(c))) answers the poll itself, with no Emit round trip.

1M loops on an M-series Mac, median of 3:

loop before now unpolled send + recv
send + recv, both polled, both ready C 160 ms, JS 610 ms C 90 ms, JS 350 ms C 50 ms, JS 230 ms
a poll that answers Wait C 90–100 ms, JS 390–400 ms C 60 ms, JS 280 ms

That's about 20 ns per poll on C on top of the operation (it was about 55), and about 60 ns on JS (it was about 190). By your measurement a try_* costs about the same as a plain operation, so on a loop whose only work is the channel, a poll is now about 1.8× a try_* on C, down from about 3×. What's left is the IO.poll request itself, one more trip through the evaluator than a try_*, plus a frame push/pop and the Ready/Wait box. That's the price of one combinator for every effect. If a real workload needs a tight channel-only loop, a Chan.try_* fast path could still be added on top later. If you have the setup handy, a re-run of your Linux numbers on the current head would be welcome.

Interleaving. With that shortcut, the poller now goes on before a partner it woke, as try_* did. So io_poll_try has the partners report through a channel rather than print: concurrent prints came out in a different order on C than on JS.

Loops. IO.poll's comment now describes the two shapes your writer and a tick loop need:

  • keep the pending action, an IO, as the loop's state, not the Step;
  • hand Ready's value and IO.resume(rest)'s value to one handler.

io_poll_writer is rewritten that way, so it no longer rebuilds a Ready{m}. Its lines are unchanged.

Two other notes:

#1122 still applies to deadlines above 0, as you measured. IO.poll(0, _) never registers a timer, so your 0 ms numbers stand.

Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself.

@nicolas-abril
nicolas-abril marked this pull request as ready for review September 29, 2026 17:46
nicolas-abril and others added 2 commits September 29, 2026 20:12
"A pollable effect": IO.poll holds an effect only before it starts, so
an effect is either not started (held, resumed as if new, cancelled
without running, or dropped as a plain term) or started (runs to its
end). Declaring nothing is always safe. An effect may declare itself
pollable when its first wait is on the handle in its first argument, a
ready handle means it can start, and it answers (handle, Result):
IO_IN / IO_OUT (or IO_READ) with IO_HAND in C, { fd: "in" / "out" } in
JS. The section says what a wrong declaration breaks, since nothing
checks it against the def's type yet. tests/io/io_poll_foreign.bend is
such an effect, written from the section: held, cancelled with its
socket back, then ready, on every lane.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The comment above IO.poll keeps the contract (Wait{rest} not started,
resume, repoll, cancel's answers, what runs to its end) and one line on
loops; EFFECTS.md's "A pollable effect" keeps the model, the three
conditions, the declarations on each lane and what a wrong one breaks.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

I read the PR along with #1162, #1122, #1147 and the discussion here. I built small programs for the points below and ran them on both the JS and C lanes, and against main where a change from main was in question. The first two are crashes and wrong answers, so I think they need fixing before this merges.

Confirmed by running

1. A timed channel poll's deadline timer outlives its poll (C: memory fault / garbage value)

When IO.poll(ms > 0, Chan.recv/send(..)) parks, it arms a deadline timer. If the other side wakes the waiter early, the timer is never cancelled. When it fires, it looks up the row for "its" waiter by (IoWork address, serial in w->word) and holds whatever matches (io_poll.c ~L94). A later plain Chan.recv/send or IO.resume on that channel leaves w->word unchanged, so the stale timer takes that new waiter and io_poll_hold runs on a NULL or unrelated frame. It also reads the freed IoWork through t->hand.

import Base

def later(ms: U32, ch: Chan(U32), x: U32) -> IO(Bool):
  IO.bind(Unit, Bool, IO.sleep(ms), u

def got(m: Maybe<&1, U32>) -> String:
  match m:
    case None{}:
      "none"
    case Some{value}:
      U32.show(value)

def step(s: IO.Step<Maybe<&1, U32>>) -> String:
  match s:
    case Ready{value}:
      "ready " ++ got(value)
    case Wait{rest}:
      "wait"

def run(c: Chan(U32)) -> IO(U32):
  +ch = c
  do IO<U32>:
    Unit <- IO.spawn(Bool, later(10, ch, 1))
    r : IO.Step<Maybe<&1, U32>> <- IO. Chan.recv(U32, ch))
    Unit <- IO.print("poll: " ++ step(r))
    Unit <- IO.spawn(Bool, later(300,
    m : Maybe<&1, U32> <- Chan.recv(U32, ch)
    Unit <- IO.print("recv: " ++ got(m
    return 0

def main() -> IO(U32):
  IO.bind(Chan(U32), U32, Chan.new(U32

#|poll: ready 1
#|recv: 2

On C it prints poll: ready 1, then dult` at the old 100 ms deadline.

Replace the plain recv with the drain- new IO.poll doc recommends(IO.poll(0, recv), then IO.resume(rest) on Wait). The resume's continuation then gets
Wait{rest} where it expects a Maybe then: 51421697.

2. JS: the same stale timer matchens continuations twice

On JS the deadline finds its waiter wiio_poll.js ~L83). But everyIO.poll(ms, Chan.recv/send(..)) shares the one io_poll_emit continuation, so any timed poll on the row matches.

  • **Two timed polls in a row on one chts answer at 10 ms. The second isIO.poll(500, recv) with a send at 300 ms. It prints first: ready 1, first: wait, second: ready 2, then deadlocks: the first poll's frame is resumed a second time.
  • Two pollers on one channel. B does IO.poll(300, recv), then 10 ms later A does IO.poll(50, recv), and a value is sent at 120 ms. Expected A: wait, B: ready 7. It prints A: wait, A: ready 7. B never answers, and io.live is decremented twice, so the process exits early.
  • The drain-then-block shape from 1 also runs a continuation twice on JS.

Fix for 1 and 2: have the waiter own its timer instead of the timer searching the row for itswaiter afterwards. Store the timer, or an answered/expired token, in the parked waiter, and cancel it in chan_wake/chan_shut on both lanes. That fixes the C crash, the JS duplicate continuations andthe memory growth in 6 in one place. Keeping the search and only making the identity check stronger would still leave the question of how long the waiter lives. The new tests have no timed poll answeredearly and then followed by more waiting on the same channel, so a regression test for that shape would catch this.

3. C: IO.resume / IO.cancel without IO.poll doesn't compile

io_poll_back, io_poll_take and IoPoll are defined only under #ifdef CID(IO.poll), but theCID(IO.resume) and CID(IO.cancel) blocks call them.

import Base

def get(-A: Type, s: IO.Step<A>) -> IO(A):
  match s:
    case Ready{value}:
      IO.pure(A, value)
    case Wait{rest}:
      IO.resume(A, rest)

def give_up(-A: Type, s: IO.Step<A>) -> IO(A):
  match s:
    case Ready{value}:
      IO.pure(A, value)
    case Wait{rest}:
      IO.cancel(A, rest)

def main() -> IO(U32):
  do IO<U32>:
    x : U32 <- get(U32, Ready{5})
    y : U32 <- give_up(U32, Ready{6})
    return (x + y : U32)

#|11

This passes the check and runs on JS. -o prog fails in clang with call to undeclared function 'io_poll_back' and 'io_poll_take'. So a library that handles IO.Step values without polling itself can't be built to C.

4. C never yields after a poll, so 0 ms polling loops starve other computations (lanes swapped vs main)

On C, a poll that answers Ready/Wait continues the computation in place and never goes back toio_runs. JS requeues it (io_poll_run, io_resume, io_cancel).

  • Chan. A spawned Chan.send(c, 7), then a loop of IO.poll(0, Chan.recv(c)) until Ready. JS gets the value after 0 re-polls. C burns all 2M iterations of fuel and then reports deadlock.
  • TCP. A loop of TCP.poll(a, 64, 0) while a spawned computation sends "hi" on the peer socket. This branch's C never sees the data in 200k polls, while main's C sees it after 0 (the oldtcp_poll_run parked). This branch's JS sees it after 0; main's JS never did. The two lanes have swapped behavior.

5. C/macOS: io_poll_fd uses poll(), which misses FIFO EOF

The runtime's own header comment says macOS poll() misses EOF on a FIFO, which is why io_wait usesselect(). io_poll_fd uses poll() anyway. I checked it directly: on a FIFO whose writer has closed, macOS poll() returns 0 and select() returns 1.

So on C/macOS, a pollable reader on a FIFO or pipe at EOF (the fifo_eof case, written the way the new EFFECTS.md section describes) never looks ready:

  • IO.poll(0, act) answers Wait forever, though read() would return 0.
  • With ms > 0, io_wait's select() wakes it, io_poll_wake's poll() says not ready, and it is held until the deadline.

JS uses select, so the two lanes disagree.

6. C: timed channel polls keep a timer allocation until the deadline, even when answered early

Each channel poll that parks with ms > 0 callocs a timer IoWork (io_poll.c ~L187). It stays inio_park until the deadline, even after the poll answers early.

  • Memory. 300k ping-pong rounds with IO.poll(20000, Chan.recv) on buffered channels reach 78 MB max RSS, against 1.7 MB with IO.poll(0, ..).
  • Deadlock reports. A non-empty io_park also delays them: a real deadlock after such polls hangs until the last stale deadline instead of failing at once.

JS keeps the same stale entries in io.waits. The fix in 1 and 2 also fixes this.

From reading the code (not run)

  1. UDP/TCP.poll can block with no deadline (base.bend ~L426). They now check readiness and thenrun the ordinary effect. If recv/recvfrom/accept then returns EAGAIN, the effect re-parks through io_wait_on with no deadline. On Linux, select/poll can report a UDP socket readable for adatagram that recvfrom then drops (bad checksum, see select(2) BUGS). UDP.poll, documented as "recv_from without the wait", would then block until the next datagram and freeze a tick loop likedemos/io_rollback_netcode. Likewise, TCP.poll(s, n, 100) can wait past 100 ms. The deleted udp_poll returned None{} on EAGAIN, and tcp_poll kept its deadline.
  2. Stack overflow in io_cancel_run (io_poll.c ~L268). It takes the held request into a fixed Term fs[16], but io_exec uses fs[256] and arities go up to WIDE = 247. A foreignIO_OUT|IO_HAND effect with 17+ fields, declared pollable as EFFECTS.md describes, overwrites the stack when it is held and then IO.cancel'd.
  3. The max == 0 special case in TCP.poll is in the wrong layer (base.bend ~L377). It is special-cased in Bend (TCP.poll.go with U32.is_eq(max, 0)) because IO.poll checks fd readinessbefore TCP.recv's own validation runs. TCP.recv with max 0 never waits, but it is declared IO_IN|IO_HAND, so a plain IO.poll(50, TCP.recv(s, 0)) on an idle socket waits 50 ms and answersWait{rest} instead of Ready{(s, Fail{EINVAL})}. Every future wrapper would have to copy the special case. The readiness check should skip the wait when the effect would answer without waiting.
  4. Nested polls aren't limited by the outer deadline (io_poll.c ~L223). io_poll_run sets a nested poll's until from its own ms only, without clipping it to the enclosing poll frame'suntil. IO.poll(10, act), where act calls a helper doing TCP.poll(sock, n, 5000), answers after about 5 s instead of about 10 ms, so the doc's "waits up to ms" doesn't hold.

Smaller items

  • Hot-path cost (io_poll.c ~L138).
    • io_poll_waits calls chan_at(x[0]) for every holdable request, including sockets and sleeps, where x[0] is an fd or a millisecond count. The lookup belongs inside the Chan.send/recvbranches.
    • UDP.poll went from one recvfrom to readiness syscall + recvfrom + IO.poll frame + (on Wait) IO.cancel with a raw frame.
    • JS io_poll_ready allocates a new fd_set and BigInt64Array on every check; those buffers couldbe reused.
  • UDP.poll reuses TCP.poll's helpers (base.bend ~L432). Its answer goes throughTCP.poll.got/TCP.poll.none, so a change to TCP.poll's mapping (its max == 0 handling, its error shape) silently changes UDP.poll.
  • JS effect table is built lazily. io_poll_desc builds a run → poll Map on first use instead of carrying poll on the op; the emitter already has $0eff[n].need. The Map misses effects registeredafter the first IO.poll, and it is keyed by function, so two CIDs that share a run function would share one entry.

nicolas-abril and others added 3 commits September 30, 2026 00:03
An effect in act that would wait more than ms before it starts is
cancelled instead: it answers at once, unrun (a send False, a recv None,
a sleep Unit, an effect on a handle (handle, Fail{ECANCELED})), and act
goes on with that answer. IO.poll answers IO.Poll: Ready{x}, or Late{x}
once something in act was cancelled. IO.Step, IO.Rest, IO.resume and
IO.cancel go: nothing is held, so there is no rest to resume, cancel or
drop, and the core loses its request-as-item path for IO.resume. A
channel step past its deadline answers cancelled where it waits, so
chan.c is main's again. A loop re-issues its effect each turn; a
cancelled recv took nothing and a cancelled send delivered nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
IO_IN (or IO_OUT) now means: the effect waits for its handle, first, to
be readable (or writable), and a cancel answers (handle, Fail{ECANCELED}).
IO_HAND said the second half, and neither did anything without the other;
the C need now reads like JS's { fd: "in" | "out" }. TCP.accept and
UDP.recv_from, which the loop parks until readable, are IO_READ | IO_IN.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A poll with ms 0 answers a waiting request cancelled without reading the
clock, and when the cancelled request's continuation is the act's end,
the cancel answers the frame itself, as a request that runs already did,
with no Emit round trip. 1M polls that answer Late: C 81 -> 62 ms, JS
354 -> 327 ms; the Ready path is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

@aldeni @LucasGois1 A heads-up: the API changed (df031d6..c0161bf), and your cases got simpler with it. IO.poll no longer holds a waiting effect in Wait{rest}. It cancels it on the spot: unrun, answered at once, and act goes on with that answer. It answers:

type IO.Poll<-A: Type> is Type:
  Ready{value: A}   # act answered with nothing cancelled
  Late{value: A}    # something in act was cancelled; value is act's answer after that

IO.Rest, IO.resume and IO.cancel are gone. Your cases now read:

  • Drop when full: IO.poll(0, Chan.send(q, span)). Ready{True} means queued, Ready{False} means closed, Late{False} means full and the span is dropped. There's no rest to drop.
  • Drain without parking: IO.poll(0, Chan.recv(q)). Ready{Some{s}} takes one, Late{None} means nothing yet, Ready{None} means closed and drained.
  • A deadline without loss (ForceFlush): IO.poll(ms, Chan.recv(reply)). Late{None} means it timed out. The cancelled receive took nothing, so a late reply stays in the channel. There's no separate cancel call.
  • The writer: poll until Late, commit, then a plain blocking Chan.recv. The cancelled receive left no waiter, so nothing is lost in between. io_poll_writer is written that way now.
  • Sockets: a cancelled TCP.recv answers (socket, Fail{ECANCELED}), so the socket comes back without an extra call.

The trade-offs: a pending operation is re-issued rather than resumed, and a cancelled send drops its value, as try_send did. Every property pinned before still holds, and the tests are rewritten for Ready/Late:

  • a cancelled send is never delivered;
  • a cancelled receive leaves no waiter;
  • IO.poll(0, _) sets no timer, and it now reads no clock either.

On cost, the Late path got faster: 1M polls that answer Late take C 58–62 ms and JS 327 ms, against a plain send+recv loop at 58 and 276 ms. A poll that answers Ready costs about 18 ns on top of the operation on C.

For effect authors, IO_HAND is folded into IO_IN/IO_OUT, so the C flags now read like JS's { fd: "in" | "out" }. guide/EFFECTS.md has the contract.

It's still a draft. @aldeni, if you still have the Linux setup, a run of the poll tests on c0161bf would be welcome.

Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself.

- A timed channel poll's deadline timer belongs to its waiter: waking the
  waiter disarms it (chan_disarm in C, the timer entry out of the waits in
  JS), and at the deadline it finds its waiter by identity. Before, a
  timer outlived an early answer and took whatever later waiter matched:
  a memory fault on C, a continuation run twice on JS, and a timer per
  poll kept until its deadline (300k early-answered polls: 75 MB -> 1 MB).
- A cancel yields to the other computations, as a wait would, so a 0 ms
  polling loop no longer starves the one it waits for on C.
- Readiness is checked with select, as io_wait does: macOS poll() misses
  a FIFO's EOF.
- A cancelled request's fields are taken into Term fs[256], as io_exec
  does (fs[16] overflowed past arity 16).
- A nested poll's deadline is clipped to the enclosing one's, and a cancel
  turns late every frame up to the one whose deadline it was.
- chan_at runs only for channel steps, JS reuses its select buffers, and
  UDP.poll and TCP.poll share Socket.polled.

tests/io/io_poll_timers, io_poll_yield and io_poll_nested pin the timer,
the yield and the nested deadline; each fails on the previous head.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

@Lorenzobattistela Thank you for this review. The repros made each problem easy to pin down.

Your review was written against the Wait{rest} design. Since then IO.poll cancels a waiting effect on the spot and answers Ready/Late (df031d6), and IO.Rest, IO.resume and IO.cancel are gone. I ported your runnable repros to the new API: 1, 2, 4 and 10 still reproduced on the head before f605c67. Here's each point, as of f605c67:

# point status
1, 2, 6 a timed channel poll's timer outlives an early answer (C memory fault, JS continuation run twice, a timer per poll kept until its deadline) Fixed as you suggested: the waiter owns its timer. Waking the waiter disarms it right away (chan_disarm in C; in JS the timer's entry comes out of the waits), and at the deadline the timer finds its waiter by identity, with no search or serial number. Your 300k ping-pong case goes from 75 MB to 1 MB on C.
3 IO.resume/IO.cancel without IO.poll don't build Obsolete: that API is gone.
4 C never yields, so a 0 ms polling loop starves others Fixed: a cancel requeues the computation, as a wait would. C and JS now behave the same.
5 poll() misses a FIFO's EOF on macOS Fixed: readiness is checked with select, as io_wait does.
7 a spurious readiness means the effect waits past ms Documented in IO.poll's comment: a read the OS reported ready and then found empty has started, so it runs to its end. Honoring the deadline there would need each effect's cooperation.
8 Term fs[16] in the cancel path Fixed: fs[256], as in io_exec.
9 max == 0 in TCP.poll sits in Bend Kept, now with a comment on why. The readiness check can't know that an effect would fail without waiting.
10 a nested poll isn't limited by the outer deadline Fixed: a nested poll's deadline is clipped to the enclosing one's, and a cancel caused by the outer deadline turns both polls Late.

The smaller items:

  • chan_at now runs only for channel steps;
  • JS reuses its select buffers;
  • UDP.poll and TCP.poll share a Socket.polled helper instead of UDP.poll borrowing TCP.poll's.

I left the JS effect table as it is. It's built on first use, after every effect has registered at load time, and no two Base effects share a run function.

Regression tests, from your shapes. Each fails on the head before f605c67 and passes on every lane now:

  • io_poll_timers: an early-answered timed poll, then a plain receive; two timed polls in a row; and your two-pollers case (A answers Late, B gets the value).
  • io_poll_yield: a 0 ms polling loop gets its spawned sender's value on C too.
  • io_poll_nested: a 2000 ms inner poll under a 20 ms outer one answers Late at 20 ms, and the value stays in the channel.

The full suite still answers as on main on both lanes. Yielding on Late costs about 3 ns per poll on C and 25 ns on JS; the Ready path is unchanged. Everything here was run on macOS arm64. A Linux run of the current head would still be welcome.

Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself.

@nicolas-abril nicolas-abril changed the title IO.poll: run an act until it answers or would wait (draft) IO.poll: run an act until it answers or would wait Sep 29, 2026
…et, ties

- A loop of IO.poll(0, _) keeps the run queue full, and the loop sees its
  timers and sockets only once nothing can run, so a spinner starved every
  sleeper and socket reader. Every 64 cancels now give the loop a turn
  that does not block (io_wait's new peek, in C and JS).
- A socket request woken with its handle no longer ready (a client that
  connects and resets) waits again until its deadline instead of being
  cancelled early.
- A nested poll's deadline is clipped to the enclosing one's only when
  that one is earlier: on a tie the cancel is the inner poll's own, so a
  0 ms poll inside a 0 ms poll no longer turns the outer Late.
- JS runs a polled act in place, as C does (io_run takes an effect's
  $GO answer), so the lanes interleave computations alike.

io_poll_yield gains a sender that sleeps first, io_poll_nested the tie,
and io_poll_order pins the interleaving; each fails on the previous head
(io_poll_order on JS). comp.ts +14 ttok (63987 / 64000); the core comment
on io_polled moves to io_poll.c, which already had it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@aldeni

aldeni commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Linux x86-64 run of ae09226, as you asked, plus two things I found on the way.

Tests. On the check, interpreted, JS and C lanes, these print their lines:

  • the twelve io_poll* tests, io_poll_foreign included;
  • tcp_poll, udp_poll, tcp_recv_max_zero;
  • the channel tests, except channel_send_recv, which fails as on main.

An HTTP server whose idle, head and body deadlines go through TCP.poll passes its end-to-end suites built with this head. GPU not run.

Cost. 1M operations, median of 5, interleaved (the 06fd74c column is from my earlier comment, same machine):

1M × try_* (#1162) IO.poll(0, _) at 06fd74c at ae09226
send + recv, both ready C 109 ms, JS 578 ms C 345 ms, JS 1690 ms C 212 ms, JS 869 ms
send on a full channel C 58 ms, JS 278 ms C 159 ms, JS 730 ms C 114 ms, JS 511 ms
recv on an empty channel C 51 ms, JS 300 ms C 157 ms, JS 730 ms C 98 ms, JS 509 ms

A poll costs about 50 ns more than a try_* on C here (your Mac shows 18 ns), so a loop whose only work is the channel runs at about 1.9× a try_* on C and 1.5–1.8× on JS, down from about 3×.

On JS, a program that never polls pays about 20 ns per request. Take a loop of 1M plain Chan.send + Chan.recv, against the PR's merge-base (3378e62), 11 runs each:

  • JS: 568 ms → 614 ms. The cost comes in with ae09226, at the line in io_run's loop that tests every effect's answer, op = x?.$ === "$GO" ? x.op : op.kont(x). With only that line put back to op = op.kont(x) in the emitted file, the loop takes 574 ms. 17c9c3b showed the same 40 ms, and 5ca465b took them away.

  • C: 101 ms → 108 ms, but I can't pin it on anything:

    • the a->poll check in the request loop and the new field on IoWork make no difference, whether they're in or out;
    • no single other change accounts for it;
    • with -falign-functions=64 -mllvm -align-all-nofallthru-blocks=6, the two builds are 104 ms and 106 ms.

    So on C it looks like code layout, and I wouldn't count it.

A cancel inside act looks like a close to the code that sees it. A cancelled recv answers None and a cancelled send False, which are a closed channel's answers, so code written without IO.poll in mind reads them that way. For example, take a helper that forwards src to dst until src closes, then closes dst, and run it under IO.poll(0, _) with src still open:

  • ae09226: the poll answers Late, but dst is already closed;
  • 06fd74c: the same helper answers Wait, and dst stays open.

Both hold on all three lanes (file below, for ae09226). The Late reaches only the caller of IO.poll, after a step that can't be undone. On a socket, the cancel is at least an answer of its own (ECANCELED) that code can tell from a close. On a channel it can't.

If that's the intended trade-off, the IO.poll comment could say that act should be one step, or code written to be polled. Otherwise, one option is to cancel only a request whose continuation is the poll's own end, and run the rest of act as unpolled code. #1162's cases all fit that form, but you know the other uses better.

A cancel read as a close: poll: Late, then dst closed while src is open, on every lane
# A helper that forwards src to dst until src closes, then closes dst.
# Under IO.poll(0, _), a cancelled recv answers None, a closed src's
# answer, so the helper closes dst although src is still open.
import Base

def forward(fuel: Nat, +src: Chan(U32), +dst: Chan(U32), m: Maybe<&1, U32>) -> IO(Unit):
  match fuel m:
    case 0n _:
      IO.pure(Unit, Unit{})
    case 1n+p Some{value}:
      IO.bind(Bool, Unit, Chan.send(U32, dst, value), b =>
        IO.bind(Maybe<&1, U32>, Unit, Chan.recv(U32, src), n => forward(p, src, dst, n)))
    case 1n+p None{}:
      Chan.close(U32, dst)

def forward_all(+src: Chan(U32), +dst: Chan(U32)) -> IO(Unit):
  IO.bind(Maybe<&1, U32>, Unit, Chan.recv(U32, src), m => forward(10n, src, dst, m))

def shown(p: IO.Poll<Unit>) -> String:
  match p:
    case Ready{value}:
      "Ready"
    case Late{value}:
      "Late"

def got(m: Maybe<&1, U32>) -> String:
  match m:
    case None{}:
      "None (closed)"
    case Some{value}:
      U32.show(value)

def run(src: Chan(U32), dst: Chan(U32)) -> IO(Unit):
  +s = src
  +d = dst
  do IO<Unit>:
    Bool <- Chan.send(U32, s, 1)
    p : IO.Poll<Unit> <- IO.poll(Unit, 0, forward_all(s, d))
    Unit <- IO.print("poll: " ++ shown(p))
    ok : Bool <- Chan.send(U32, s, 2)
    Unit <- IO.print("src still open: " ++ Bool.show(ok))
    a : Maybe<&1, U32> <- Chan.recv(U32, d)
    b : Maybe<&1, U32> <- Chan.recv(U32, d)
    IO.print("dst: " ++ got(a) ++ ", then " ++ got(b))

def main() -> IO(Unit):
  IO.bind(Chan(U32), Unit, Chan.new(U32, 4), src =>
    IO.bind(Chan(U32), Unit, Chan.new(U32, 4), dst => run(src, dst)))

#|poll: Late
#|src still open: True
#|dst: 1, then None (closed)

@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

I havent found any good way of implementing this that isn't full of edges and pitfall for users, so i'll just go back to the original PR with Chan.try_recv/send. I'll just change it so that our IOs have more uniform API

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.

4 participants