Skip to content

tcp: the sweep walks the connection table only for a clock or a starved recv, and a write shutdown deferred behind a flush waits in a queue of its own - #653

Merged
MDA2AV merged 5 commits into
mainfrom
fix/tcp-sweep-events
Nov 23, 2026
Merged

MDA2AV merged 5 commits into
mainfrom
fix/tcp-sweep-events

Conversation

@MDA2AV

@MDA2AV MDA2AV commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

TcpSweep walked every slot of the reactor's connection table on every tick (~250 ms), whatever the options. That table is indexed by fd, so it spans every descriptor in the process, not one reactor's share. At a million connections over 64 reactors, each reactor walks about 1M slots (8 MiB of references) to find its ~15.6K connections, and all of them do it on the same tick, since they start together. The reactor serves no completions during the walk.

That is where genhttp-ioxide's tail on HttpArena's held-connection profiles comes from. Its median matches the field (p50 70 µs), but p99 is 1.5-2.4 ms against 134-158 µs for the six other entries, p99.9 is 3.7-4.7 ms and the max 5-7 ms. The same shape shows on CON-1M-TLS, and CON-5M has p99 54 ms. Measured on the dev box, on main:

  • Probe: one connection sending a request every millisecond while the server held a paced fleet saw a stall exactly every 250 ms, growing with the fleet: none at 0, ~0.4 ms at 50K, ~0.56 ms at 200K.
  • The loop body timed at CON-1M's shape (a 1,048,576-slot table, 1/64 of it live): 0.69 ms with one reactor sweeping, 2.98 ms p50 (3.56 ms max) with 32 sweeping at once. CON-5M's shape: 15.7-20 ms.

GenHTTP leaves both TCP timeouts at 0, so it needed none of the clocks the walk serves.

What changes

  • The walk is made only when a connection can need it: ReadTimeoutMs or SendTimeoutMs set, or a recv parked on -ENOBUFS. The parked recv needs the reclaim of buffers that let-go connections still hold, and the teardown of a condemned connection whose recv is parked. The re-arm of accepts paused on EMFILE/ENOMEM still runs every tick.
  • Deferred write shutdowns wait in a queue of their own. Making them was the other thing the walk did with no clock set. A handler that lets go, or ShutdownWrite, means shutdown(SHUT_WR); with a flush in flight that would cut the flush short, so it waits for the flush. Such a connection is now added to a small queue (_deferredWriteShutdowns), from any thread, and each tick looks at what is in it: the flush over, the shutdown is made; still in flight, it stays for the next tick; the connection gone, it is dropped. The queue is nearly always empty, because a handler that awaits its last flush never defers anything.
  • Same timing as main: within a tick of the flush being over. DecRef goes through ShutdownWrite.

Nothing is added to the send path or the loop: FinishSend, the loop and the drainers are main's. Per tick, the reactor checks one queue, which is nearly always empty. Throughput was not measured (bench/ab.sh was not run), and there is nothing new on the request path to measure.

Names

ioxide sends no FIN: it calls shutdown(SHUT_WR), and the kernel sends the FIN behind the bytes it already took. The internal members around it were named for the FIN, so they are renamed after the public ShutdownWrite:

Was Is now
SendFin ShutdownWriteNow
SuppressFin SuppressWriteShutdown
FinSent WriteShutdownDone
_finSent, _finSentMs _writeShutdown, _writeShutdownMs
FinWanted gone, with the walk's use of it

QUIC's FIN names are untouched: there the FIN is a frame bit that ioxide and ngtcp2 do write. Comments and tests still say FIN for what the peer receives.

Not in this PR:

  • A dense per-reactor list of connections for the walk itself, which would still help whoever sets a timeout (both default to 60 s): about 0.39 ms instead of 2.98 ms per tick at the shape above.
  • In incremental mode a recv parked on its own ring brings the walk back, although no other connection's buffers can help it. Main always walks, so this is no worse.
  • The Kotlin port (kotlin branch, TcpTransport.sweep()) has the same walk and needs the same change.

Tests

