Loading src/quic.cpp +22 −170 Changes for src/quic.cpp: 22 added lines, 170 removed lines. Original line number Diff line number Diff line Loading @@ -41,7 +41,6 @@ #include <thread> #include <chrono> #include <cstdio> #include <cstdlib> #include <cmath> #define QUIC_DBG(fmt, ...) do { } while(0) Loading Loading @@ -77,29 +76,6 @@ ThreadPool& quicDispatchPool() { static ThreadPool pool((std::max<unsigned>)(4, std::thread::hardware_concurrency() * 2)); return pool; } // TEMP diagnostic counters (throughput investigation) — remove before done. std::atomic<uint64_t> g_stat_sendPacket{0}; std::atomic<uint64_t> g_stat_sendmmsg_batch{0}; std::atomic<uint64_t> g_stat_pto_retransmit{0}; std::atomic<uint64_t> g_stat_loss_retransmit{0}; std::atomic<uint64_t> g_stat_app_acks{0}; std::atomic<uint64_t> g_stat_stream_data_pkts{0}; std::atomic<uint64_t> g_stat_cwnd_blocked{0}; const bool g_cwnd_trace = std::getenv("QUIC_CWND_TRACE") != nullptr; struct StatsPrinter { ~StatsPrinter() { fprintf(stderr, "[QUIC STATS] sendPacket=%lu batch=%lu pto_retx=%lu loss_retx=%lu acks=%lu stream_pkts=%lu cwnd_blocked=%lu\n", (unsigned long)g_stat_sendPacket.load(), (unsigned long)g_stat_sendmmsg_batch.load(), (unsigned long)g_stat_pto_retransmit.load(), (unsigned long)g_stat_loss_retransmit.load(), (unsigned long)g_stat_app_acks.load(), (unsigned long)g_stat_stream_data_pkts.load(), (unsigned long)g_stat_cwnd_blocked.load()); } } g_stats_printer; } // namespace // ============================================================================ Loading Loading @@ -317,7 +293,6 @@ void quic::generateConnectionId(std::vector<uint8_t>& cid, size_t len) { // ============================================================================ ssize_t quic::sendPacket(const uint8_t* data, size_t len) { g_stat_sendPacket++; if (_Socket < 0) { QUIC_DBG("sendPacket: _Socket < 0, dropping %zu bytes", len); return -1; Loading Loading @@ -432,11 +407,10 @@ void quic::processApplicationPacketsBatch( } trackRecvPN(pn, _app_pn_recv_ranges); // Defer ACK across the whole batch — flushed once below (subject to // the delayed-ACK policy in flushAckIfDue()), or piggybacked sooner // if frame processing triggers an outgoing data packet — so N // packets arriving in one recv cycle cost at most one ACK, not N. markAckPending(); // Defer ACK across the whole batch — sent once below (or piggybacked // sooner if frame processing triggers an outgoing data packet), so N // packets arriving in one recv cycle cost one ACK instead of N. _app_ack_pending = true; size_t offset = 0; while (offset < payload.size()) { Loading @@ -444,7 +418,10 @@ void quic::processApplicationPacketsBatch( } } flushAckIfDue(); if (_app_ack_pending) { sendAppAck(); _app_ack_pending = false; } } // ============================================================================ Loading @@ -455,9 +432,7 @@ bool quic::cwndAllowsSend(size_t packet_size) const { // RFC 9002: A sender MUST be able to send at least one minimum-sized // datagram when nothing is in flight, even if it exceeds cwnd. if (_bytes_in_flight == 0) return true; bool allowed = _bytes_in_flight + packet_size <= _cwnd; if (!allowed) g_stat_cwnd_blocked++; return allowed; return _bytes_in_flight + packet_size <= _cwnd; } void quic::onPacketSentCC(size_t packet_size) { Loading Loading @@ -485,9 +460,6 @@ void quic::onPacketAckedCC(size_t packet_size, uint64_t pn) { // Approximation: cwnd += MTU * packet_size / cwnd _cwnd += (1472 * packet_size) / _cwnd; } if (g_cwnd_trace) fprintf(stderr, "[CWND] %c ACK pn=%-8lu cwnd=%-8lu ssthresh=%-10lu bif=%-8lu\n", _is_server ? 'S' : 'C', (unsigned long)pn, (unsigned long)_cwnd, (unsigned long)_ssthresh, (unsigned long)_bytes_in_flight); } void quic::onPacketLostCC(size_t packet_size, uint64_t pn) { Loading @@ -504,9 +476,6 @@ void quic::onPacketLostCC(size_t packet_size, uint64_t pn) { // Multiplicative decrease _ssthresh = std::max(_cwnd / 2, MIN_CWND); _cwnd = _ssthresh; if (g_cwnd_trace) fprintf(stderr, "[CWND] %c LOSS pn=%-8lu cwnd=%-8lu ssthresh=%-10lu bif=%-8lu\n", _is_server ? 'S' : 'C', (unsigned long)pn, (unsigned long)_cwnd, (unsigned long)_ssthresh, (unsigned long)_bytes_in_flight); } } Loading Loading @@ -1446,7 +1415,6 @@ void quic::handshake_after_accept() { } pmtudTick(); maybeFlushDelayedAck(); } // Collect pending dispatches before releasing lock Loading Loading @@ -1617,12 +1585,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { existing->sendMaxData(existing->_pending_max_data_value); existing->_pending_max_data = false; } // See pumpIncoming()/recvData() for why this matters: a // pending ACK left here for its deadline has no other tick // to flush it, since this drain loop only revisits a given // connection when a NEW datagram for it arrives. existing->pmtudTick(); existing->maybeFlushDelayedAck(); } if (!existing->_pending_dispatches.empty()) { Loading Loading @@ -1796,7 +1759,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { existing->_pending_max_data = false; } existing->pmtudTick(); existing->maybeFlushDelayedAck(); } // Dispatch stream callbacks off-thread (see scheduleDispatches) Loading Loading @@ -1907,7 +1869,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { winner->_pending_max_data = false; } winner->pmtudTick(); winner->maybeFlushDelayedAck(); } if (!winner->_pending_dispatches.empty()) { Loading Loading @@ -1977,7 +1938,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { child_ptr->_pending_max_data = false; } child_ptr->pmtudTick(); child_ptr->maybeFlushDelayedAck(); } // Dispatch any pending child callbacks off-thread (see scheduleDispatches) Loading Loading @@ -2296,16 +2256,19 @@ void quic::processApplicationPacket(const uint8_t* data, size_t len) { trackRecvPN(pn, _app_pn_recv_ranges); // Defer ACK — it will be piggybacked on the next outgoing data packet // (e.g., echo response), flushed below subject to the delayed-ACK // policy, or flushed later by maybeFlushDelayedAck(). markAckPending(); // (e.g., echo response). If no data is sent, flush after frame processing. _app_ack_pending = true; size_t offset = 0; while (offset < payload.size()) { processFrame(payload.data(), payload.size(), offset); } flushAckIfDue(); // If ACK is still pending (no data was sent in response), send standalone ACK if (_app_ack_pending) { sendAppAck(); _app_ack_pending = false; } } // ============================================================================ Loading Loading @@ -3062,21 +3025,8 @@ size_t quic::recvData(buffer& data, int flags) { } } // This is the actual per-packet path the epoll event framework // drives for accepted server connections (see epoll.cpp's // recvData()-in-a-loop dispatch) — unlike pumpNetwork()/ // pumpIncoming()/handshake_after_accept(), it has no other tick // alongside it, so a pending ACK left waiting for its deadline // here would otherwise only get flushed by the event loop's own // (much coarser, ~500ms-scale) timeout tick — far too coarse next // to a delay meant to be ~100-250us on a fast path. Missing this // one spot reproduced as cascading handshake timeouts under // concurrent load (quic_concurrent_test) once delayed-ACK was // added: a stalled ACK here stalls the peer's flow control, which // backs up into the server's worker pool. if (_handshake_complete && _conn_state.load() == ConnectionState::Connected) { pmtudTick(); maybeFlushDelayedAck(); } // Collect pending dispatches before releasing lock Loading Loading @@ -3180,18 +3130,16 @@ void quic::pumpNetwork(int flags) { } } // Path MTU Discovery + delayed-ACK flush: drive both unconditionally // Path MTU Discovery: drive the probe state machine unconditionally // (not just when datagrams just arrived above) so a lost probe's // timeout, or a pending ACK that never got piggybacked, is still // handled on a caller that polls pumpNetwork() in a tight loop without // new data ever showing up. handshake_after_accept() carries the // equivalent ticks for event-loop-driven connections; this is the one // that matters for callers (including these tests) that poll a bare, // non-event-loop quic object directly. // timeout is still detected on a caller that polls pumpNetwork() in a // tight loop without new data ever showing up. handshake_after_accept() // carries the equivalent tick for event-loop-driven connections; this // is the one that matters for callers (including these tests) that // poll a bare, non-event-loop quic object directly. if (_handshake_complete && _conn_state.load() == ConnectionState::Connected) { std::lock_guard<std::recursive_mutex> lock(quic_mtx()); pmtudTick(); maybeFlushDelayedAck(); } } Loading Loading @@ -3763,10 +3711,6 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { if (offset + stream_len > len) return; if (g_cwnd_trace) fprintf(stderr, "[STREAM] %c this=%p sid=%lu off=%lu len=%lu fin=%d\n", _is_server ? 'S' : 'C', (void*)this, (unsigned long)stream_id, (unsigned long)stream_offset, (unsigned long)stream_len, (int)has_fin); // Ignore data for streams that were already fully closed (both FIN sent // and received). Retransmitted packets for erased streams would otherwise // auto-create a new Stream object, inflating _data_recv and potentially Loading Loading @@ -4173,7 +4117,6 @@ void quic::checkLossAndRetransmit() { ssize_t sent = sendPacket(packet.data(), packet.size()); if (sent < 0) sent = sendPacket(packet.data(), packet.size()); if (sent > 0) { g_stat_pto_retransmit++; recordSentPacket(new_pn, sp.stream_id, sp.stream_offset, sp.stream_data.data(), sp.stream_data.size(), sp.fin, packet.size()); Loading Loading @@ -4284,7 +4227,6 @@ void quic::checkLossAndRetransmit() { } if (sent > 0) { g_stat_loss_retransmit++; // Track retransmitted packet under new PN recordSentPacket(new_pn, sp.stream_id, sp.stream_offset, sp.stream_data.data(), sp.stream_data.size(), sp.fin, packet.size()); Loading Loading @@ -4425,86 +4367,11 @@ void quic::sendStreamDataBlocked(uint64_t stream_id, uint64_t limit) { sendPacket(packet.data(), packet.size()); } // ============================================================================ // Delayed ACK (RFC 9000 §13.2.1) // ============================================================================ // Called once per received ack-eliciting application packet (both the // single-packet and batch receive paths). Starts the deadline on the // first packet since the last ACK, so a lone packet with nothing to // piggyback on still gets acked within a bounded delay instead of // waiting indefinitely. // // The delay is RTT-adaptive, not the fixed APP_MAX_ACK_DELAY ceiling: a // fixed 25ms is fine when the path RTT is itself tens of ms (WAN), but // on a loopback/LAN path with sub-millisecond RTT and a congestion // window that only allows 1-2 packets in flight (the common case right // after a loss, or for small/interactive transfers), the peer's next // send is often gated on THIS ack — so a flat 25ms tax turns into a // 25ms tax per round trip, compounding into a multi-second stall over // many round trips (measured: quic_concurrent_test went from ~1s to a // 120s timeout with a flat 25ms delay). Scaling with srtt keeps the // coalescing benefit where it matters (higher-RTT/higher-BDP paths // naturally carry more packets per RTT) without taxing the // stop-and-wait case where it doesn't. void quic::markAckPending() { if (!_app_ack_pending) { _app_ack_pending = true; static const double kCeilingSec = std::chrono::duration<double>(APP_MAX_ACK_DELAY).count(); auto delay = _rtt_initialized ? std::chrono::duration_cast<std::chrono::steady_clock::duration>( std::chrono::duration<double>(std::clamp(0.25 * _srtt, 0.0001, kCeilingSec))) : std::chrono::microseconds(200); _app_ack_deadline = std::chrono::steady_clock::now() + delay; } ++_app_unacked_count; } // Called once per receive cycle (end of processApplicationPacket() / // processApplicationPacketsBatch()): send now if we've accumulated 2+ // unacked packets or a gap is pending (RFC 9000 §13.2.1 — immediate ACK // on reordering/loss so the peer's own loss detection isn't delayed). // Otherwise leave it pending for sendStreamData() to piggyback on the // next outgoing data packet, or for maybeFlushDelayedAck() to flush once // APP_MAX_ACK_DELAY elapses. void quic::flushAckIfDue() { if (!_app_ack_pending) return; bool gap_pending = _app_pn_recv_ranges.size() > 1; bool fire = _app_unacked_count >= 2 || gap_pending; if (g_cwnd_trace) fprintf(stderr, "[ACKFLUSH] %c this=%p unacked=%u gap=%d fire=%d\n", _is_server ? 'S' : 'C', (void*)this, _app_unacked_count, (int)gap_pending, (int)fire); if (fire) { sendAppAck(); _app_ack_pending = false; _app_unacked_count = 0; } } // Called once per pumpNetwork()/handshake_after_accept() tick, alongside // pmtudTick() — flushes a pending ACK that's been waiting for a // piggyback opportunity that never came. void quic::maybeFlushDelayedAck() { if (!_app_ack_pending) return; bool due = std::chrono::steady_clock::now() >= _app_ack_deadline; if (g_cwnd_trace) fprintf(stderr, "[ACKDEADLINE] %c this=%p due=%d\n", _is_server ? 'S' : 'C', (void*)this, (int)due); if (due) { sendAppAck(); _app_ack_pending = false; _app_unacked_count = 0; } } // ============================================================================ // ACK: Send ACK frame for 1-RTT application packets // ============================================================================ void quic::sendAppAck() { g_stat_app_acks++; if (g_cwnd_trace) fprintf(stderr, "[SENDACK] %c this=%p largest=%lu ranges=%zu\n", _is_server ? 'S' : 'C', (void*)this, (unsigned long)_app_pn_recv, _app_pn_recv_ranges.size()); std::vector<uint8_t> frame = buildAckFrame(_app_pn_recv, 0, _app_pn_recv_ranges); std::vector<uint8_t> packet = buildShortHeaderPacket(frame); Loading Loading @@ -5429,7 +5296,6 @@ size_t quic::sendStreamData(uint64_t stream_id, const uint8_t* data, size_t len, vlen = encodeVarInt(0, vbuf); std::memcpy(pkt_buf + frame_off, vbuf, vlen); frame_off += vlen; } _app_ack_pending = false; _app_unacked_count = 0; } uint8_t frame_type = 0x08 | 0x02; // LEN always set Loading Loading @@ -5870,11 +5736,7 @@ void quic::pumpIncoming() { t->sendMaxData(t->_pending_max_data_value); t->_pending_max_data = false; } // Same delayed-ACK/PMTUD tick as the self case below — a // routed child connection needs its pending-ACK deadline // checked too, not just `this`. t->pmtudTick(); t->maybeFlushDelayedAck(); } } Loading @@ -5891,17 +5753,7 @@ void quic::pumpIncoming() { _pending_max_data = false; } // Flush a pending ACK that never got piggybacked or hit the // 2-packet threshold. Without this, a caller that only ever // drives this connection through pumpIncoming() (sendStreamData()'s // congestion-window-wait loop is exactly that caller) never checks // the delayed-ACK deadline at all — a lone unacked packet with no // reply to piggyback on then waits forever, stalling the peer's // flow control on an ACK that never comes (reproduced as a hang in // quic_concurrent_test). pmtudTick() belongs here for the same // reason, even though it's a no-op at the default ceiling. pmtudTick(); maybeFlushDelayedAck(); } // After processing incoming packets (which may contain ACKs), Loading src/socket.h +1 −23 Changes for src/socket.h: 1 added line, 23 removed lines. Original line number Diff line number Diff line Loading @@ -875,30 +875,8 @@ namespace netplus { uint64_t _handshake_pn_recv = 0; uint64_t _app_pn_send = 0; uint64_t _app_pn_recv = 0; uint32_t _app_unacked_count = 0; // Delayed ACK counter — ack-eliciting packets // received since the last ACK was sent (see // maybeFlushDelayedAck() / APP_MAX_ACK_DELAY). uint32_t _app_unacked_count = 0; // Delayed ACK counter bool _app_ack_pending = false; // Deferred ACK flag std::chrono::steady_clock::time_point _app_ack_deadline; // when a pending ACK must be flushed static constexpr std::chrono::milliseconds APP_MAX_ACK_DELAY{25}; // RFC 9000 §13.2.1-ish default // Delayed ACK (RFC 9000 §13.2.1): send a standalone ACK immediately // on every 2nd ack-eliciting packet or when a gap is detected, but // otherwise let it wait for either a data packet to piggyback on // (see sendStreamData's ack_reserve/piggyback logic) or this // deadline — called once per pumpNetwork()/handshake_after_accept() // tick, alongside pmtudTick(). Without this, every received packet // (batches are frequently size 1 under load — see pumpIncoming's // batching comment) cost its own standalone ACK datagram: measured // at ~97% of all sendto() calls in benchmark_quic being ACK-only, // which — since ACK-only packets consume packet numbers from the // same space checkLossAndRetransmit()/onPacketLostCC() use to decide // when a post-loss recovery period ends (_recovery_start_pn) — also // froze congestion-window growth for far more round trips than one // true RTT after any single loss. void maybeFlushDelayedAck(); void markAckPending(); // called once per received ack-eliciting packet void flushAckIfDue(); // called once per receive cycle (batch or single packet) // Received packet-number ranges (inclusive) for proper ACK encoding // Each pair is [lo, hi] representing contiguous received PNs. Loading Loading
src/quic.cpp +22 −170 Changes for src/quic.cpp: 22 added lines, 170 removed lines. Original line number Diff line number Diff line Loading @@ -41,7 +41,6 @@ #include <thread> #include <chrono> #include <cstdio> #include <cstdlib> #include <cmath> #define QUIC_DBG(fmt, ...) do { } while(0) Loading Loading @@ -77,29 +76,6 @@ ThreadPool& quicDispatchPool() { static ThreadPool pool((std::max<unsigned>)(4, std::thread::hardware_concurrency() * 2)); return pool; } // TEMP diagnostic counters (throughput investigation) — remove before done. std::atomic<uint64_t> g_stat_sendPacket{0}; std::atomic<uint64_t> g_stat_sendmmsg_batch{0}; std::atomic<uint64_t> g_stat_pto_retransmit{0}; std::atomic<uint64_t> g_stat_loss_retransmit{0}; std::atomic<uint64_t> g_stat_app_acks{0}; std::atomic<uint64_t> g_stat_stream_data_pkts{0}; std::atomic<uint64_t> g_stat_cwnd_blocked{0}; const bool g_cwnd_trace = std::getenv("QUIC_CWND_TRACE") != nullptr; struct StatsPrinter { ~StatsPrinter() { fprintf(stderr, "[QUIC STATS] sendPacket=%lu batch=%lu pto_retx=%lu loss_retx=%lu acks=%lu stream_pkts=%lu cwnd_blocked=%lu\n", (unsigned long)g_stat_sendPacket.load(), (unsigned long)g_stat_sendmmsg_batch.load(), (unsigned long)g_stat_pto_retransmit.load(), (unsigned long)g_stat_loss_retransmit.load(), (unsigned long)g_stat_app_acks.load(), (unsigned long)g_stat_stream_data_pkts.load(), (unsigned long)g_stat_cwnd_blocked.load()); } } g_stats_printer; } // namespace // ============================================================================ Loading Loading @@ -317,7 +293,6 @@ void quic::generateConnectionId(std::vector<uint8_t>& cid, size_t len) { // ============================================================================ ssize_t quic::sendPacket(const uint8_t* data, size_t len) { g_stat_sendPacket++; if (_Socket < 0) { QUIC_DBG("sendPacket: _Socket < 0, dropping %zu bytes", len); return -1; Loading Loading @@ -432,11 +407,10 @@ void quic::processApplicationPacketsBatch( } trackRecvPN(pn, _app_pn_recv_ranges); // Defer ACK across the whole batch — flushed once below (subject to // the delayed-ACK policy in flushAckIfDue()), or piggybacked sooner // if frame processing triggers an outgoing data packet — so N // packets arriving in one recv cycle cost at most one ACK, not N. markAckPending(); // Defer ACK across the whole batch — sent once below (or piggybacked // sooner if frame processing triggers an outgoing data packet), so N // packets arriving in one recv cycle cost one ACK instead of N. _app_ack_pending = true; size_t offset = 0; while (offset < payload.size()) { Loading @@ -444,7 +418,10 @@ void quic::processApplicationPacketsBatch( } } flushAckIfDue(); if (_app_ack_pending) { sendAppAck(); _app_ack_pending = false; } } // ============================================================================ Loading @@ -455,9 +432,7 @@ bool quic::cwndAllowsSend(size_t packet_size) const { // RFC 9002: A sender MUST be able to send at least one minimum-sized // datagram when nothing is in flight, even if it exceeds cwnd. if (_bytes_in_flight == 0) return true; bool allowed = _bytes_in_flight + packet_size <= _cwnd; if (!allowed) g_stat_cwnd_blocked++; return allowed; return _bytes_in_flight + packet_size <= _cwnd; } void quic::onPacketSentCC(size_t packet_size) { Loading Loading @@ -485,9 +460,6 @@ void quic::onPacketAckedCC(size_t packet_size, uint64_t pn) { // Approximation: cwnd += MTU * packet_size / cwnd _cwnd += (1472 * packet_size) / _cwnd; } if (g_cwnd_trace) fprintf(stderr, "[CWND] %c ACK pn=%-8lu cwnd=%-8lu ssthresh=%-10lu bif=%-8lu\n", _is_server ? 'S' : 'C', (unsigned long)pn, (unsigned long)_cwnd, (unsigned long)_ssthresh, (unsigned long)_bytes_in_flight); } void quic::onPacketLostCC(size_t packet_size, uint64_t pn) { Loading @@ -504,9 +476,6 @@ void quic::onPacketLostCC(size_t packet_size, uint64_t pn) { // Multiplicative decrease _ssthresh = std::max(_cwnd / 2, MIN_CWND); _cwnd = _ssthresh; if (g_cwnd_trace) fprintf(stderr, "[CWND] %c LOSS pn=%-8lu cwnd=%-8lu ssthresh=%-10lu bif=%-8lu\n", _is_server ? 'S' : 'C', (unsigned long)pn, (unsigned long)_cwnd, (unsigned long)_ssthresh, (unsigned long)_bytes_in_flight); } } Loading Loading @@ -1446,7 +1415,6 @@ void quic::handshake_after_accept() { } pmtudTick(); maybeFlushDelayedAck(); } // Collect pending dispatches before releasing lock Loading Loading @@ -1617,12 +1585,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { existing->sendMaxData(existing->_pending_max_data_value); existing->_pending_max_data = false; } // See pumpIncoming()/recvData() for why this matters: a // pending ACK left here for its deadline has no other tick // to flush it, since this drain loop only revisits a given // connection when a NEW datagram for it arrives. existing->pmtudTick(); existing->maybeFlushDelayedAck(); } if (!existing->_pending_dispatches.empty()) { Loading Loading @@ -1796,7 +1759,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { existing->_pending_max_data = false; } existing->pmtudTick(); existing->maybeFlushDelayedAck(); } // Dispatch stream callbacks off-thread (see scheduleDispatches) Loading Loading @@ -1907,7 +1869,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { winner->_pending_max_data = false; } winner->pmtudTick(); winner->maybeFlushDelayedAck(); } if (!winner->_pending_dispatches.empty()) { Loading Loading @@ -1977,7 +1938,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { child_ptr->_pending_max_data = false; } child_ptr->pmtudTick(); child_ptr->maybeFlushDelayedAck(); } // Dispatch any pending child callbacks off-thread (see scheduleDispatches) Loading Loading @@ -2296,16 +2256,19 @@ void quic::processApplicationPacket(const uint8_t* data, size_t len) { trackRecvPN(pn, _app_pn_recv_ranges); // Defer ACK — it will be piggybacked on the next outgoing data packet // (e.g., echo response), flushed below subject to the delayed-ACK // policy, or flushed later by maybeFlushDelayedAck(). markAckPending(); // (e.g., echo response). If no data is sent, flush after frame processing. _app_ack_pending = true; size_t offset = 0; while (offset < payload.size()) { processFrame(payload.data(), payload.size(), offset); } flushAckIfDue(); // If ACK is still pending (no data was sent in response), send standalone ACK if (_app_ack_pending) { sendAppAck(); _app_ack_pending = false; } } // ============================================================================ Loading Loading @@ -3062,21 +3025,8 @@ size_t quic::recvData(buffer& data, int flags) { } } // This is the actual per-packet path the epoll event framework // drives for accepted server connections (see epoll.cpp's // recvData()-in-a-loop dispatch) — unlike pumpNetwork()/ // pumpIncoming()/handshake_after_accept(), it has no other tick // alongside it, so a pending ACK left waiting for its deadline // here would otherwise only get flushed by the event loop's own // (much coarser, ~500ms-scale) timeout tick — far too coarse next // to a delay meant to be ~100-250us on a fast path. Missing this // one spot reproduced as cascading handshake timeouts under // concurrent load (quic_concurrent_test) once delayed-ACK was // added: a stalled ACK here stalls the peer's flow control, which // backs up into the server's worker pool. if (_handshake_complete && _conn_state.load() == ConnectionState::Connected) { pmtudTick(); maybeFlushDelayedAck(); } // Collect pending dispatches before releasing lock Loading Loading @@ -3180,18 +3130,16 @@ void quic::pumpNetwork(int flags) { } } // Path MTU Discovery + delayed-ACK flush: drive both unconditionally // Path MTU Discovery: drive the probe state machine unconditionally // (not just when datagrams just arrived above) so a lost probe's // timeout, or a pending ACK that never got piggybacked, is still // handled on a caller that polls pumpNetwork() in a tight loop without // new data ever showing up. handshake_after_accept() carries the // equivalent ticks for event-loop-driven connections; this is the one // that matters for callers (including these tests) that poll a bare, // non-event-loop quic object directly. // timeout is still detected on a caller that polls pumpNetwork() in a // tight loop without new data ever showing up. handshake_after_accept() // carries the equivalent tick for event-loop-driven connections; this // is the one that matters for callers (including these tests) that // poll a bare, non-event-loop quic object directly. if (_handshake_complete && _conn_state.load() == ConnectionState::Connected) { std::lock_guard<std::recursive_mutex> lock(quic_mtx()); pmtudTick(); maybeFlushDelayedAck(); } } Loading Loading @@ -3763,10 +3711,6 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { if (offset + stream_len > len) return; if (g_cwnd_trace) fprintf(stderr, "[STREAM] %c this=%p sid=%lu off=%lu len=%lu fin=%d\n", _is_server ? 'S' : 'C', (void*)this, (unsigned long)stream_id, (unsigned long)stream_offset, (unsigned long)stream_len, (int)has_fin); // Ignore data for streams that were already fully closed (both FIN sent // and received). Retransmitted packets for erased streams would otherwise // auto-create a new Stream object, inflating _data_recv and potentially Loading Loading @@ -4173,7 +4117,6 @@ void quic::checkLossAndRetransmit() { ssize_t sent = sendPacket(packet.data(), packet.size()); if (sent < 0) sent = sendPacket(packet.data(), packet.size()); if (sent > 0) { g_stat_pto_retransmit++; recordSentPacket(new_pn, sp.stream_id, sp.stream_offset, sp.stream_data.data(), sp.stream_data.size(), sp.fin, packet.size()); Loading Loading @@ -4284,7 +4227,6 @@ void quic::checkLossAndRetransmit() { } if (sent > 0) { g_stat_loss_retransmit++; // Track retransmitted packet under new PN recordSentPacket(new_pn, sp.stream_id, sp.stream_offset, sp.stream_data.data(), sp.stream_data.size(), sp.fin, packet.size()); Loading Loading @@ -4425,86 +4367,11 @@ void quic::sendStreamDataBlocked(uint64_t stream_id, uint64_t limit) { sendPacket(packet.data(), packet.size()); } // ============================================================================ // Delayed ACK (RFC 9000 §13.2.1) // ============================================================================ // Called once per received ack-eliciting application packet (both the // single-packet and batch receive paths). Starts the deadline on the // first packet since the last ACK, so a lone packet with nothing to // piggyback on still gets acked within a bounded delay instead of // waiting indefinitely. // // The delay is RTT-adaptive, not the fixed APP_MAX_ACK_DELAY ceiling: a // fixed 25ms is fine when the path RTT is itself tens of ms (WAN), but // on a loopback/LAN path with sub-millisecond RTT and a congestion // window that only allows 1-2 packets in flight (the common case right // after a loss, or for small/interactive transfers), the peer's next // send is often gated on THIS ack — so a flat 25ms tax turns into a // 25ms tax per round trip, compounding into a multi-second stall over // many round trips (measured: quic_concurrent_test went from ~1s to a // 120s timeout with a flat 25ms delay). Scaling with srtt keeps the // coalescing benefit where it matters (higher-RTT/higher-BDP paths // naturally carry more packets per RTT) without taxing the // stop-and-wait case where it doesn't. void quic::markAckPending() { if (!_app_ack_pending) { _app_ack_pending = true; static const double kCeilingSec = std::chrono::duration<double>(APP_MAX_ACK_DELAY).count(); auto delay = _rtt_initialized ? std::chrono::duration_cast<std::chrono::steady_clock::duration>( std::chrono::duration<double>(std::clamp(0.25 * _srtt, 0.0001, kCeilingSec))) : std::chrono::microseconds(200); _app_ack_deadline = std::chrono::steady_clock::now() + delay; } ++_app_unacked_count; } // Called once per receive cycle (end of processApplicationPacket() / // processApplicationPacketsBatch()): send now if we've accumulated 2+ // unacked packets or a gap is pending (RFC 9000 §13.2.1 — immediate ACK // on reordering/loss so the peer's own loss detection isn't delayed). // Otherwise leave it pending for sendStreamData() to piggyback on the // next outgoing data packet, or for maybeFlushDelayedAck() to flush once // APP_MAX_ACK_DELAY elapses. void quic::flushAckIfDue() { if (!_app_ack_pending) return; bool gap_pending = _app_pn_recv_ranges.size() > 1; bool fire = _app_unacked_count >= 2 || gap_pending; if (g_cwnd_trace) fprintf(stderr, "[ACKFLUSH] %c this=%p unacked=%u gap=%d fire=%d\n", _is_server ? 'S' : 'C', (void*)this, _app_unacked_count, (int)gap_pending, (int)fire); if (fire) { sendAppAck(); _app_ack_pending = false; _app_unacked_count = 0; } } // Called once per pumpNetwork()/handshake_after_accept() tick, alongside // pmtudTick() — flushes a pending ACK that's been waiting for a // piggyback opportunity that never came. void quic::maybeFlushDelayedAck() { if (!_app_ack_pending) return; bool due = std::chrono::steady_clock::now() >= _app_ack_deadline; if (g_cwnd_trace) fprintf(stderr, "[ACKDEADLINE] %c this=%p due=%d\n", _is_server ? 'S' : 'C', (void*)this, (int)due); if (due) { sendAppAck(); _app_ack_pending = false; _app_unacked_count = 0; } } // ============================================================================ // ACK: Send ACK frame for 1-RTT application packets // ============================================================================ void quic::sendAppAck() { g_stat_app_acks++; if (g_cwnd_trace) fprintf(stderr, "[SENDACK] %c this=%p largest=%lu ranges=%zu\n", _is_server ? 'S' : 'C', (void*)this, (unsigned long)_app_pn_recv, _app_pn_recv_ranges.size()); std::vector<uint8_t> frame = buildAckFrame(_app_pn_recv, 0, _app_pn_recv_ranges); std::vector<uint8_t> packet = buildShortHeaderPacket(frame); Loading Loading @@ -5429,7 +5296,6 @@ size_t quic::sendStreamData(uint64_t stream_id, const uint8_t* data, size_t len, vlen = encodeVarInt(0, vbuf); std::memcpy(pkt_buf + frame_off, vbuf, vlen); frame_off += vlen; } _app_ack_pending = false; _app_unacked_count = 0; } uint8_t frame_type = 0x08 | 0x02; // LEN always set Loading Loading @@ -5870,11 +5736,7 @@ void quic::pumpIncoming() { t->sendMaxData(t->_pending_max_data_value); t->_pending_max_data = false; } // Same delayed-ACK/PMTUD tick as the self case below — a // routed child connection needs its pending-ACK deadline // checked too, not just `this`. t->pmtudTick(); t->maybeFlushDelayedAck(); } } Loading @@ -5891,17 +5753,7 @@ void quic::pumpIncoming() { _pending_max_data = false; } // Flush a pending ACK that never got piggybacked or hit the // 2-packet threshold. Without this, a caller that only ever // drives this connection through pumpIncoming() (sendStreamData()'s // congestion-window-wait loop is exactly that caller) never checks // the delayed-ACK deadline at all — a lone unacked packet with no // reply to piggyback on then waits forever, stalling the peer's // flow control on an ACK that never comes (reproduced as a hang in // quic_concurrent_test). pmtudTick() belongs here for the same // reason, even though it's a no-op at the default ceiling. pmtudTick(); maybeFlushDelayedAck(); } // After processing incoming packets (which may contain ACKs), Loading
src/socket.h +1 −23 Changes for src/socket.h: 1 added line, 23 removed lines. Original line number Diff line number Diff line Loading @@ -875,30 +875,8 @@ namespace netplus { uint64_t _handshake_pn_recv = 0; uint64_t _app_pn_send = 0; uint64_t _app_pn_recv = 0; uint32_t _app_unacked_count = 0; // Delayed ACK counter — ack-eliciting packets // received since the last ACK was sent (see // maybeFlushDelayedAck() / APP_MAX_ACK_DELAY). uint32_t _app_unacked_count = 0; // Delayed ACK counter bool _app_ack_pending = false; // Deferred ACK flag std::chrono::steady_clock::time_point _app_ack_deadline; // when a pending ACK must be flushed static constexpr std::chrono::milliseconds APP_MAX_ACK_DELAY{25}; // RFC 9000 §13.2.1-ish default // Delayed ACK (RFC 9000 §13.2.1): send a standalone ACK immediately // on every 2nd ack-eliciting packet or when a gap is detected, but // otherwise let it wait for either a data packet to piggyback on // (see sendStreamData's ack_reserve/piggyback logic) or this // deadline — called once per pumpNetwork()/handshake_after_accept() // tick, alongside pmtudTick(). Without this, every received packet // (batches are frequently size 1 under load — see pumpIncoming's // batching comment) cost its own standalone ACK datagram: measured // at ~97% of all sendto() calls in benchmark_quic being ACK-only, // which — since ACK-only packets consume packet numbers from the // same space checkLossAndRetransmit()/onPacketLostCC() use to decide // when a post-loss recovery period ends (_recovery_start_pn) — also // froze congestion-window growth for far more round trips than one // true RTT after any single loss. void maybeFlushDelayedAck(); void markAckPending(); // called once per received ack-eliciting packet void flushAckIfDue(); // called once per receive cycle (batch or single packet) // Received packet-number ranges (inclusive) for proper ACK encoding // Each pair is [lo, hi] representing contiguous received PNs. Loading