Skip to content

TCP gets the byte twins File already has: recv_bytes, send_bytes and poll_bytes - #978

Closed
aldeni wants to merge 9 commits into
bendlang:mainfrom
aldeni:tcp-bytes
Closed

aldeni wants to merge 9 commits into
bendlang:mainfrom
aldeni:tcp-bytes

Conversation

@aldeni

@aldeni aldeni commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

What changes

TCP gets the byte twins File already has, with the same types and the
same shape:

text bytes
File.read File.read_bytes (today)
File.write File.write_bytes (today)
TCP.recv TCP.recv_bytes
TCP.send TCP.send_bytes
TCP.poll TCP.poll_bytes

List<&2, U32>, exactly as File.read_bytes and File.write_bytes
already use. No new type and no new concept. The text effects keep their
code unchanged, now under #ifdef CID(TCP.*) the way effs/file_read.c
already guards its pair, since each pair shares one effect file; the send
loop, the receive step and the poll deadline are shared rather than
copied, and the JS lane mirrors the C lane through the same pack-shaped
parameter.

TCP.poll_bytes is in the set because TCP.poll is the only receive
with a deadline: without it, a server that drops idle connections cannot
read bytes.

Why

A socket carries bytes. TCP.recv answers a String, so io_str
decodes each read as UTF-8 and writes U+FFFD over whatever it cannot
decode. Two kinds of payload do not survive that.

A body that is not text — an image, a protobuf frame, a gzip
stream — loses every byte that is not valid UTF-8. FF 00 80 reads back
as three replacement characters, and TCP.send cannot spell those bytes
either, since it encodes the String as UTF-8.

A valid character split across two reads. This is the one that bites
a correct program. "café" is 63 61 66 C3 A9; the network may deliver
C3 at the end of one read and A9 at the start of the next. Each read
decodes on its own, with no state carried over, so both halves become
U+FFFD. Measured against a Bend receiver:

sent:  63 61 66 C3 | A9          ("café", split by the network)
got code points: 99 97 102 65533
got code points: 65533

Sent whole, the same bytes give 99 97 102 233. Nothing in that program
is wrong: the split is the network's choice, it depends on load, and the
loss is silent.

File already draws this line. File.read decodes; File.read_bytes
answers, in the words of the comment in effs/file_read.c, "the bytes as
they are (0..255), one List cell each; a text reader would decode them as
UTF-8". A socket is the same seam as a file, and today only the file has
both doors.

This is also where #809 leaves things. That issue found the two lanes
decoding invalid UTF-8 differently, and the fix in 2.0.7 made the C
runtime a forward WHATWG decoder, one U+FFFD per maximal subpart, exactly
as TextDecoder does. That is the right decode — and it is precisely
why a decoding reader cannot be the only way to read a socket: now that
both lanes agree, they agree on discarding the bytes. The decoder is
correct; what is missing is the door that does not decode.

Alternatives considered

Make TCP.recv carry decoder state between calls, so a character
split across two reads is stitched back. Rejected: it would make a
recv stateful and still leave no way to read a byte that is not text,
so the binary case stays broken. It would also change what an existing
TCP.recv returns.