TcpSweepTests is new. Servers in it run with both clocks off unless the test is about one, so the walk never runs, and a write shutdown that is never made fails with "no FIN: nothing more after N bytes". A stalling body against a bounded SO_SNDBUF and client receive buffer keeps the flush in flight until the client reads, on any tcp_wmem and tcp_rmem. It covers:

  • a let-go behind a flush that is still in flight two ticks later, for every send shape (SEND, SEND without MSG_WAITALL, segmented SENDMSG, SEND_ZC, incremental): not one byte may be lost, and the FIN must come after
  • sixteen let-gos from the thread pool at once
  • ShutdownWrite behind a flush, with the read side staying open
  • a let-go inside a flush's completion, behind a second flush armed there
  • a flush that ends without a send, which no completion follows
  • an entry whose connection is gone: dropped, and the descriptor's next connection left alone
  • a deferred let-go on the read clock from its write shutdown
  • the send clock alone still bringing the walk: a slow reader's flush cut at its deadline
  • a paused accept re-armed with no clock set

Checked against mutants in a separate checkout, all twelve caught: the queue never run, the early return ahead of it, one still in flight dropped instead of kept, the flush in flight ignored by the tick, nothing queued, shut down at once regardless, DecRef not asking, the early return ahead of the accept re-arm, only the flush's completion making it, the early return ignoring the send clock, the generation and state checks dropped, and no read-clock stamp. The new tests passed 12 of 12 repeat runs, and 8 of 8 pinned to two cores and to one.

Suite Result
E2E 812 passed, 0 failed, 1 skipped (a Kestrel kTLS test)
Unit 397 passed, 0 failed, 0 skipped
Http 113 passed, 0 failed, 0 skipped
File 14 passed, 0 failed, 0 skipped
Tls 217 passed, 0 failed, 41 skipped (every skip is a kTLS test: no tls module on this box)
Chaos 105 passed, 0 failed, 0 skipped
Pg, Redis not run, not reached by this change

Review

Two agents reviewed this version: one the write shutdown's lifecycle and races, one everything else it touches.

  • No bug introduced. The first fuzzed 20 handler shapes against 6 client behaviors in 9 configurations, with delays injected at every step, ran the same probes on main, and explored every interleaving of 13 scenarios in a model. The second ran the suites on this branch and on main with both clocks forced to 0, with -1, and with only one set, and got the same results.
  • A race that main has and this closes. Main's walk reads whether a flush is outstanding before it reads whether the handler let go, so an off-reactor handler that flushes and lets go between the two gets its FIN ahead of its response. With 1 ms between the reads, main cut 24 of about 6,200 responses to 0 bytes; this branch, delayed the same way, cut none of about 5,900.
  • Fixed from review: ShutdownWrite had become documented for any thread, which is only safe while the caller holds the handler's ref throughout; it is "Reactor thread only" again, as on main. The rest were test gaps, closed above.
  • Cost of a stuck entry: per reactor, 10K let-gos whose flush never finishes cost 0.15 ms a tick here against 0.05 ms in main's walk, 100K cost 2.4 ms against 0.63 ms. The default 60 s send clock reaps them.
  • Pre-existing, not changed here: a tick that lands between FlushAsync taking _flushInProgress and stamping FlushArmedMs, off the reactor, sees the last flush's stamp, or 0, and closes a healthy connection on the send clock.

Four agents reviewed an earlier version, which made the shutdown from the flush's completion, through a queue to the reactor and with a retry list for what that missed. One found a bug in it: 16 of 100 connections that asked while an empty flush was passing never got their FIN. That code is gone, and the same scenario run against this version lost none of 300.

Overlap

git merge-tree --write-tree against every open PR: this change adds no conflict.

🤖 Generated with Claude Code

…ed recv, and a FIN asked for behind a flush goes out from that flush's completion

The ticker's TcpSweep walked every slot of the reactor's fd-indexed connection table four times a second, whatever the options. The table spans every descriptor in the process, not one reactor's share: at a million connections over 64 reactors each walks a million slots, all on the same tick, and the walk held each reactor off its ring for long enough to show in the tail of every request behind it.

The walk is now made only when a connection can need it: ReadTimeoutMs or SendTimeoutMs set, or a recv parked on -ENOBUFS (the reclaim of buffers that let-go connections still hold). The re-arm of accepts paused on EMFILE/ENOMEM still runs every tick.

