Repository navigation
Every channel and socket wait has a try_ twin with a limit ms, answering Poll - #1259
Conversation
|
A review turned up some correctness problems. Each one below has a reproduction on both the C and JS lanes, and none of them is caught by the new tests.
When a try_ waiter is woken before its deadline, its timer is only disarmed, so it stays in io_park (C) or io.waits (JS) for the full ms. That breaks two things:
This came in with 8c151b9. At 311881b the timer was unlinked on wake, and the same programs ran at blocking speed. A park entry that can be cancelled with an O(1) unlink would fix both problems. It would also stop overloading the waiter's made field as both the timer pointer and the "is try_" flag.
On C, chan_late removes the timed-out waiter inside io_wait itself. On JS, the waiter's io_wake only joins the run queue, so a fiber already queued ahead of it still finds the expired waiter in row.wait and hands it Ready. Take a capacity-0 channel. Fiber S does IO.sleep(20) then Chan.send(c, 7). The main fiber does IO.sleep(0), then Chan.try_recv(c, 20), then a Chan.recv if it got Wait. C prints A: wait / A: then got 7 / S: sent. JS prints S: sent / A: ready got 7, on every run. So JS delivers to a waiter whose deadline already passed, which contradicts the Poll docs. Any test that hits this ordering passes on one lane and fails on the other.
Building only the branch that is actually returned fixes all three, which is what io_res did on main.
base.bend now says a max of 0 "fails with EINVAL, as in every receive below", but the UDP effects never check for it:
The f[1] == 0 guard in tcp_recv_start can be copied over.
echo_step now takes Result<…, Maybe>, but the laws still pass Done{SCon{c, t}} and Done{""}. bend demos/io_tcp_echos/PROOF.bend --check-only fails with expected: Maybe<&1, String> / observed: String. Changing them to Done{Some{SCon{c, t}}} and Done{None{}} restores main's result. The (an empty recv) comment at line 12 is also out of date. No gate checks demos, so CI won't catch this. Non-blocking
|
|
The design covers everything #1162 was for, and more (the Tests. On the check, interpreted, JS and C lanes, these print their Cost. 1M operations, 5 runs each, f2cc47c against this head:
The step that does not wait costs what #1162's did, and the blocking path pays about 3% on C and 0–4% on JS, close to the spread between runs. The review's points on Linux.
Fit. The shapes match what a networked program needs: a receive with a deadline is |
…s in the pass that finds it, and a UDP receive of max 0 fails with EINVAL From Lorenzo's review of bendlang#1259: - io_park links both ways, so chan_wake cuts and frees a try_ waiter's timer in O(1) (io_park_cut); JS splices it from the waits. A dead timer no longer hides a deadlock for its whole ms, and a try_recv per message runs at blocking speed (1M messages: JS 12.05 s, 1.3 GB -> 0.31 s, 84 MB; C 55 MB -> 1 MB). made is only the waiter's timer, 0 if not try_. - JS io_wait calls a due wait's more at once, as C's io_wait calls pack, so a try_ deadline that passes in the same pass as an earlier timer withdraws its waiter before a fiber ahead of it in the run queue can hand it Ready. io_wake goes. - UDP.recv_from and try_recv_from fail with EINVAL for a max of 0, as base.bend says every receive does; recv_from parks itself, like try_recv_from, instead of waiting for a readable socket first. - The echo demo's laws pass Done{Some{..}} and Done{None{}}, so PROOF.bend checks again. - io_err builds the (code, message) pair once; JS io_fail takes the rest a failed send hands back. udp_send_to_end answers a NUL host with EINVAL instead of a "-" host. chan_wait builds Wait{rest} once per lane. New tests: chan_try_deadlock, chan_try_late and udp_recv_max_zero, which fail (time out, or print the other lane's order) on 987d60d. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Thanks for the review. Pushed fbe3861 and 111e1ef; each item has a test that fails on 987d60d.
Non-blocking:
Note: this comment was written by an AI after it fixed the PR for me. If anything here is wrong, reply and I will review it myself. |
…s in the pass that finds it, and a UDP receive of max 0 fails with EINVAL From Lorenzo's review of bendlang#1259: - io_park links both ways, so chan_wake cuts and frees a try_ waiter's timer in O(1) (io_park_cut); JS splices it from the waits. A dead timer no longer hides a deadlock for its whole ms, and a try_recv per message runs at blocking speed (1M messages: JS 12.05 s, 1.3 GB -> 0.31 s, 84 MB; C 55 MB -> 1 MB). made is only the waiter's timer, 0 if not try_. - JS io_wait calls a due wait's more at once, as C's io_wait calls pack, so a try_ deadline that passes in the same pass as an earlier timer withdraws its waiter before a fiber ahead of it in the run queue can hand it Ready. io_wake goes. - UDP.recv_from and try_recv_from fail with EINVAL for a max of 0, as base.bend says every receive does; recv_from parks itself, like try_recv_from, instead of waiting for a readable socket first. - The echo demo's laws pass Done{Some{..}} and Done{None{}}, so PROOF.bend checks again. - io_err builds the (code, message) pair once; JS io_fail takes the rest a failed send hands back. udp_send_to_end answers a NUL host with EINVAL instead of a "-" host. chan_wait builds Wait{rest} once per lane. New tests: chan_try_deadlock, chan_try_late and udp_recv_max_zero, which fail (time out, or print the other lane's order) on 987d60d. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ing Poll: Ready{what the blocking twin answers} or Wait{what did not happen}
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…iting JS send builds its rest only then, the bytes twins have a test, and the guide stays as on main Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…d each new comment one line Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…again and io_poll_end in C, io_until, io_late and io_ready in JS Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s in the pass that finds it, and a UDP receive of max 0 fails with EINVAL From Lorenzo's review of bendlang#1259: - io_park links both ways, so chan_wake cuts and frees a try_ waiter's timer in O(1) (io_park_cut); JS splices it from the waits. A dead timer no longer hides a deadlock for its whole ms, and a try_recv per message runs at blocking speed (1M messages: JS 12.05 s, 1.3 GB -> 0.31 s, 84 MB; C 55 MB -> 1 MB). made is only the waiter's timer, 0 if not try_. - JS io_wait calls a due wait's more at once, as C's io_wait calls pack, so a try_ deadline that passes in the same pass as an earlier timer withdraws its waiter before a fiber ahead of it in the run queue can hand it Ready. io_wake goes. - UDP.recv_from and try_recv_from fail with EINVAL for a max of 0, as base.bend says every receive does; recv_from parks itself, like try_recv_from, instead of waiting for a readable socket first. - The echo demo's laws pass Done{Some{..}} and Done{None{}}, so PROOF.bend checks again. - io_err builds the (code, message) pair once; JS io_fail takes the rest a failed send hands back. udp_send_to_end answers a NUL host with EINVAL instead of a "-" host. chan_wait builds Wait{rest} once per lane. New tests: chan_try_deadlock, chan_try_late and udp_recv_max_zero, which fail (time out, or print the other lane's order) on 987d60d. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…NVAL through its one end
udp_send_to_end cost 58 ttok more than blanking the host, which
io_sys_addr then refuses as it refuses any malformed one. udp_bad_address
probes "127.0.0.1\u{0}x": without the check, C reads the quad before the
NUL and sends.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…-verdict (#59) * fix(intrusive list): rename Root's Ready to RootReady, for Bend 2.0.36+ Bend 2.0.36 added `type Poll ... Ready{value} Wait{rest}` to Base (bendlang/bend#1259), and Base's names are global, so `type Root is Data: Ready{} Waiting{}` fails with "duplicate declaration: Ready" on 2.0.36 and 2.0.37. That stops the intrusive list's proof, its example and every root that imports them (laws_containers.bend, proofs/PROOF.bend). array_adapter.bend is regenerated from array_adapter.src with tools/generators/mac.py (which reproduces the committed file byte for byte before the change). Co-Authored-By: Claude Opus 5.5 <[email protected]> * proofs: concrete calls of the generic laws --verdict needs a model for From bendlang/bend#1580 (on bend main, after 2.0.37), --verdict takes a ~ constant's model from a call of its def at concrete ~ arguments, and no longer searches for one. Nothing called prepend_valid, remove_head_valid, optional_suffix, remove_nonhead_valid, prepend_preserves, remove_head_preserves or remove_nonhead_preserves (at ~reflex) or set_post (at ~hp) at any, so the kernel never saw them. One call each, at Bool (with a local bool_eq) and at the empty map with m2 = set(m, key, x), gives them models; the laws still hold for every argument. On 2.0.37 these calls check and change nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(proofs): preserve verdict instances in edits source template --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Giulio Rebuffo <[email protected]>
Context
Base has one non-blocking API per handle type, each with its own shape:
TCP.poll(sock, max, ms)is a receive with a deadline.UDP.poll(sock, max)is a receive that never waits.Chan.try_sendandChan.try_recv.This PR gives every channel and socket operation that can wait one shape: the plain name blocks, and a
try_twin takes a limitmsand never waits longer. It supersedesTCP.poll,UDP.polland #1162. Closes #1147.Change
One new type. A
try_answersReady{x}, wherexis exactly what its blocking twin answers, orWait{rest}oncemspasses (0: at once), whererestis what did not happen:A blocking call never answers
Wait, so its type doesn't mention it. Atry_caller matches both layers at once:case Ready{Done{Some{data}}},case Wait{rest}.Blocking answers use
MaybeandResult. Only operations that can end get aMaybe, and a failed send hands back what wasn't sent:try_Chan.send(c, v)Result<A, Unit>(wasBool)Chan.try_send(c, v, ms):Poll<Result<A, Unit>, A>Chan.recv(c)Maybe<A>(unchanged)Chan.try_recv(c, ms):Poll<Maybe<A>, Unit>TCP.recv(s, max)Result<Err, Maybe<String>>(was""at the end)TCP.try_recv(s, max, ms)TCP.recv_bytes(s, max)Result<Err, Maybe<List<U32>>>TCP.try_recv_bytes(s, max, ms)TCP.send(s, data)Result<Err & String, Unit>TCP.try_send(s, data, ms):Wait{rest}after a partial writeTCP.send_bytes(s, data)Result<Err & List<U32>, Unit>TCP.try_send_bytes(s, data, ms)TCP.accept(l)Result<Err, Socket>(unchanged)TCP.try_accept(l, ms)UDP.recv_from(s, max)Result<Err, Addr & String>(unchanged)UDP.try_recv_from(s, max, ms)UDP.send_to(s, h, p, data)Result<Err & String, Unit>UDP.try_send_to(s, h, p, data, ms)Every outcome of an operation lands on a distinct path:
Chan.send:Fail{v}means closed.try_send'sWait{v}means full. Both handvback.TCP.recv:Done{None};Fail;maxof 0 staysFail{EINVAL};Somenever holds"".UDP.recv_from: it has noMaybe, because UDP has no end and an empty datagram is valid data. Amaxof 0 fails withEINVALat once, as in TCP, instead of taking a waiting datagram and dropping it.restis what the kernel didn't take.Runtime.
TCP.pollused it). Every socket effect now carries its deadline inw->time, with 0 for the blocking twin, and answersWaitonce it passes. As on main since comp.ts back under its cap by removing mechanisms at their root: a global File, one way to read a shared cell, and effects that park themselves #1281,TCP.acceptandUDP.recv_fromwait for their socket to be readable before their first try, so a backlog can't starve the timers; theirtry_twins wait the same way with their deadline, answering when the socket is ready or the deadline passes. Every effect registers withio_eff(cid, run).try_waiter parks a small timer whose expiry takes it off the channel. Whichever comes first removes the other: the timer cuts the waiter from the channel, or a wake cuts the timer from the park list in O(1) (io_park_cut;io_parknow links both ways). JS splices the timer from its waits list. A woken waiter leaves nothing parked, so deadlock detection and throughput are as for a blocking wait.io_waitnow runs a due wait at once, as C's runspack, instead of queueing it behind runnable fibers. So when atry_deadline and an earlier timer fall due in the same pass, both lanes withdraw the waiter before anything can hand itReady.Polleverywhere:PolljoinsRUNTIME_ADTS, so every effect can nameReadyandWait.comp.tsholds the deadline rule once per lane. In C,io_until(ms)gives a deadline,io_again(w)decides whether to park again, andio_poll_end(e, w, rest, r)answersWait{rest},Ready{r}orr. JS hasio_until,io_lateandio_ready. C'sio_errbuilds the(code, message)pair thatio_failboxes and that a failed send pairs with its rest; JS'sio_fail(code, ...rest)does both.A timed-out
try_withdraws its own wait, whichIO.withincan't do (its loser still runs). That means a receive with a deadline never swallows a later value.Breaking
Chan.sendanswersResultinstead ofBool.TCP.recv/recv_bytesanswerNone{}at the peer's end instead of""/[].(error, rest)instead oferror.UDP.recv_fromwith amaxof 0 fails withEINVALinstead of answering an empty datagram.TCP.pollandUDP.pollare gone. Their replacements areTCP.try_recv(s, max, ms)andUDP.try_recv_from(s, max, 0).parse_freshrejects a new constructor whose bare name is already taken, and Base's constructors are stored under bare names. SoReadyandWaitare now off limits in the main file, in imported modules and in hub packages.tests/reg/show_shared_layoutdeclared its ownReady(as an arbitrary name), so it now usesFinal.Hub packages that use these need updating.
Known limits
String. When the kernel takes part of a multi-byte character, theStringrestdecodes the cut as U+FFFD, so resending it isn't byte-exact.TCP.send_bytesis.Stringholding a surrogate comes back from a failed C send as U+FFFDs, since its rest is decoded from the UTF-8 it was sent as. JS refuses such aStringbefore it gets that far; Char.from_u32 of a surrogate fails in JS and the interpreter but prints invalid UTF-8 natively #1080 tracks C accepting it.IO.withinstill doesn't cancel its loser.try_readonly means something on pipes, FIFOs and stdin; a follow-up can giveFile.readthe sameMaybeend.Checks
After rebasing onto main d052d4f (with #1281's effect API and #1340's fetch loop), on an Apple M4:
io_eff, JS keeps no need functions, accept and receive wait for readability first as on main (theirtry_twins with the deadline), and JSio_failkeeps main'sio_strerrorfallback. Otherwise every file carries the same changes as before the rebase. Main'sudp_backlog_timertest now matchesUDP.send_to's failure with its rest. fix(demo): read fragmented HTTP responses until EOF #1340's read-until-EOF loop indemos/io_http_fetchand its copy intests/io/http_fetch_eofend onDone{None}and match a failed send's rest.udp_backlog_timer, now fixed.gates/test.ts's shard script on this Mac): 1,574 of 1,576 pass, the twogfxtests failing as on main.repo50/50,test1,576/1,576,perf121/124 (GPU cells around the 1.15x line, as on main).comp.tsis 63,464 ttok against main's 63,132.Before the rebase:
On an Apple M-series Mac, against
main(f2cc47c):tests/onmain, and all 1,539 on the branch, ran on every lane. Each went through the interpreter, and every program that builds also ran in C and JS.#|lines. The other two aregfx/clicksandgfx/window, which expect no display (this Mac has one) and fail identically onmain.main, and every one is intended.chan_try,tcp_try,tcp_try_bytesandudp_trycover eachtry_withms0, with a deadline that passes, and with a wake before the deadline. They also check that a timed-out receive doesn't swallow a later value, thattry_sendandtry_send_bytesanswerWait{rest}against a full kernel buffer, and that closed channels and failed sends hand their value back (a rejected byte list comes back whole).tcp_pollandudp_pollbecametcp_try_recvandudp_try_recv_from. They check the same things through the new functions.chan_close_send:TrueFalsebecomesDoneFail2.tcp_bytes: the rejected list comes back,22, kept 1 256.tcp_recv_max_zero:poll:becomestry_recv:.tcp_short_recv:end:becomesended.udp_bad_address: each failure prints the datagram it hands back.show_shared_layout:ReadybecomesFinal.io_tcp_echos,io_http_server,io_http_fetchandio_rollback_netcodebuild in C and JS. Run by hand, they behave as before: the echo server echoes,curlgets the page, the fetch prints a response, and two netcode bots stay in sync.comp.tsgoes from 63,502 to 63,834 ttok (63,868 merged with currentmain); the review fixes below add 158.PolljoinsRUNTIME_ADTS, and the deadline rule each effect shares is defined there once per lane:io_until,io_againandio_poll_endin C, andio_until,io_lateandio_readyin JS. Those helpers cost 171 ttok incomp.tsand save 594 across the effects.GUIDE.mdis unchanged: it is 32 ttok under its cap, too few to describetry_without cutting something else.bun gates/repo.tspasses (50/50).tscreports the same 12 errors as onmain, none incomp.ts.gates/test.ts's own shard script, run on this Mac (interpreter, JS and C): 1,529 of 1,531 pass, the same twogfxtests failing as onmain.chan_try_deadlock: atry_recv(c, 60000)woken by a sender, then arecvnobody answers, reports the deadlock at once (it waited out the 60 s on every lane).chan_try_late: a 10 mstry_recvand a sender's 1 ms sleep fall due in one pass, held there by a busy computation; every lane answersWait(JS and the interpreter answeredReady{7}).udp_recv_max_zero:try_recv_fromandrecv_fromwith amaxof 0 fail withEINVAL, on a quiet socket and with a datagram waiting, which a laterrecv_fromstill reads.udp_bad_addressalso sends to"127.0.0.1\u{0}x", which fails withEINVAL(without the check, C sent it).try_recv(c, 30000)per message, 1M messages: JS 12.05 s and 1.3 GB on 987d60d, 0.31 s and 84 MB now; C's peak memory 55 MB, now 1 MB.io_poll_endhad already fixed that).demos/io_tcp_echos/PROOF.bendchecks again; every demo checks as onmain.gates/_run.ts, on this branch at 111e1ef merged withmainat 57b6c15, 27.5 s):repo49/49,test1,533/1,533.perf106/117, failing the same cells asmainalone (also 106/117): PAR-CPU space on tree-matmul, mandelbrot, tree-radix, nbody and gameoflife (1.2x to 4.6x of their pins on both), and GPU times around the 1.15x line that flip between runs. Every other cell is within a few percent ofmain, and every output matches its pin.pingskipped: the site repo isn't checked out on this Mac.🤖 Generated with Claude Code