Preserve undecodable bytes inside the String (surrogate escapes, as
Python's surrogateescape does). Rejected: a String would stop being
a sequence of valid code points, and the split-character case still needs
the program to re-decode by hand — the work of bytes, with a type that
says text.

Ship only recv_bytes/send_bytes and leave poll_bytes out.
Rejected: TCP.poll is the only receive with a deadline, so a server
that times out idle connections would be forced back to text.

UDP.recv_from and UDP.poll have the same seam and are not touched
here, to keep this reviewable; happy to follow up with the same pair for
UDP if you want it.

Test output

tests/io/tcp_bytes_split.bend sends a character in two halves and then
three bytes that are not text, reading both back over loopback in one
program:

first read: 99 97 102 195
second read: 169
not text: 255 0 128

Checked, interpreted, JS-built and C-built on this tree
(bun bend2/main.ts <file> [--check-only | -o x.js | -o x]): all four
lanes print those three lines. The same exchange through TCP.recv
gives 99 97 102 65533 / 65533 instead, which is the defect.

tests/io/tcp_bytes_edges.bend, written in review, covers the edges:
an empty send, a byte past 255 (EINVAL, nothing sent), and
poll_bytes idle, with data and at EOF, where recv_bytes answers
[].

No regressions, on Linux x86-64 with Bun 1.3.11, on main 95317d9:

  • The 19 tcp_*, udp_*, file_* and port_bound tests, the two
    new ones included, print their expected lines on the check,
    interpreted, JS and C lanes.
  • The tests/io checkup (119 modules, one process, as gates/test.ts
    runs it) is identical to main's but for the two new tests' sections.
  • gates/repo.ts passes 46 / 46.
  • Each pair shares one effect file, and the runtime refuses an effect
    registered twice, so a program that uses both effects of a pair must
    still build: tcp_bytes_split mixes recv and recv_bytes, and a
    scratch program mixing send/send_bytes and poll/poll_bytes
    passes all four lanes.

macOS was not re-run here after the rebase onto #1042.

Duplicate check

No open issue or PR asks for byte-level socket effects. #809 (closed,
fixed in 2.0.7) is the decode-divergence issue this builds on, and #846
asks about bundled HTTP/TLS/crypto libraries, which is a different
question — this adds no library, only the byte door on the effect that
already exists. WONTFIX.txt does not cover it.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Not a criticism of your PR, but i think it would make more sense to have these functions take an array of bytes input in the future

Comment thread guide/GUIDE.md Outdated
handle (`File`, `Socket`, `Window`) is an affine, opaque value, so every effect
on one hands it back beside its result, and no program can forge or reuse one.

A file and a socket carry bytes, and each has a text reader and a byte reader:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not needed in the guide, it's pretty self explanatory by the function signatures

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Tested on macOS (arm64), merged onto 2.0.26. This looks good to me: the new effects match File.read_bytes/File.write_bytes exactly (same List<&2, U32>, same shared-.c layout, same EINVAL rule), tests/io/tcp_bytes_split passes in the check, interpreted, JS and C lanes, the existing TCP and file tests pass in all three runtime lanes, and gates/repo.ts passes.

Two requests before merge:

1. Test the paths tcp_bytes_split does not reach. Nothing exercises TCP.poll_bytes, the EINVAL path of TCP.send_bytes, or EOF. The test below covers them and passes in the interpreted, JS and C lanes on this branch: an empty send, a byte past 255 (fails with EINVAL, and a poll right after shows nothing went out), poll_bytes idle / with data / at EOF, and recv_bytes at EOF.

tests/io/tcp_bytes_edges.bend
# io (io_tcp_bytes_edges): the byte effects' edges. An empty send_bytes
# succeeds; a byte past 255 fails with EINVAL and sends nothing (the
# poll after it finds the socket empty); poll_bytes answers None{} when
# idle, Some{bytes} when data waits, and Some{[]} at EOF, as recv_bytes
# answers [] there. The listener retries upward from a base port on
# Fail, as tcp_loopback does.
import Base

law show_bytes:
  for xs: List<&2, U32>
  String

def show_bytes(xs):
  match xs:
    case Nil{}:
      ""
    case h <> t:
      U32.show(h) ++ (" " ++ show_bytes(t))

law show_res:
  for r: Result<&1, &1, (U32 & String), Unit>
  String

def show_res(r):
  match r:
    case Done{u}:
      "sent"
    case Fail{e}:
      (code, message) = e
      U32.show(code) ++ (" " ++ message)

law show_poll:
  for m: Maybe<&1, List<&2, U32>>
  String

def show_poll(m):
  match m:
    case None{}:
      "none"
    case Some{v}:
      "some: " ++ show_bytes(v)

law said:
  for m: Socket & Result<&1, &1, (U32 & String), Unit>
  IO(Socket)

def said(m):
  (s, r) = m
  do IO<Socket>:
    u : Unit <- IO.print(show_res(r))
    return s

law polled:
  for tag: String
  for m: Socket & Result<&1, &1, (U32 & String), Maybe<&1, List<&2, U32>>>
  IO(Socket)

def polled(tag, m):
  (s, r) = m
  do IO<Socket>:
    v : Maybe<&1, List<&2, U32>> <- IO.pass(Maybe<&1, List<&2, U32>>, r)
    u : Unit <- IO.print(tag ++ show_poll(v))
    return s