The other job it did with no clock set was the FIN asked for behind a flush, by a handler that let go or by ShutdownWrite: it went out at the first tick after the flush completed. FinishSend now sends it when the flush's final completion lands. The ask is decided on the reactor, inline there and through a queue (_finQ) from any other thread, so the ask and the completion are ordered by one thread rather than raced across two. The sweep keeps calling it as a backstop when it walks anyway.
…so one whose flush ended without a send still goes out

Review of #653 found an ask from another thread could be stranded with both clocks off. It was decided at the reactor's drain while a flush with nothing staged was passing through FlushAsync, or while an arm released by MarkClosed was ending, and so left standing behind a flush that has no send completion. With the walk skipped, nothing retried it. The reviewer's probe lost 16 of 100 FINs, where main's every-tick walk had healed each within a tick.

The reactor now keeps the asks it leaves standing (_finAsked) and retries only those on every tick (RetryFinAsks), whatever the options. That restores main's bound without walking the table. The walk's own FIN backstop is gone: the list covers every ask, since AskFinBehindFlush is the only place one is left standing.

Also from review:
- SendFinOrDefer returns at once for a FIN already sent or suppressed instead of queueing an ask.
- EnqueueFinBehindFlush stops spinning once the reactor's posts are closed, as EnqueueReturnQ does.
- ShutdownWrite is documented for any thread, now that its ask is decided on the reactor.

The FIN tests move to FinBehindFlushTests, written by the test reviewer, all with both clocks off. They cap the server socket's SO_SNDBUF and keep the client from reading until the handler has let go, so a flush is deterministically in flight on any tcp_wmem, and they read the FIN state to prove which branch ran. Coverage:
- every send shape (SEND, SEND without MSG_WAITALL, segmented SENDMSG, SEND_ZC, incremental);
- sixteen let-gos from the thread pool;
- an off-reactor ShutdownWrite;
- an ask drained only after its flush completed;
- a let-go inside a flush's completion behind a second flush;
- a stop with an ask still queued;
- accepts paused on EMFILE resuming with no clock set.

Two more cover ShutdownWrite on the reactor behind a flush, and the stranded ask above, which stops at its first lost FIN.
… for the FIN the kernel sends

ioxide sends no FIN. It calls shutdown(SHUT_WR), and the kernel sends the FIN behind the bytes it already took. The internal members around it were named for the FIN, so they are renamed after the public ShutdownWrite:

- SendFin -> ShutdownWriteNow
- SuppressFin -> SuppressWriteShutdown
- FinSent, FinWanted -> WriteShutdownDone, WriteShutdownDeferred
- _finSent, _finSentMs -> _writeShutdown, _writeShutdownMs
- SendFinOrDefer is gone: it is ShutdownWrite's body, which DecRef calls too
- AskFinBehindFlush -> ShutdownWriteOrDefer
- SendFinBehindFlush -> RunDeferredWriteShutdown
- EnqueueFinBehindFlush, _finQ, DrainFinQ -> EnqueueWriteShutdown, _writeShutdownQ, DrainWriteShutdownQ
- AskFin, _finAsked, RetryFinAsks -> ShutdownWriteOrDefer, _deferredWriteShutdowns, RetryDeferredWriteShutdowns
- FinBehindFlushTests -> WriteShutdownTests

No change in behavior: with comments stripped and the names mapped, the code is the same but for SendFinOrDefer moving into ShutdownWrite. QUIC's FIN names stay, as the FIN there is a bit of the frames ioxide and ngtcp2 write, and so does FIN for what a peer receives.
@MDA2AV MDA2AV changed the title tcp: no table walk without a clock or a starved recv, and a FIN behind a flush goes out from that flush's completion tcp: no table walk without a clock or a starved recv, and a write shutdown behind a flush is made from that flush's completion Nov 23, 2026
…om a queue of its own, and by nothing else

The flush's own completion made it before, with a queue that took the decision to the reactor thread and a retry list for what the completion missed: a let-go from another thread that lost the race with it, and a flush that ends without a send. The tick had to catch those anyway, so it now makes all of them, when main's sweep did, from a queue instead of a walk of the table. Nearly always that queue is empty: a handler that awaits its last flush never defers anything.

