Repository navigation
IO.poll: run an act until it answers or would wait - #1172
nicolas-abril wants to merge 13 commits into
Conversation
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]>
|
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:
|
…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]>
|
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:
One caveat for the tracer: 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. |
|
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
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
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):
A loop of plain #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): Linux, your open box. On Linux x86-64, these print their lines on the check, interpreted, JS and C lanes:
Also, #1162 stays open, as you asked. If #1172 lands, it has nothing left to do. The writer:
|
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]>
|
@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: Cost. You were right that it was too high, so I went after it (e1e838d):
1M loops on an M-series Mac, median of 3:
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 Interleaving. With that shortcut, the poller now goes on before a partner it woke, as Loops.
Two other notes:
#1122 still applies to deadlines above 0, as you measured. Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself. |
"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]>
|
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 Confirmed by running1. A timed channel poll's deadline timer outlives its poll (C: memory fault / garbage value)When 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: 2On C it prints Replace the plain recv with the drain- new 2. JS: the same stale timer matchens continuations twiceOn JS the deadline finds its waiter wi
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 3. C:
|
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]>
|
@aldeni @LucasGois1 A heads-up: the API changed (df031d6..c0161bf), and your cases got simpler with it. 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
The trade-offs: a pending operation is re-issued rather than resumed, and a cancelled send drops its value, as
On cost, the For effect authors, 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]>
|
@Lorenzobattistela Thank you for this review. The repros made each problem easy to pin down. Your review was written against the
The smaller items:
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:
The full suite still answers as on main on both lanes. Yielding on Note: this reply was written by an AI at my request. If anything here is wrong, reply and I will review it myself. |
…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]>
|
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:
An HTTP server whose idle, head and body deadlines go through Cost. 1M operations, median of 5, interleaved (the 06fd74c column is from my earlier comment, same machine):
A poll costs about 50 ns more than a On JS, a program that never polls pays about 20 ns per request. Take a loop of 1M plain
A cancel inside
Both hold on all three lanes (file below, for ae09226). The If that's the intended trade-off, the A cancel read as a close:
|
|
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 |
Base has one non-blocking API per type (
TCP.poll,UDP.poll, and #1162'sChan.try_send/try_recv); this is one mechanism for every effect.API
IO.poll(ms, act)runsact, but any effect inactthat would wait more thanmsbefore it starts is cancelled instead. It answers at once without running, andactgoes on with that answer:False(its value dropped), a receiveNone;(socket, Fail{ECANCELED}), so the socket comes back to be closed.IO.pollanswersReady{x}ifactansweredxwith nothing cancelled, elseLate{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
actwaits no longer than the enclosing one.Runs to its end, past
ms: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.pollandUDP.pollare now Bend definitions overIO.poll, with the same behavior, sharingSocket.polled. Their effect files are gone.An earlier version held the waiting effect in a
Wait{rest}withIO.resume/IO.cancel(df031d6 replaced it). The cost of cancelling on the spot:try_senddoes.How
(k, until, late, own).untilis clipped to the enclosing frame's when that one is earlier, andownis 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.Emitcontinuation, on both lanes, so theEmitthat ends it pops its frame.IO_IN/IO_OUTin C or{ fd: "in" | "out" }in JS: its handle first,(handle, Result)back.select, asio_waitdoes.io_wait'speek).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.comp.tsis 63987 / 64000 on the branch, and 63958 / 64000 merged with current main. The rest iseffs/io_poll.candeffs/io_poll.js, plus a waiter's timer inchan.c/chan.js.Cost
1M loops on an M-series Mac, median of 7, interleaved:
Chan.send+Chan.recv, unpolledIO.poll(0, _)that answersLateIO.pollrequest itself (one more trip through the evaluator than atry_*), a frame push/pop, and theReady/Latebox.try_*, on loops that do nothing but the channel: about 1.5–1.8× on C and 1.4–1.5× on JS.IO.pollrun as on main.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.bendandio_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_yieldandio_poll_nestedcome from @Lorenzobattistela's review, and each fails on the head before f605c67. The sleeping sender, the tie andio_poll_ordercome from a later code review; each fails on the head before ae09226 (io_poll_orderon JS).Existing tests: the full suite answers as on main on both lanes,
tcp_poll,udp_pollandtcp_recv_max_zeroincluded.Memory (C): 1M polls stay at 1 MB. 300k early-answered timed polls: 1 MB (75 MB before f605c67).
tscis clean, andgates/repo.tspasses 49/49.Open
IO_IN/IO_OUT,{ fd }) against the def's type.GUIDE.mddoesn't mentionIO.poll. The guide is at 7968 / 8000 ttok.io_poll_canceltakes a request apart the wayio_execdoes, as a second copy of that logic. A shared helper would cost 55 ttok incomp.ts, which has no room for it.🤖 Generated with Claude Code