law got:
  for tag: String
  for m: Socket & Result<&1, &1, (U32 & String), List<&2, U32>>
  IO(Socket)

def got(tag, m):
  (s, r) = m
  do IO<Socket>:
    xs : List<&2, U32> <- IO.pass(List<&2, U32>, r)
    u  : Unit <- IO.print(tag ++ show_bytes(xs))
    return s

law run:
  for l: Listener
  for c: Socket
  for a: Socket
  IO(U32)

def run(l, c, a):
  do IO<U32>:
    s0 : Socket & Result<&1, &1, (U32 & String), Unit> <- TCP.send_bytes(c, [])
    c1 : Socket <- said(s0)
    s1 : Socket & Result<&1, &1, (U32 & String), Unit> <- TCP.send_bytes(c1, 7 <> (256 <> []))
    c2 : Socket <- said(s1)
    p0 : Socket & Result<&1, &1, (U32 & String), Maybe<&1, List<&2, U32>>> <- TCP.poll_bytes(a, 64, 100)
    a1 : Socket <- polled("empty: ", p0)
    s2 : Socket & Result<&1, &1, (U32 & String), Unit> <- TCP.send_bytes(c2, 1 <> (2 <> (255 <> [])))
    c3 : Socket <- said(s2)
    p1 : Socket & Result<&1, &1, (U32 & String), Maybe<&1, List<&2, U32>>> <- TCP.poll_bytes(a1, 64, 1000)
    a2 : Socket <- polled("data: ", p1)
    x  : Unit <- Socket.close(c3)
    r0 : Socket & Result<&1, &1, (U32 & String), List<&2, U32>> <- TCP.recv_bytes(a2, 64)
    a3 : Socket <- got("eof: ", r0)
    p2 : Socket & Result<&1, &1, (U32 & String), Maybe<&1, List<&2, U32>>> <- TCP.poll_bytes(a3, 64, 1000)
    a4 : Socket <- polled("eof poll: ", p2)
    y  : Unit <- Socket.close(a4)
    z  : Unit <- Listener.close(l)
    return 0

law accepted:
  for c: Socket
  for p: Listener & Result<&1, &1, (U32 & String), Socket>
  IO(U32)

def accepted(c, p):
  (l, ar) = p
  do IO<U32>:
    a : Socket <- IO.pass(Socket, ar)
    run(l, c, a)

law main_go:
  for b: Listener & U32
  IO(U32)

def main_go(b):
  (l, port) = b
  do IO<U32>:
    c : Socket <- IO.try(Socket, TCP.connect("127.0.0.1", port))
    p : Listener & Result<&1, &1, (U32 & String), Socket> <- TCP.accept(l)
    accepted(c, p)

law tcp_retry:
  for port : U32
  for r    : Result<&1, &1, (U32 & String), Listener>
  for rest : IO(Listener & U32)
  IO(Listener & U32)

def tcp_retry(port, r, rest):
  match r:
    case Done{l}:
      IO.pure(Listener & U32, (l, port))
    case Fail{e}:
      rest

law tcp_listen_any:
  for tries : Nat
  for +port : U32
  IO(Listener & U32)

def tcp_listen_any(tries, port):
  match tries:
    case 0n:
      IO.die(Listener & U32, 1, "no free tcp port")
    case 1n+t:
      rest = tcp_listen_any(t, (port + 1 : U32))
      do IO<Listener & U32>:
        r : Result<&1, &1, (U32 & String), Listener> <- TCP.listen(port)
        tcp_retry(port, r, rest)

law main:
  IO(U32)

def main():
  do IO<U32>:
    b : Listener & U32 <- tcp_listen_any(32n, 21013)
    main_go(b)

#|sent
#|22 Invalid argument
#|empty: none
#|sent
#|data: some: 1 2 255
#|eof:
#|eof poll: some:

2. (Optional) Share the receive loop in tcp_recv.c. tcp_poll.c shares tcp_poll_end and tcp_send.c shares tcp_send_more between the text and byte effects, but tcp_recv.c copies the whole recv/EAGAIN loop into tcp_recv_bytes_more. Sharing it, as the other two files do, would keep the pair from drifting.

