Skip to content

TCP recovery: D-SACK, RACK reordering window, congestion undo, Eifel and F-RTO - #20

Merged
KoganTheDev merged 32 commits into
mainfrom
feat/recovery
Nov 19, 2026
Merged

KoganTheDev merged 32 commits into
mainfrom
feat/recovery

Conversation

@KoganTheDev

Copy link
Copy Markdown
Owner

Summary

Item D of the follow-up plan. A spurious retransmission or timeout used to cut cwnd for nothing, and RACK's reordering window never adapted. Stacked on #19.

  • Receiver D-SACK (RFC 2883 section 4): a duplicate segment is reported as the first SACK block of the next ACK.
  • Sender D-SACK: counted only when it exactly matches a range on the episode's retransmission ledger, once per copy sent; never fed to the scoreboard. Forged D-SACKs do nothing.
  • RACK reo_wnd_mult (RFC 8985 6.2): grows on D-SACK, lasts 16 episodes, capped (window <= SRTT). Once reordering is seen, RACK alone decides losses.
  • Congestion undo (RFC 3708): when D-SACKs cover every retransmission of an episode, cwnd, ssthresh and CUBIC's curve come back - never above their episode-start values, never after ECE or a probe-repaired loss, never after the episode's evidence window (idle restart, one RTO after it ends).
  • Spurious RTO: Eifel (RFC 3522) when timestamps are on, comparing with the first retransmission of any kind (Linux retrans_stamp); SACK-enhanced F-RTO (RFC 5682) otherwise, requiring acks for data never retransmitted.
  • Holding ssthresh on a repeated RTO (a blackout used to cascade 17 RTOs).
  • Sim: NetemChannel delay filter; a stack-level timestamps switch for the F-RTO variant.

Results