- ShutdownWrite (and DecRef, through it) with a flush in flight marks the connection and adds it to the reactor's queue, from any thread.
- The tick looks at each entry once. Its flush over, the shutdown is made; still in flight, it goes back for the next tick; its connection gone, it is dropped.
- FinishSend, the loop and the drainers are main's again, so nothing is added to the send path or the loop.

The tests lose the two that were about the queue's order against the completion. The send shapes now stall their flush past two ticks, which must neither cut it short nor lose the shutdown.
@MDA2AV MDA2AV changed the title tcp: no table walk without a clock or a starved recv, and a write shutdown behind a flush is made from that flush's completion tcp: the sweep walks the connection table only for a clock or a starved recv, and a write shutdown deferred behind a flush waits in a queue of its own Nov 23, 2026
…ests cover what review found they did not

Two reviewers found no bug in the change, one wording to take back and gaps in its tests.

- ShutdownWrite is documented "Reactor thread only (#211)" again, as on main. Off the reactor it is only safe while the caller holds the handler's ref throughout, which DecRef, its only off-reactor caller here, does.
- TcpSweep's summary no longer says that it is one pass over the table.

WriteShutdownTests becomes TcpSweepTests, and:
- a flush that ends without a send (MarkClosed releases it) must still get its deferred shutdown. No test noticed a version where only the flush's completion made it;
- the send clock alone must still bring the walk: a slow reader's flush has to be cut at its deadline, which TCP_USER_TIMEOUT does not do;
- an entry whose connection is gone must be dropped, and the descriptor's next connection left alone;
- a deferred let-go is on the read clock from its write shutdown;
- the send shapes assert that the flush is still in flight after two ticks, with the client's receive buffer bounded so that a large tcp_rmem cannot absorb it;
- the paused accept is put on the list rather than made by lowering RLIMIT_NOFILE, at which .NET cannot even start a thread;
- the off-reactor ShutdownWrite and the stop tests are gone: the first is now outside the contract, the second never had a tick look at its entry.
@MDA2AV
MDA2AV merged commit fb54135 into main Nov 23, 2026
2 checks passed
@MDA2AV
MDA2AV deleted the fix/tcp-sweep-events branch November 23, 2026 17:13
MDA2AV added a commit that referenced this pull request Nov 23, 2026
… the table walk, only a look at the recvs waiting (#655)

A recv parked on -ENOBUFS makes the sweep walk the table, to take back what connections their handler let go hold. From the shared ring any of them can end the wait. With a ring per connection only the one waiting can, and then only once its handler has let go, so the walk served nothing for as long as a handler was too busy to read an upload.

The sweep now looks at the recvs waiting alone in that mode, and gives back what one's handler let go of. It cannot leave that out too: a connection whose handler lets go of a dry ring would never see its client close, and keep its descriptor. Condemned ones are let go of as before, walk or no walk.

Suites, on main with #653 and #654: E2E 816 (1 kTLS skip), Unit 403, Http 113, File 14, Tls 217 (41 kTLS skips), Chaos 105, none failing.
@MDA2AV MDA2AV mentioned this pull request Nov 23, 2026
MDA2AV added a commit that referenced this pull request Nov 23, 2026
All twelve csproj Version elements, 0.28.652 to 0.29.656. Carries the 3 PRs from #653 to #655. Package validation against 0.28.652, in strict mode, finds no API change in any of the eleven published packages.

Suites on this tree: Unit 403, Pg 10 (19 skipped, no server here), Redis 1 (7 skipped and 1 pending, no server here). On the same code before the bump: E2E 816 (1 kTLS skip), Http 113, Chaos 105, File 14, Tls 217 (41 kTLS skips, no tls module here).
MDA2AV added a commit to Kaliumhexacyanoferrat/GenHTTP that referenced this pull request Nov 23, 2026
All five ioxide packages move from 0.27.637 to 0.29.656, past 0.28.652. Neither release changes the API, so the engine builds against it unchanged.

0.29 stops a reactor from walking its whole connection table every 250 ms when both TCP timeouts are off, the engine's default, and no longer closes a connection whose flush was just being started by the time of the one before (MDA2AV/ioxide#653 to #655). 0.28 checks HTTP/2 frames, streams and requests against RFC 9113 and refuses a QUIC ClientHello without transport parameters, which aborted the process (MDA2AV/ioxide#645 to #651).
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.

1 participant