Suggestion for a separate PR: the runtime has no helper to build or walk a list. Every effect that does it hand-rolls the loop: args.c, file_read.c and window_frame.c build lists; file_write.c and audio.c walk them; the JS twins do the same. With this PR, the bytes-to-list loop exists three times in C and three times in JS, and the list-to-buffer loop twice in each. Helpers next to io_str/io_cstr (C) and io_text/io_bytes (JS), such as io_list_u8 and io_take_u8, or a generic version that takes an element converter, would cover all of them. That is a runtime refactor across several effects, so it doesn't belong in this PR.

FYI on performance, since the byte effects might look like the fast path: they aren't. A List<U32> cell is the same 2-word cell a String uses per character. Draining 256 MB over loopback and counting every cell, recv_bytes is about 15% slower than recv in the C lane (0.52 s vs 0.45 s); in the JS lane it is faster on ASCII (1.72 s vs 2.56 s) and slower on 2-byte UTF-8 (1.76 s vs 1.33 s, twice the cells). The reason to use them is correctness, which is the right reason for this PR.

Note: this comment was written by an AI after it tested the PR for me and I reviewed the findings. If anything here is wrong, reply and I will review it myself.

@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for testing it on macOS, and for writing the edge test. It's in as tests/io/tcp_bytes_edges.bend, unchanged, with you as co-author (5b74688); it passes the check, interpreted, JS and C lanes here (Linux x86-64).

I also took the optional one, since it's the same shape the other two files already have: in 27454fd tcp_recv.c has a single tcp_recv_step shared by TCP.recv and TCP.recv_bytes, each keeping only its pack function (text or a list of bytes). The guide paragraph is gone too. The 19 tcp_*, udp_*, file_* and port_bound tests keep their output on all four lanes.

On arrays of bytes: agreed. Your measurement matches what I saw (a List cell per byte costs what a String char costs), so when a byte array type lands in Base these signatures should move to it. The list helpers (io_list_u8 / io_take_u8) sound right to me too; I'd be glad to try that refactor as a separate PR if you'd like.

One small edge I noticed while testing, in case it's useful: with max = 0, recv(fd, buf, 0) returns 0, so when data is waiting TCP.poll answers Some{""} (and TCP.poll_bytes Some{[]}), which reads as the peer's close while the peer is still open. TCP.poll already behaves this way, so I left it out of this PR; refusing max = 0 with EINVAL in both would fix it, here or separately, whichever you prefer.

…poll_bytes

A socket carries bytes and TCP.recv answers a String, so io_str decodes
each read as UTF-8 and writes U+FFFD over what it cannot decode. Two
kinds of payload do not survive that. A body that is not text -- an
image, a protobuf frame, a gzip stream -- loses every byte that is not
valid UTF-8. And a perfectly valid character loses itself when the
network splits it across two reads: each read decodes on its own, with
no state carried over, so "café" sent as 63 61 66 C3 | A9 arrives as
code points 99 97 102 65533 and 65533. Nothing in such a program is
wrong; the split is the network's choice and it happens under load.

File already draws this line: File.read decodes, File.read_bytes answers
"the bytes as they are (0..255), one List cell each", and its comment in
effs/file_read.c says a text reader would decode them as UTF-8. This
commit gives TCP the same pair, with the same types and the same shape:
TCP.send_bytes beside TCP.send, TCP.recv_bytes beside TCP.recv, and
TCP.poll_bytes beside TCP.poll, so a server with a deadline can read
bytes too. No new type, no new concept: List<&2, U32>, as File uses.

The text effects keep their code untouched, now under #ifdef CID(TCP.*)
as effs/file_read.c does, since each pair shares one effect file; the
send loop and the poll deadline are shared rather than copied. The JS
lane mirrors the C lane through the same pack-shaped parameter.

tests/io/tcp_bytes_split.bend sends a character in two halves and a
three-byte payload that is not text, and reads both back byte for byte
(99 97 102 195 / 169 / 255 0 128). It checks, interprets, JS-builds and
C-builds; tcp_listen_close, tcp_loopback, tcp_poll, tcp_spawn,
tcp_short_recv, tcp_send_slow_peer, tcp_connect_black_hole and
port_bound keep their output on both runnable lanes.