A 3 s ACK delay spike used to cost one RTO and cwnd 46456 -> 1460; now the cwnd is restored (46456 with Eifel, 46720 with F-RTO, and via D-SACK when the retransmission's ack overtakes).

Review

An opus security review found three issues, all fixed with tests that failed first: Eifel compared with the RTO retransmission instead of an earlier loss probe (could undo a real loss); F-RTO accepted acks inside the retransmitted segment; the undo snapshot outlived its episode.

Tests

Safety tests: real losses with/without timestamps never undo; CE marks plus a spike never undo; 50 forged D-SACKs count once and change nothing. make test (1279), asan, tsan, strict, SIM_SEEDS=10000 make sim (20018 passed, 0 failed), soak, fuzz 60 s, clang-format, clang-tidy, cppcheck. Bench medians within noise.

🤖 Generated with Claude Code

KoganTheDev and others added 30 commits November 19, 2026 12:22
The working limits move from the static constants (now only the defaults)
to _send_capacity / _receive_capacity, used by _advertised_window(), the
window-reopen threshold, the reorder-buffer bound (via the window) and
send_space_available(). Setters clamp to [max(4 KiB, 2*MSS), 16 MiB]; a
shrunk receive capacity never moves the advertised right edge left.
receive_capacity_locked() is exposed for a later autotuning step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Plumbed like TCP_NODELAY: Socket fields, setsockopt/getsockopt cases,
_apply_options, inheritance from a listener. getsockopt returns double the
(clamped) value set, as Linux does; the payload capacity is the undoubled
value. Setting SO_RCVBUF marks the receive capacity locked for the later
autotuning step. UDP stores and reads back but does not apply (its queue is
bounded by datagram count). KernelStack already forwards the options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A connection that only receives had no RTT estimate at all: the sender's
comes from acks of its own data. Receive autotuning needs one. Measured as
Linux's tcp_rcv_rtt_measure_ts / tcp_rcv_rtt_measure: with timestamps,
now minus the echoed TSval (turned back onto this connection's clock) on a
full-sized segment advancing RCV.NXT, each echo once, smoothed with gain
1/8; without, the time RCV.NXT takes to reach RCV.NXT + RCV.WND as noted
when the measurement started, kept as a running minimum because a sender
that is not window-limited makes it longer than the RTT.

WINDOW_SCALE_SHIFT becomes public so tests can read a scaled window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fixed receive buffer caps a connection at capacity / RTT. As Linux's
tcp_rcv_space_adjust: once per receiver RTT (every 200 ms until there is
a sample) read() compares what the application read in that interval with
the largest such count so far; if it is larger, the capacity grows to
2 * read + 16 segments, plus twice the relative growth while the rate is
climbing, bounded by MAX_BUFFER_CAPACITY. Never when locked (SO_RCVBUF),
never without window scaling. Capacity only grows, so the advertised edge
never moves left; a growth that at least doubles the offered window is
announced at once, as tcp_cleanup_rbuf does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unless the application set SO_SNDBUF, the send capacity follows
max(SEND_BUFFER_CAPACITY, 2 * cwnd), bounded by MAX_BUFFER_CAPACITY,
checked on every ack in ESTABLISHED and CLOSE_WAIT: a full window in
flight while the next is already queued. The new room reaches a waiting
writer through the send-space callback (EPOLLOUT). TcpConnection gets
set_send_capacity_locked(), which ustack sets with SO_SNDBUF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Like Linux's tcp_mem: each NetworkStack holds a TcpMemoryBudget (64 MiB by
default, set_tcp_memory_limit()) that autotuning's growth above the
default capacities is drawn from, per connection and per buffer, with
partial grants. Once it is spent no connection grows further; nothing is
shrunk, so no offered window is taken back. A connection gives its share
back on reaching TIME_WAIT or CLOSED, when it is destroyed, and when the
application sets that capacity itself (which is not counted).

Tested with 100 connections growing at once through stacks whose budgets
cover a fraction of what they want.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Releasing autotuning's whole charge on TIME_WAIT/CLOSED gave back memory
that unread (or unacked) data could still be holding: many connections
parked with full unread buffers would exceed the stack-wide cap. Now
those states keep the part of each charge that the bytes still buffered
occupy beyond the default capacity, and give it back as read() drains
them; destruction (reaping) releases the rest, as before.

Found by an automated security review (MEDIUM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WINDOW_SCALE_SHIFT was a fixed 1, capping every window at 128 KiB - and
so autotuning, whatever the buffer grew to. It is now the smallest shift
with which the 16-bit field describes MAX_BUFFER_CAPACITY, computed the
way Linux's tcp_select_initial_window() does from tcp_rmem[2]: 9 for
16 MiB (0xFFFF << 8 falls 256 bytes short). Linux's default 7 comes from
its 6 MiB tcp_rmem[2]. Scaling now rounds the window to 512-byte units,
so an edge already offered is rounded up rather than pulled back.

The .pkt scripts' expected SYN options say wscale 9; the reorder and
duplicate-ack tests read the window through the constant and use
segments large enough to show at the new resolution. SYN cookies are
unaffected: a cookie SYN-ACK offers no window scale (the cookie cannot
remember one), and existing tests tell cookie SYN-ACKs apart by exactly
that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Rounding the scaled window up to keep an offered edge recorded the
rounded edge as the new promise, so the next ack rounded up from there:
a peer sending exactly to each advertised edge in non-unit sizes walked
the edge forward by up to 511 bytes per ack, past the buffer without
bound (with shift 9). Now only the rounded-down window is a promise;
the edge actually sent is tracked apart and only widens what is
accepted, so it stays within one unit of the promise. The sent edge may
then retreat by less than a unit, which RFC 7323 2.4 allows; the
promised edge (C1's no-shrink rule) still never moves left.

Defense in depth: in-order data is now trimmed to the acceptance window
(RFC 9293 3.10.7.4) instead of being taken whole, so buffered bytes
stay within the promised edge plus one unit - the capacity plus one
unit, or the edge promised before a capacity shrink. A coalesced-
retransmission test that relied on taking 71 KB through a 64 KiB
window now stays inside it.

Found by an automated security review (HIGH).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INITIAL_SSTHRESH was 64 KiB, so slow start ended at 45 segments on any
path. Harmless while windows were capped near 64 KiB; with window scale 9
and autotuning it became the limit - on a 100 Mbit/s, 100 ms path the
sender left slow start at a twentieth of the bandwidth-delay product and
CUBIC took seconds to climb from there (15% of the link where the
throughput test that follows expects 70%). RFC 5681 asks for the largest
possible advertised window; it is now MAX_CWND, as Linux uses infinity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mark_losses() ran on every ack with SACK in use and walked the whole
scoreboard even when nothing was SACKed, so nothing could be marked:
O(flight) per ack on a lossless path. With windows of thousands of
segments (window scale 9, autotuning) that was most of the sender's
work - 4.2 million entry visits for one lossless 8 MiB transfer over a
100 Mbit/s, 100 ms link, 11 thousand after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
100 Mbit/s (12500 bytes/ms), 50 ms each way, 8 MiB. With autotuning the
second half of the transfer runs at >= 70% of the link (95% measured);
with the receive capacity locked at 128 KiB it stays near 128 KiB per
round trip (9.4% of the link). A third run with a 300-frame bottleneck
recovers from slow-start overshoot at a window of hundreds of segments
without a timeout. The steady-state rate is asserted rather than the
whole-transfer one: from a 10-segment initial window, slow start alone
takes about seven round trips to reach the 1.25 MB bandwidth-delay
product, which no buffer policy changes.

Suite SimThroughput, not *SimTransfer*: that pattern is the seeded sweep
(make sim, ctest label sim) that runs each matching test once per seed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SO_RCVBUF / SO_SNDBUF on a connected TCP socket now read the
connection's capacity as it is now - autotuning's growth included -
rather than the value last set, doubled as before; Linux reports
sk_rcvbuf / sk_sndbuf the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…emory cap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With INITIAL_SSTHRESH uncapped, nothing stopped a lossless connection
that never fills its window (request/response, trickle) from growing
cwnd by every byte acked, forever, and _tune_send_capacity charged
2 * cwnd of it - up to 16 MiB per connection - to the 64 MiB stack
budget. A few light connections could starve the busy ones.

CongestionControl::on_ack now takes the flight as the ack arrived
(prior_in_flight, sampled before SACK or cumulative retirement) and
grows only when is_cwnd_limited(): in slow start in-flight * 2 >= cwnd
(Linux: cwnd < 2 * max_packets_out), past ssthresh in-flight >= cwnd
minus one MSS (RFC 7661's idea). The check sits in the base class, so
Reno and CUBIC both get it. CUBIC pauses its epoch clock across an
app-limited stretch (as Linux does after idle), so the curve does not
come back far ahead and close the gap in one burst.

_tune_send_capacity grows only after an ack that found the sender
cwnd-limited, so a window grown in an earlier bulk phase no longer
pulls the buffer up for a connection that has gone quiet.

New tests: CongestionControl.AnAppLimitedSenderDoesNotGrowTheWindow,
CongestionControl.CubicDoesNotCountAnAppLimitedStretchAsGrowthTime,
TcpAutotune.AnAppLimitedConnectionKeepsItsWindowAndSendBuffer (500
request/response rounds: cwnd stays at IW, send buffer at 128 KiB;
before this it reached 2 MB of cwnd).

Test changes in test_congestion_control.cpp, all of which modelled an
app-limited sender while expecting growth:
- acknowledge() defaulted in_flight to 0. It now defaults to
  FULL_WINDOW, meaning cc.window() at each ack, i.e. a bulk sender.
  Every test using it (slow start doubling, established_at setup, fast
  convergence) means a bulk sender.
- CubicGrowthIsDrivenByElapsedTime, RenoGrowthIgnoresElapsedTime,
  TheTcpFriendlyRegion and FastConvergence passed a fixed in-flight
  (the window they started at) while cwnd grew past it, which would now
  stop growth one MSS later. They pass each flow's current window.
  The unused started_at locals went with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
_acceptance_window() took the larger of the advertised window and
_rcv_wire_edge_unwrapped, the highest edge the rounded-up scaled field
had ever carried, kept as a monotonic max. Once RCV.NXT reached the
promised edge and the window went to 0, up to 511 bytes past it were
still accepted - including a zero-window probe's byte - so the receive
queue grew past its capacity.

Acceptance is now _advertised_window(): the free space, or the promised
edge, whichever is further. The wire edge is gone. Under a zero window
nothing past RCV.NXT is queued, so a probe is acked with window 0 and
dropped (RFC 9293 3.8.6.1). RFC 7323 2.4's tolerance for data sent
before a retreat of less than one unit is kept as far as the buffer has
room - free space is part of the advertised window, so such bytes are
accepted whenever the application has read since; otherwise they are
trimmed and resent, never queued past the capacity. (Clipping the old
wire-edge term to the free space would give the same result, since the
advertised window already includes all free space.)

New test: TcpAutotune.AZeroWindowProbeIsAckedButNotQueued (full buffer
behind a rounded-up edge, zero window, a 1-byte probe: not queued, the
ack carries window 0 and the old RCV.NXT, buffered <= capacity; before
the fix 131073 of 131072 bytes were buffered).

Test changed: RoundingUpTheScaledWindowNeverGrowsTheBufferPastCapacity
bounded the buffer at capacity plus one scale unit, which encoded the
slack the wire edge allowed. The bound is now the capacity itself (the
old code reached 131434 of 131072 under it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
set_delay_filter is the counterpart of the drop filter: it returns extra
one-way delay per frame, draws no random numbers, and lets later frames
overtake the delayed one. SimRecovery.ADelaySpikeCausesASpuriousTimeout_Baseline
records today's behaviour under a 3 s ACK delay (RTO, cwnd cut, spurious
retransmission); the D2 step flips it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A data segment entirely below RCV.NXT, or inside data the reorder buffer
already holds, is remembered (only the duplicate part when the segment was
partly old) and the next ack leads with it as its first SACK block; when it
lies in an out-of-order range that range is the second block. Reported once,
only with SACK negotiated, counted in Stats::dsacks_sent. Two existing
overlap tests now see the D-SACK block ahead of the union.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nsmissions

RFC 2883 section 4: the first SACK block is a D-SACK if it lies below the
cumulative ack or inside the second block. It is taken out of the blocks
the scoreboard sees and matched against a per-episode ledger of what was
retransmitted (current and last episode): it counts only if it names
exactly one or more consecutive retransmitted ranges, each with a copy
not yet reported. Stats::dsacks_received. A D-SACK for a retransmitted
loss probe means both copies arrived, so the probe repaired nothing
(RFC 8985 7.4.2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
reo_wnd = min(reo_wnd_mult * min_RTT / 4, SRTT). A D-SACK that counted
grows the multiplier by one, at most once per round trip
(RACK.dsack_round), and marks the path as reordering; the wider window
lasts 16 episodes (RACK.reo_wnd_persist), then falls back to 1.

Once reordering has been seen RACK alone decides losses, as Linux does:
the DupThresh rule (three SACKed above a hole) is exactly what
reordering looks like, and would resend whatever the window says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…708)

CongestionControl gains save_for_undo() / undo() / forget_undo(): the
snapshot is taken where an episode starts, before its reduction, and an
undo restores cwnd and ssthresh (never below their current values, as
Linux's tcp_undo_cwnd_reduction()) and CUBIC's curve, its epoch shifted
by the episode's length.

The connection undoes an episode once it is over and D-SACKs have
reported every copy on its ledger - repeated copies and the loss probe
included (Linux's undo_retrans). An ECN-Echo or a probe-repaired loss
forgets the snapshot, so such an episode is never undone; an undo of
an episode with a timeout also resets the RTO back-off
(RttEstimator::reset_backoff()). Stats::spurious_recoveries_undone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TcpConnection::set_timestamps_enabled() and
NetworkStack::set_tcp_timestamps(): with it off, a SYN offers no TSopt
and a peer's is declined, so the connection runs without timestamps.
Needed to exercise loss recovery on the paths that only apply without
them (F-RTO).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At a timeout that starts an episode: with timestamps, Eifel (RFC 3522,
Linux's tcp_packet_delayed()) - the first ack for new data echoing a
TSval older than the retransmission's (per-pair clock) means the
original arrived. Without timestamps but with SACK, SACK-enhanced F-RTO
(RFC 5682 3.1, tcp_frto = 2): a first ack for part of the flight sends
up to two new segments instead of retransmissions; a second ack for new
data proves the timeout spurious, a duplicate falls back to
conventional recovery, an ack covering the whole flight stops it. Not
while a loss-probe retransmission is outstanding, and not for a
repeated timeout.

Both go through one undo path: the congestion snapshot back, RTO
recovery left, the loss marks taken back (RACK.segment forgotten - it
was the ambiguous retransmission), the RTO back-off reset. An episode
that saw ECN-Echo is not undone. Stats::spurious_rtos_undone.

SimRecovery: the baseline becomes ADelaySpikeTimeoutIsUndone, a 1 s
spike that ends after the retransmission reached the receiver, run with
timestamps (Eifel) and with SACK only (F-RTO): one RTO, undone, cwnd
back to 46456 / 46720 bytes, no further retransmission. The original
3 s spike, where the retransmission's ack overtakes the delayed ones,
is undone by its D-SACK when timestamps are off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A timeout inside an episode that already had one collapses cwnd to one
segment again but keeps ssthresh and CUBIC's curve, as RFC 5681 3.1 has
it for a segment the timer already resent and Linux's tcp_enter_loss()
does in the Loss state. The window that timed out the second time is the
slow start after the first, not the path's capacity; reducing from it
left ssthresh at two segments.

Found by the real-loss safety test: a blackout of new data after an RTO
makes F-RTO's two new segments vanish, so a second RTO follows, and with
ssthresh cut again from the two-segment window the repair crawled in
congestion avoidance - a cascade of backed-off RTOs (17 in 600 s of
virtual time). Now 3 RTOs and under 3 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eep property

- SimRecovery.ARealLossIsNeverUndone: several losses in one flight, a lost
  retransmission, a tail loss and a blackout repaired by RTO, with and
  without timestamps: no undo of either kind.
- SimRecovery.CeMarksDuringASpuriousTimeoutKeepItsReduction: the delay
  spike that is otherwise undone, on a path marking CE: not undone.
- TcpDsackForgery: D-SACKs for data never resent, below the ISN, the whole
  flight, part of a segment, inverted, above SND.NXT, and the genuine one
  50 times: one count, no undo, reo_wnd_mult at most 2.
- SimTransfer (every seed): an undo never raises cwnd above the window its
  episode started with (it may leave a window already grown past it).
- fuzz: the stack harness fixes its secrets (stack_seed.h) so its ISN is
  known and inputs replay identically; gen_corpus adds seeds with the
  genuine D-SACK repeated and with forged ones after a timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Moves them out of "Deliberately out of scope": the feature list now
describes D-SACK acceptance, the reordering window, the detection
order for a timeout (Eifel, then F-RTO, then D-SACK alone) and the undo
safety rules. What stays out of scope: no D-SACK without SACK, and
D-SACK's blind spot for network duplication. The fuzzing section notes
the stack harness's fixed secrets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…conditions)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Eifel armed with the TSval of the timeout's own retransmission. When a
loss probe had already resent the segment and repaired the loss, the
probe's ack - delayed past the RTO - echoed the probe's older TSval and
the reduction for a real loss was undone. Like Linux's retrans_stamp,
the stamp is now the TSval of the earliest retransmission of any kind
whose data is not yet all acknowledged, and Eifel compares against it.
(Not arming Eifel while a probe is outstanding would also be safe, but
would give up the case Linux keeps: the original's echo is older than
the probe's too, and still proves the timeout spurious.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
KoganTheDev and others added 2 commits November 19, 2026 19:47
Any ack advancing SND.UNA passed step 2 and proved the timeout spurious
at step 3, so a peer acking a few bytes of the retransmitted segment at
a time undid a real loss's reduction. Step 2 now falls back unless the
ack covers the whole retransmitted segment (2a), and step 3 undoes only
for an ack above it - data that was sent once (3b); any other ack falls
back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A finished episode's snapshot stayed valid until the next episode, so a
D-SACK arriving much later - after an idle restart, say - restored the
pre-idle window as a burst. The snapshot is now forgotten on an idle
restart (CongestionControl::on_idle_restart()) and one RTO after the
episode ends, by when its copies' D-SACKs have come back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@KoganTheDev
KoganTheDev changed the base branch from feat/buffers to main November 19, 2026 22:16
@KoganTheDev
KoganTheDev merged commit 8ac5848 into main Nov 19, 2026
16 checks passed
@KoganTheDev
KoganTheDev deleted the feat/recovery branch November 19, 2026 22:16
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