Commit 8f212857 authored by jan.koester's avatar jan.koester
Browse files

test

parent a03f3614
Loading
Loading
Loading
Loading
+217 −43
Changes for src/quic.cpp: 217 added lines, 43 removed lines.
Original line number Diff line number Diff line
@@ -41,6 +41,7 @@
#include <thread>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cmath>

#define QUIC_DBG(fmt, ...) do { } while(0)
@@ -76,6 +77,29 @@ 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

// ============================================================================
@@ -293,6 +317,7 @@ 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;
@@ -407,10 +432,11 @@ void quic::processApplicationPacketsBatch(
        }
        trackRecvPN(pn, _app_pn_recv_ranges);

        // 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;
        // 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();

        size_t offset = 0;
        while (offset < payload.size()) {
@@ -418,10 +444,7 @@ void quic::processApplicationPacketsBatch(
        }
    }

    if (_app_ack_pending) {
        sendAppAck();
        _app_ack_pending = false;
    }
    flushAckIfDue();
}

// ============================================================================
@@ -432,7 +455,9 @@ 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;
    return _bytes_in_flight + packet_size <= _cwnd;
    bool allowed = _bytes_in_flight + packet_size <= _cwnd;
    if (!allowed) g_stat_cwnd_blocked++;
    return allowed;
}

void quic::onPacketSentCC(size_t packet_size) {
@@ -460,6 +485,9 @@ 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) {
@@ -476,6 +504,9 @@ 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);
    }
}

@@ -1415,6 +1446,7 @@ void quic::handshake_after_accept() {
        }

        pmtudTick();
        maybeFlushDelayedAck();
    }

    // Collect pending dispatches before releasing lock
@@ -2252,19 +2284,16 @@ 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). If no data is sent, flush after frame processing.
    _app_ack_pending = true;
    // (e.g., echo response), flushed below subject to the delayed-ACK
    // policy, or flushed later by maybeFlushDelayedAck().
    markAckPending();

    size_t offset = 0;
    while (offset < payload.size()) {
        processFrame(payload.data(), payload.size(), offset);
    }

    // If ACK is still pending (no data was sent in response), send standalone ACK
    if (_app_ack_pending) {
        sendAppAck();
        _app_ack_pending = false;
    }
    flushAckIfDue();
}

// ============================================================================
@@ -3021,6 +3050,23 @@ 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
        dispatches = std::move(_pending_dispatches);
        _pending_dispatches.clear();
@@ -3122,16 +3168,18 @@ void quic::pumpNetwork(int flags) {
        }
    }

    // Path MTU Discovery: drive the probe state machine unconditionally
    // Path MTU Discovery + delayed-ACK flush: drive both unconditionally
    // (not just when datagrams just arrived above) so a lost probe's
    // 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.
    // 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.
    if (_handshake_complete && _conn_state.load() == ConnectionState::Connected) {
        std::lock_guard<std::recursive_mutex> lock(quic_mtx());
        pmtudTick();
        maybeFlushDelayedAck();
    }
}