Co-Authored-By: Claude Opus 5 <[email protected]>
…y send, a byte past 255, poll_bytes idle, with data and at EOF

Written in review of this PR. It passes the check, interpreted, JS and C
lanes here (Linux x86-64): an empty send_bytes succeeds, a byte past 255
fails with EINVAL and sends nothing, poll_bytes answers None{} idle,
Some{bytes} with data and Some{[]} at EOF, as recv_bytes answers [] there.

Co-Authored-By: Nico Abril <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…CP.send already do, and the guide keeps no paragraph for them

tcp_recv.c's recv/EAGAIN loop lived twice; it is now tcp_recv_step,
which takes the caller's own wake and a pack function (text for
TCP.recv, a List of bytes for TCP.recv_bytes), plus a shared
tcp_recv_start. The JS twin already shared tcp_recv_with. The guide
paragraph on text and byte readers is gone: the signatures say it.

tcp_bytes_edges, tcp_bytes_split and the other tcp_*, udp_*, file_* and
port_bound tests (19) print their expected lines on the check,
interpreted, JS and C lanes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (95317d9): #1042 changed how effect files name things, and the branch no longer merged. The new effects now follow its form in both lanes: CID(TCP.recv_bytes) and the other ids in C, under #ifdef CID(TCP.*) guards as file_read.c has them, and in JS the CID(Con) / CID(Some) tags and one io_eff(CID(...), ...) per effect. Applied to these six files as they stood before #1042, the same respelling gives main's versions byte for byte, so the port changes nothing but the names. The three commits are the same, and your edge test is in unchanged, with you as co-author.

Re-run on the new base, Linux x86-64:

  • The 19 tcp_*, udp_*, file_* and port_bound tests, tcp_bytes_split and tcp_bytes_edges included, print their expected lines on the check, interpreted, JS and C lanes.
  • The tests/io checkup (119 modules) is identical to main's but for the two new tests' sections.
  • gates/repo.ts passes 46 / 46.
  • Each pair shares one effect file, and the runtime now refuses an effect registered twice, so I also built programs that use both effects of a pair: tcp_bytes_split already mixes recv and recv_bytes, and a scratch program mixing send / send_bytes and poll / poll_bytes passes all four lanes.

macOS was not re-run here after the rebase.

Comment thread bend2/effs/tcp_poll.js Outdated
@@ -5,15 +5,25 @@
// nothing parks on the socket and on the clock, whichever fires first;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment above was for tcp_poll

Comment thread bend2/effs/tcp_poll.js Outdated
function tcp_poll(socket, max, ms, k) {
// The bytes as they are (0..255), one List cell each, as File.read_bytes
// gives them.
function tcp_poll_list(b, n) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be made into a array-to-list helper at the shared runtime, like io_text

Comment thread bend2/effs/tcp_poll.js
return xs;
}

function tcp_poll_with(socket, max, ms, k, pack) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

poll_with now receives a function argument, check if the performance is still the same.

