Skip to content

TCP.connect_within connects with a deadline, as TCP.poll receives with one - #1011

Closed
aldeni wants to merge 1 commit into
bendlang:mainfrom
aldeni:tcp-connect-deadline
Closed

aldeni wants to merge 1 commit into
bendlang:mainfrom
aldeni:tcp-connect-deadline

Conversation

@aldeni

@aldeni aldeni commented Sep 23, 2026

Copy link
Copy Markdown
Contributor
def TCP.connect_within(host: String, port: U32, ms: U32) ->
  IO(Result<&1, &1, U32 & String, Socket>)

It answers as TCP.connect does, with one more way to fail: if the handshake
has not finished ms milliseconds after the call, the connect fails with
ETIMEDOUT and the socket it opened is closed.

Why

TCP.connect has no deadline. To an address that silently drops SYNs it waits
for the kernel's own timeout: here (Linux, default tcp_syn_retries = 6) a
native build of TCP.connect("192.0.2.1", 80) answered 110 Connection timed out after 134 s. TCP.poll (#861) gave a receive a deadline; connecting is
the one step left where a client cannot bound its time. A program with a total
deadline can refuse to start a connect once the deadline has passed, but
cannot bound one in flight, and nothing outside can end it: the program holds
no handle to a connect that has not answered.

Design

  • A new def, TCP.connect unchanged. The alternative is to add ms to
    TCP.connect itself; that breaks every caller, while the Base IO additions
    in the changelog are new defs beside the old ones (TCP.poll beside
    TCP.recv, File.read_at beside File.read), and it is the shape TCP.listen_shared lets N processes share a port; TCP.listen keeps owning its own #972
    settled on after review (TCP.listen_shared beside TCP.listen). The name
    reads as read_at and send_to do: a preposition naming the extra
    argument.
  • One source for both. The two defs share tcp_connect.c and .js, each
    effect under its own CID guard, as file_read.c does. TCP.connect runs the
    same code as before with no deadline on its park (0 to io_wait_on,
    undefined to io_park_on), so its wake is the one it had. comp.ts does
    not change: both parks already take a deadline.
  • ms is relative, as in TCP.poll: the deadline is io_tick() + ms * 1000000 in C and performance.now() + ms in JS, taken when the effect runs.
    No special case for ms = 0: the deadline is now and the poller answers at
    once.
  • Expiry fails with ETIMEDOUT, the error the kernel's own timeout gives
    (above), through io_fail on both lanes, so the text is libc's strerror
    as for every other failure; the fd is closed by the path that already closes
    it on any error. No Maybe: unlike a TCP.poll that answers None{}, a
    timed-out connect leaves no socket worth handing back.
  • A deadline is never read as success. The park waits on writability and
    on the clock, whichever fires first, and the wake is not told which. So a
    wake of a park with a deadline first asks the socket, without waiting,
    whether it is writable (poll in C; in JS select, the one readiness call
    io_sys binds). Not writable: the wake came from the clock and the connect
    is still pending, so it fails with ETIMEDOUT; a failed poll/select is
    read the same way. Writable: SO_ERROR says how the connect ended, exactly
    as TCP.connect's wake does. Without that check a deadline wake would read
    SO_ERROR = 0 from a pending socket and answer Done. A handshake that has
    finished when the wake runs, even at or past the deadline, answers how it
    finished, as a TCP.poll wake that finds data answers it. On Linux this is
    what ms = 0 to a local listener shows: loopback has finished the
    handshake by the time connect() returns EINPROGRESS, and 200 of 200
    such connects answered Done on the interpreted, JS and C lanes.

Tests

tests/io/tcp_connect_within.bend, on the check, interpreted, JS and C lanes:

  1. to a local listener (a free port found by a failing TCP.listen, as the
    other TCP tests do) it connects and the socket carries a send and a recv;
  2. to that port after the listener closes it fails with Connection refused:
    the deadline rewrites no error;
  3. to TEST-NET-1 (192.0.2.1:80) with ms = 200, beside a 1500 ms timer, it
    fails before the timer prints. The line names the outcome, not the error,
    so a network that refuses the address at once prints the same lines.

Unlike tcp_connect_black_hole, the test needs no IO.die: the connect ends
at its deadline, so the program ends with the timer. The C lane here, each
line stamped by a wrapper as it arrived:

      1 ms  bend-within
      1 ms  Connection refused
    202 ms  hole: failed
   1504 ms  timer

The JS lane printed the same lines at 29, 30, 231 and 1538 ms, and the
interpreted lane at 181, 182, 383 and 1686 ms (its start-up and check
included).

It fails on this machine, on all three run lanes, with either change undone:

  • TCP.connect in place of the 200 ms connect prints timer and then does
    not end (the harness's alarm kills it);
  • without the writability check, the deadline wake answers hole: connected.

A scratch program printed 110 Connection timed out for ms = 200 (201-202
ms) and for ms = 0 (0 ms) on each lane, and 22 Invalid argument for a bad
host or a port past 65535, as TCP.connect answers them. 1000 connects in a
row to 192.0.2.1 with ms = 0, under ulimit -n 64, all answered ETIMEDOUT
on the JS and C lanes: the timed-out socket is closed. Four concurrent copies
of the test, three rounds, passed 12/12 on the JS and on the C lane.

Regression: tests/io, tests/base and tests/reg (236 tests) through the
same four lanes give identical results on this branch and on 6a77e12: 172
pass every lane on both, and the other 64 fail a local runner simpler than the
gate the same way on both (expected checker errors, the exit N line the gate
appends, mains that cannot be printed, tests with their own foreign twins).

Merge: clean with #972, #977 and #978, pairwise and all four together in every
order (one resulting tree). On that tree the eleven tcp_* tests, the other
three PRs' included, and port_bound pass on all four lanes.

Not tested

  • macOS: not tested. The macOS constants (ETIMEDOUT = 60) and the
    zero-timeout poll/select on a connecting socket are unverified there; the
    loopback ms = 0 result above is Linux only, and the test does not rely on
    it.
  • The black-hole case shows the deadline only where the network drops packets
    to 192.0.2.1, as it does here. In a sandbox with no route the connect fails
    at once, the test prints the same lines, and it does not discriminate.
  • A handshake that finishes in the same instant as the deadline cannot be
    forced; the rule for it is the one above.

…IMEDOUT and closes its socket

TCP.connect waits for the kernel's own timeout: here (Linux,
tcp_syn_retries = 6) a native TCP.connect("192.0.2.1", 80) answered
"110 Connection timed out" after 134 s. TCP.poll gave a receive a
deadline (bendlang#858); this gives one to the connect, the one step a client
still could not bound.

TCP.connect_within(host, port, ms) is a new def beside TCP.connect,
which is unchanged. Both share tcp_connect.c/.js, each effect under its
own CID guard, as in file_read.c. The deadline is relative, as
TCP.poll's: io_tick() + ms * 1000000 to io_wait_on in C,
performance.now() + ms to io_park_on in JS; TCP.connect parks with none
(0, undefined), so its wake is the one it had. comp.ts does not change.

The park wakes for writability or for the clock and is not told which,
and SO_ERROR is 0 on a socket still connecting. So a wake of a park with
a deadline first checks, without waiting, that the socket is writable
(poll in C, select in JS): if not, the connect is still pending and
fails with ETIMEDOUT through io_fail, and the existing error path closes
the fd; if so, SO_ERROR says how it ended, as for TCP.connect. A
handshake that has finished by the wake answers how it finished, even
past the deadline, as a TCP.poll wake that finds data does.

tests/io/tcp_connect_within.bend passes the check, interpreted, JS and
native lanes, and four concurrent copies (three rounds, 12/12 on JS and
on C): a local listener connects and carries a send, the same port
after its listener closes answers "Connection refused", and 192.0.2.1
with ms = 200 fails before a 1500 ms timer (202 ms on the native lane).
With TCP.connect in its place the timer prints first and the program
does not end; without the writability check the deadline wake answers
Done. Scratch runs on each lane: ETIMEDOUT (110) at 201-202 ms for
ms = 200 and at once for ms = 0; 1000 timed-out connects under
ulimit -n 64, all ETIMEDOUT (no fd leak); ms = 0 to a local listener
connects 200/200, as Linux loopback finishes the handshake before
connect() returns.

tests/io, tests/base and tests/reg (236 tests) through the same four
lanes give identical results here and on 6a77e12. The branch merges
clean with bendlang#972, bendlang#977 and bendlang#978, pairwise and all four in every order
(one tree), and on that tree the eleven tcp_* tests and port_bound
pass on all four lanes.

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

Copy link
Copy Markdown
Collaborator

Thanks for the PR, and for how carefully it was tested. I'm going to close it, but the problem it points at is real, so here's what I think a better fix looks like.

My concern is the shape: a deadline version next to a blocking effect. TCP.poll was the first, TCP.connect_within would be the second, and TCP.accept, Chan.recv and FIFO reads would each need one too. Every one needs its own C and JS code and its own tricky wake handling. You found one of those yourself: a wake doesn't say whether the clock fired or the socket did. That adds up to a lot of core surface for one idea, and we'd like to solve it once.

There are two ways I'd take it:

  1. A combinator in Base, no new effects. Race any IO(A) against IO.sleep(ms) with IO.fork and a Chan, returning IO(Maybe<A>). It bounds how long the caller waits for any action, using what we already have. What it doesn't do is stop the losing action: a pending connect stays parked, holds its fd, and keeps the program from ending.

  2. A general cancellable timeout in the runtime, something like IO.within(ms, act). Parks already take a deadline. What's missing is a way for a wake to know it timed out, and a cleanup step so a cancelled effect releases what it holds. Deciding what cancelling a whole IO sequence means is the hard design question.

If you'd like to keep going, please open an issue about timeouts and cancellation in general so we can agree on a design first. Or send a new PR with approach 1, which would already cover most real uses. Either one is much easier for us to accept than per-effect variants.

@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for closing it with the reasoning; that makes sense to me. One mechanism for every blocking effect is clearly better than a deadline twin for each of them.

Two things I ran into while writing it, in case they help the design:

  1. The wake ambiguity shows up in another place too. In the JS lane, io_wait ignores select's return, and when a signal interrupts it (EINTR) Linux leaves the fd sets as they were, so every parked fd is woken as if it were ready. Most effects just park again on EAGAIN, but tcp_connect.js reads SO_ERROR, which is 0 while the connect is still in progress: with a SIGINT handler installed, a TCP.connect to 192.0.2.1 plus kill -INT answers Done. The native lane stays pending, as it should.

  2. For a server, the cleanup step you mention is the part that matters most. With approach 1, a timed-out connect keeps its fd until the kernel gives up (about two minutes on Linux), so under load the fds pile up.

I'd be glad to open an issue on timeouts and cancellation with these notes, so we can agree on the design first.

@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Opened #1034 with these notes, so the design can be discussed there.

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