@@ -4109,6 +4157,7 @@ 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());
@@ -4219,6 +4268,7 @@ 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());
@@ -4359,11 +4409,77 @@ 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;
    if (_app_unacked_count >= 2 || gap_pending) {
        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;
    if (std::chrono::steady_clock::now() >= _app_ack_deadline) {
        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++;
    std::vector<uint8_t> frame = buildAckFrame(_app_pn_recv, 0, _app_pn_recv_ranges);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
@@ -5288,6 +5404,7 @@ 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
@@ -5627,6 +5744,23 @@ void quic::pumpIncoming() {
    std::vector<std::vector<uint8_t>> datagrams;
    parent->recvBatch(datagrams, 64);

    // Short-header (1-RTT) datagrams are grouped by target connection and
    // processed together via processApplicationPacketsBatch() — one
    // deferred ACK per target per pumpIncoming() call, the same batching
    // pumpNetwork() already does for its own single-connection case —
    // instead of routing each datagram individually through
    // processIncomingPacket(), which ACKs immediately per packet. That
    // per-packet path measured at ~30x more ACK-only sendto() calls than
    // data packets under load (see benchmark_quic diagnostics): this is
    // exactly the path sendStreamData()'s congestion-window-wait spin loop
    // calls repeatedly while blocked, so every datagram it drains paid for
    // its own standalone ACK datagram. Long-header packets (Initial/
    // Handshake, rare here) keep the immediate per-packet path — coalescing
    // them isn't worth the complexity since they aren't the steady-state
    // traffic and don't go through the deferred-ACK mechanism anyway.
    std::vector<std::shared_ptr<quic>> pins; // keep routed children alive for the whole call
    std::unordered_map<quic*, std::vector<std::pair<const uint8_t*, size_t>>> grouped;

    for (auto& dgram : datagrams) {
        if (dgram.empty()) continue;
        const uint8_t* data = dgram.data();
@@ -5635,12 +5769,13 @@ void quic::pumpIncoming() {
        // Route to whichever connection this datagram is for — which may
        // be `this`, a sibling child (if `this` is itself a child and the
        // packet is for a different one), or a child of `this` (if `this`
        // is the listener). Every case below locks the *target's own*
        // quic_mtx() before touching it, not just `this`'s — under the old
        // shared-parent-mutex design one lock covered every connection, so
        // reaching into a sibling/child's state under only `this`'s lock
        // was safe by accident; it no longer is now that each connection
        // has its own mutex.
        // is the listener). Registry lookups take only a shared_lock, same
        // as before; only how the datagram is subsequently *processed*
        // changes (grouped below instead of processed inline here) — under
        // the old shared-parent-mutex design one lock covered every
        // connection, so reaching into a sibling/child's state under only
        // `this`'s lock was safe by accident; it no longer is now that each
        // connection has its own mutex.
        bool route_to_self = false;
        std::shared_ptr<quic> target; // pinned alive past the registry lookup

@@ -5660,8 +5795,25 @@ void quic::pumpIncoming() {
                auto it = parent->_child_connections.find(cidKey(data + 1, CID_LEN));
                if (it != parent->_child_connections.end()) target = it->second;
            }

            quic* target_raw = nullptr;
            if (route_to_self) {
                target_raw = this;
            } else if (target) {
                target_raw = target.get();
                pins.push_back(std::move(target));
            } else {
            // Long header (Initial, Handshake, etc.)
                continue; // no matching connection for this DCID
            }
            grouped[target_raw].emplace_back(data, len);
        } else {
            // Long header (Initial, Handshake, etc.) — unchanged immediate
            // per-packet path. Matches the original routing exactly: only
            // dispatched when a matching child is found in the registry
            // (never falls back to `this`, even for a listener — a brand
            // new client's Initial packet is accept()'s job, not
            // pumpIncoming()'s; silently dropping an unmatched one here is
            // intentional, same as before this refactor).
            if (len >= 7) {
                size_t dcid_len = static_cast<size_t>(data[5]);
                if (6 + dcid_len <= len) {
@@ -5670,25 +5822,35 @@ void quic::pumpIncoming() {
                    if (it != parent->_child_connections.end()) target = it->second;
                }
            }
        }

        if (route_to_self) {
            std::lock_guard<std::recursive_mutex> self_lock(quic_mtx());
            processIncomingPacket(data, len);
        } else if (target) {
            if (target) {
                std::lock_guard<std::recursive_mutex> target_lock(target->quic_mtx());
                target->processIncomingPacket(data, len);
            if (target->_handshake_complete &&
                target->_conn_state.load() == ConnectionState::Connected) {
                for (auto& [sid, limit] : target->_pending_max_stream_data)
                    target->sendMaxStreamData(sid, limit);
                target->_pending_max_stream_data.clear();
                if (target->_pending_max_data) {
                    target->sendMaxData(target->_pending_max_data_value);
                    target->_pending_max_data = false;
            }
        }
    }

    for (auto& [t, pkts] : grouped) {
        std::lock_guard<std::recursive_mutex> target_lock(t->quic_mtx());
        t->processApplicationPacketsBatch(pkts);
        // The self case's pending flow-control frames are flushed by the
        // unconditional block below (operating on `this`'s own state);
        // this only covers actually-routed child connections, matching the
        // pre-batching code's behavior.
        if (t != this && t->_handshake_complete &&
            t->_conn_state.load() == ConnectionState::Connected) {
            for (auto& [sid, limit] : t->_pending_max_stream_data)
                t->sendMaxStreamData(sid, limit);
            t->_pending_max_stream_data.clear();
            if (t->_pending_max_data) {
                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();
        }
    }

    // Flush own pending flow control frames, and check for lost packets to
@@ -5703,6 +5865,18 @@ void quic::pumpIncoming() {
            sendMaxData(_pending_max_data_value);
            _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),
+23 −1
Changes for src/socket.h: 23 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -875,8 +875,30 @@ 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
		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).
		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.