Comment thread bend2/effs/tcp_recv.c
// still finds nothing (the socket is non-blocking) parks again, on `more`,
// the caller's own wake. `pack` turns what was read into the answer: text
// for TCP.recv, bytes for TCP.recv_bytes. The rest is the same for both.
static Term tcp_recv_step(Env e, IoWork* w, Term (*more)(Env, IoWork*),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same thing, test the performance

Comment thread bend2/effs/tcp_poll.js Outdated
// past the deadline it answers None{}, else Some{data} ("" is the peer's
// close, as TCP.recv answers it).
function tcp_poll(socket, max, ms, k) {
// The bytes as they are (0..255), one List cell each, as File.read_bytes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is incomprehensive.

…ild a String

Asked in review. The six copies of the bytes-to-list loop (File.read_bytes
and File.read_at, TCP.recv_bytes, TCP.poll_bytes, in C and JS) now call
io_list, next to io_str in the C runtime and io_text in the JS one. The C
helper sits under #if defined(CID(Nil)) && defined(CID(Con)): a program
with no List has no such ids, and without the guard every IO program that
does not use one failed to build. TCP.poll's comment is back above
tcp_poll, where it stood before this PR.

The 19 tcp_*, udp_*, file_* and port_bound tests print their expected lines
on the check, interpreted, JS and C lanes; gates/repo.ts passes 46 / 46.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldeni

aldeni commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. All five are addressed in b930244:

  • The list helper. io_list now sits in the shared runtime in both lanes, next to io_str in C and io_text in JS: n bytes become a List, one cell each. It replaces all six copies of the loop: File.read_bytes / File.read_at, TCP.recv_bytes and TCP.poll_bytes, in C and in JS. The C helper needs a #if defined(CID(Nil)) && defined(CID(Con)) guard, because a program that has no List also has no ids for it, and without the guard every IO program that doesn't use a list failed to build. The list-to-buffer direction (file_write, tcp_send) is untouched. I can do that one the same way if you want.
  • The comments. The TCP.poll comment is back above tcp_poll, where it was on main. The one you flagged as incomprehensible went away with the function it described.
  • Performance. I drained 256 MB (C) and 32 MB (JS) over loopback, counting every cell. The runs were interleaved, the machine was idle, and the numbers are medians of 5 runs. I compared the branch's base, which has no function argument, the PR before the shared step, and the PR now:
lane effect base before sharing now
C recv 1.198 s 1.206 s 1.199 s
C poll 1.217 s 1.208 s 1.209 s
JS recv 4.095 s 4.031 s 4.033 s
JS poll 4.069 s 4.013 s 4.004 s
JS recv_bytes – 2.325 s 2.341 s
JS poll_bytes – 2.325 s 2.316 s

The function argument costs nothing measurable. In C, clang inlines pack through the constant pointer, and in JS the text paths didn't move.

One thing I can't fully explain: in C, the byte effects are about 3% slower with io_list than with the loop written inside the effect (7 interleaved runs of poll_bytes, 1.121 s vs 1.085 s; recv_bytes is the same). The emitted loop is the same code, and the io_list version even keeps the load of w->data out of the loop. Forcing the loop alignment (-falign-loops=64) didn't change either number. I suspect code layout, but I haven't proven it. If the 3% matters more than one shared loop, I can keep the helper in JS and inline the loop in C. Your call.

The 19 tcp_*, udp_*, file_* and port_bound tests pass the check, interpreted, JS and C lanes, and gates/repo.ts passes 46 / 46 (Linux x86-64).

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, io_list looks good, and so do the performance numbers. I merged this onto current main (which now has #977 and #1061): it merges cleanly, tcp_bytes_split and tcp_bytes_edges pass on the check, interpreted, JS and C lanes, the other tcp_*, udp_*, file_* tests and port_bound still pass, and gates/repo.ts is 46/46.

Three more things before merge:

  1. Share the poll step in tcp_poll.c. tcp_poll_bytes_more and tcp_poll_bytes_run are copies of tcp_poll_more and tcp_poll_run, with only io_str swapped for io_list. Please share them through a pack function the way tcp_recv.c now does with tcp_recv_step (and tcp_poll.js with tcp_poll_with).

  2. Share the list-to-buffer direction too. tcp_send_bytes_run in C repeats file_write_bytes_run's loop, and tcp_send_bytes in JS repeats file_write_bytes's. Please do what you offered: one helper for each runtime, next to io_list (and io_cstr / io_bytes), used by both File.write_bytes and TCP.send_bytes.

  3. Fewer comments. Most of the new ones restate what the signature or the function name already says (e.g. "TCP.poll with the bytes as they are, the pair of TCP.recv_bytes…", and the ones on io_list and above tcp_send_bytes). The one above tcp_recv_list explains why TCP.recv loses bytes, which belongs in the PR, not the code. Please keep only comments that say something the code doesn't.

On your questions: the ~3% in C for io_list is fine, one shared loop is worth more. Refusing max = 0 makes sense, but as its own PR.

aldeni and others added 4 commits September 25, 2026 15:22
…recv_bytes do

tcp_poll_step(e, w, more, pack) takes over the deadline logic that
tcp_poll_more and tcp_poll_bytes_more used to duplicate; tcp_poll_start
factors the other duplicate, the handle/size/buffer setup. Each effect
keeps only its thin _more (one call into the shared step) and _run
(start, then park). pack is the raw builder, Term (*)(Env, const char*,
u64): io_str for TCP.poll, io_list for TCP.poll_bytes, matching what
tcp_poll.js already passes to tcp_poll_with (io_text / io_list). The step
wraps the result itself (io_done(io_box(Some{pack(...)}))), so pack does
not need to know about IoWork or the Some{} wrapping.

tcp_recv.c's tcp_recv_step took the same pack signature, which drops the
tcp_recv_text and tcp_recv_list wrapper functions: tcp_recv_step now
calls io_str / io_list directly and wraps the result in io_done itself,
the same way tcp_poll_step does. This also removes the comment that
explained why TCP.recv loses bytes (UTF-8 decoding per call, split
characters not surviving) — that belongs in the PR thread, not in code
that no longer has a natural place to hang it once the wrapper it
documented is gone.

Both io_str and io_list stay inside the #ifdef CID(TCP.poll) / CID(TCP.
poll_bytes) and CID(TCP.recv) / CID(TCP.recv_bytes) sections, as before,
so a program that never uses List still builds (io_list itself only
exists under #if defined(CID(Nil)) && defined(CID(Con)), and nothing
outside those effect blocks references it).

Lanes (check/interp/js/c) all PASS on tcp_poll, tcp_bytes_split,
tcp_bytes_edges, the other tcp_*, udp_*, file_* tests and port_bound.
bun gates/repo.ts: PASS 46/46.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…io_clist

io_clist sits next to io_list in both runtimes (bend2/comp.ts), as io_cstr
sits next to io_str in C and io_bytes sits next to io_text in JS: io_list
already decodes a byte buffer into a List with the same name in both
runtimes, so its encode-direction twin keeps that pairing. Semantics are
unchanged from the two copies it replaces: every value 0..255 becomes one
byte; a value past 255 fails the effect with EINVAL (22) and nothing is
written or sent; in C every list cell is still consumed and freed by the
same loop, including after a bad value (io_clist always returns a buffer
to free, and drains the list to the end via *bad instead of an early
return). File.write_bytes's early return (w->code ? file_write_pack(...)
: io_work(...)) and TCP.send_bytes's path through tcp_send_more are
unchanged.

Lanes (check/interp/js/c) all PASS on tcp_bytes_split, tcp_bytes_edges,
the other tcp_*, udp_*, file_* tests and port_bound. bun gates/repo.ts:
PASS 46/46.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…esn't already say

Trims comments the PR added that restated the signature or the function
name: io_list's ("io_list is io_str's/io_text's twin for bytes...", both
runtimes — the #if guard and the function body already say as much),
tcp_poll_bytes's/tcp_poll.js's ("TCP.poll with the bytes as they are, the
pair of TCP.recv_bytes...") and tcp_recv_bytes's JS twin of the comment
already dropped from tcp_recv.c in the previous commit ("TCP.recv decodes
the same bytes as UTF-8...").

Lanes (check/interp/js/c) all PASS on every tcp_*, udp_*, file_* test and
port_bound. bun gates/repo.ts: PASS 46/46.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…es takes 141 ms in C, where the loop it replaced took 181

io_clist wrote *bad through its pointer on every cell, and since the
byte store into buf may alias it, clang loaded and stored it on every
turn. A local flag, stored once at the end, stays in a register.
File.write_bytes of 50M bytes to /dev/null, medians of 7 interleaved
runs in C: 181 ms before this round (the inline loop), 191 ms with the
first io_clist, 141 ms now; the JS lane is unchanged. Its two comments
go as well: what they said, the code says.

The 19 tcp_*, udp_*, file_* and port_bound tests print their expected
lines on the check, interpreted, JS and C lanes; gates/repo.ts passes
46 / 46.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldeni

aldeni commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for merging it onto main and running everything again, and for the clear list. All three are in, in three commits on top of b930244, plus a small fix that came out of measuring them:

  • The poll step (f77ae80). tcp_poll.c now has tcp_poll_step(e, w, more, pack) and tcp_poll_start, the shape tcp_recv.c has. pack takes the bytes read, Term (*)(Env, const char*, u64), so both files pass io_str or io_list straight in, as tcp_poll.js and tcp_recv.js already pass io_text or io_list. That drops the tcp_recv_text and tcp_recv_list wrappers.
  • The list-to-buffer direction (b015b3d). io_clist sits next to io_list in both runtimes, the list twin of io_cstr in C and of io_bytes in JS, and both File.write_bytes and TCP.send_bytes call it. A value past 255 still fails the effect with EINVAL before anything is written or sent, and in C every cell is still freed. The C helper sits under the same #if defined(CID(Nil)) && defined(CID(Con)) guard as io_list.
  • Comments (484d8f3, 10dd464). Every comment this PR had added is gone, and the one on tcp_recv_step is back to main's two lines. The comments that were already on main stay. The UTF-8 explanation lives in the PR description, under "Why".
  • io_clist's flag (10dd464). The first version wrote the out-of-range flag through its pointer on every cell. Since the byte store into the buffer may alias it, clang loaded and stored it on every turn. A local flag, stored once at the end, stays in a register.

Performance. Drained over loopback as last time (256 MB in C). Medians of 7 interleaved runs on an idle machine:

C before this round now
TCP.poll 1.264 s 1.405 s
TCP.poll, both built with -falign-functions=64 1.405 s 1.414 s
TCP.poll_bytes 1.169 s 1.161 s
File.write_bytes, 50M bytes to /dev/null 181 ms 141 ms

TCP.poll in C reads 11% slower, but the shared step isn't the cause. tcp_poll_more, the function every read runs, compiles to the same machine code before and after, and it calls io_str directly, not through pack. What moved is where the code lands: the new tcp_poll_start shifts tcp_poll_more and io_str by 32 bytes. Built with -falign-functions=64, both versions take the same time, and the old one alone goes from 1.264 s to 1.405 s under that flag. So I read it as code layout, which may also be behind the 3% I couldn't explain last round. TCP.recv, TCP.recv_bytes and the JS lane stayed within noise (5 interleaved runs, 256 MB in C and 32 MB in JS).

Checks (Linux x86-64):

  • The 19 tcp_*, udp_*, file_* and port_bound tests pass the check, interpreted, JS and C lanes on the branch, and so do the 20 of them merged onto current main (11c65a2, which adds tcp_listen_backlog).
  • Programs that use both effects of a pair (TCP.poll/poll_bytes, recv/recv_bytes, send/send_bytes, File.write/write_bytes) pass all four lanes. So do programs that use only TCP.poll, or only File.write, with no List anywhere; their C defines neither CID_NIL nor CID_CON, so both helpers drop out.
  • gates/repo.ts passes 46 / 46, on the branch and merged. Merged with main, comp.ts sits at 63923 of its 64000 ttok, in case that matters for the next change nearby.

The max = 0 change will follow as its own PR once this one lands. And thank you for the care across these rounds: the shared helpers and the edge test made this PR much better than the one I first opened.

…ce next to io_str

87a1e9c moved io_str's comment into the section header, which was the
only conflict. The poll step picks up main's w->time in place of the
io_wait_time it replaced. The 20 tcp_*, udp_*, file_* and port_bound
tests (tcp_listen_backlog included) print their expected lines on the
check, interpreted, JS and C lanes, and so do programs that mix both
effects of each pair and programs with no List; gates/repo.ts passes
46 / 46, comp.ts at 62984 of its 64000 ttok.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldeni

aldeni commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the three review rounds on this, @nicolas-abril. TCP.send_bytes and TCP.recv_bytes are in 2.0.32 (573002f), in the shape this PR ended up with (io_list, the reader passed to the shared receive step, one list-to-buffer helper), so I'm closing this one.

The piece 2.0.32 leaves out is TCP.poll_bytes, the byte twin of TCP.poll. IO.within doesn't cover it: on a timeout it answers None{} while the losing recv_bytes still holds the socket, so a server that drops idle connections needs the deadline inside the effect to read bytes and keep its socket. If you want it, it's a small PR on top of main's tcp_poll.c / .js, with the same reader parameter as tcp_recv_with, and the max = 0 refusal you suggested can go as its own PR. Happy to send either or both.

@aldeni aldeni closed this Sep 27, 2026
nicolas-abril added a commit to tachytelicdetonation/bend that referenced this pull request Sep 28, 2026
bendlang#978, which was to rewrite them, closed, so they fold like the rest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants