Defer ACK-only packets while delivering queued packets to a new session when the client sends SDAO.

When `QuicDispatcher` creates a session for a multi-packet `ClientHello`, it delivers the packet that completed the `ClientHello` and then the buffered `INITIAL` fragments, flushing after each individual packet. Since `INITIAL` packets are ACKed immediately, the server sent a standalone 1200-byte padded `INITIAL` ACK packet after the first packet was processed, before the full `ClientHello` was available, instead of bundling the ACK with the ServerHello.

Protected by reloadable flag `gfe2_reloadable_flag_quic_defer_ack_only_packets_for_queued_packets`, and enabled per connection by the new `SDAO` client connection option so the impact can be measured with a client-side experiment:
- When `QuicDispatcher::ProcessChlo` or `QuicDispatcher::ProcessBufferedChlos` creates a session for a multi-packet `ClientHello`, it checks `packet_list.tls_chlo_extractor.transport_params()` for `SDAO` and calls `QuicConnection::set_allow_deferring_ack_only_packets(true)`. Single-packet `ClientHello`s have no buffered packets, so they are unaffected.
- `QuicDispatcher::ProcessChlo` and `QuicDispatcher::DeliverPacketsToSession` hold a `QuicConnection::ScopedAckDeferrer` (added in cl/1015665961) while the current and queued packets are processed. Pending ACKs are then bundled with outgoing data (e.g. the ServerHello) or sent once when the deferrer goes out of scope.
- Guards moving `transport_params_` in `TlsChloExtractor::operator=` behind the flag.

The packet delivery order is unchanged. With ACK-only packets deferred for the whole batch, processing the completing packet first produces the same single ServerHello with a bundled ACK as processing the packets in order.

`SDAO` is not detected for draft-29, which uses the legacy transport parameters TLS extension.

Protected by quic_reloadable_flag_quic_defer_ack_only_packets_for_queued_packets.

PiperOrigin-RevId: 1029354817
diff --git a/quiche/common/quiche_feature_flags_list.h b/quiche/common/quiche_feature_flags_list.h
index 5d7a05e..4335983 100644
--- a/quiche/common/quiche_feature_flags_list.h
+++ b/quiche/common/quiche_feature_flags_list.h
@@ -32,6 +32,7 @@
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_default_enable_5rto_blackhole_detection2, true, true, "If true, default-enable 5RTO blachole detection.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_default_to_bbr, true, false, "When true, defaults to BBR congestion control instead of Cubic.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_default_to_bbr_v2, false, false, "If true, use BBRv2 as the default congestion controller. Takes precedence over --quic_default_to_bbr.")
+QUICHE_FLAG(bool, quiche_reloadable_flag_quic_defer_ack_only_packets_for_queued_packets, false, false, "When true and the client sends the SDAO connection option in a multi-packet ClientHello, QuicDispatcher defers ACK-only packets while delivering queued packets to the new session.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_deliver_stop_sending_to_zombie_streams, true, true, "If true, deliver STOP_SENDING to zombie streams.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_disable_batch_write, false, false, "If true, round-robin stream writes instead of batching in QuicWriteBlockedList.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_disable_server_blackhole_detection, false, false, "If true, disable blackhole detection on server side.")
diff --git a/quiche/quic/core/crypto/crypto_protocol.h b/quiche/quic/core/crypto/crypto_protocol.h
index 57b5f81..a7ccfc1 100644
--- a/quiche/quic/core/crypto/crypto_protocol.h
+++ b/quiche/quic/core/crypto/crypto_protocol.h
@@ -330,6 +330,9 @@
 DEFINE_STATIC_QUIC_TAG(DFER);  // Do not defer sending.
 DEFINE_STATIC_QUIC_TAG(CDFR);  // Defer sending on client.
 DEFINE_STATIC_QUIC_TAG(DAOP);  // Defer sending ACK-only packets on client.
+DEFINE_STATIC_QUIC_TAG(SDAO);  // Defer sending ACK-only packets on server
+                               // while delivering queued packets to a new
+                               // session.
 
 // Pacing options.
 DEFINE_STATIC_QUIC_TAG(NPCO);  // No pacing offload.
diff --git a/quiche/quic/core/quic_connection.h b/quiche/quic/core/quic_connection.h
index 495ad70..876bfee 100644
--- a/quiche/quic/core/quic_connection.h
+++ b/quiche/quic/core/quic_connection.h
@@ -1065,6 +1065,11 @@
     can_truncate_connection_ids_ = can;
   }
 
+  // Allows ScopedAckDeferrer to defer ACK-only packets on this connection.
+  void set_allow_deferring_ack_only_packets(bool allow) {
+    allow_deferring_ack_only_packets_ = allow;
+  }
+
   // Returns the underlying sent packet manager.
   const QuicSentPacketManager& sent_packet_manager() const {
     return sent_packet_manager_;
@@ -2640,7 +2645,8 @@
   bool fix_mtu_discovery_ : 1 = GetQuicReloadableFlag(quic_fix_mtu_discovery);
   bool send_acks_after_on_can_write_ : 1 = false;
   bool coalesce_ping_with_last_packet_ : 1 = false;
-  // Set by the client-only DAOP connection option.
+  // Set by the client-only DAOP connection option, or by QuicDispatcher on the
+  // server when the client sends the SDAO connection option.
   bool allow_deferring_ack_only_packets_ : 1 = false;
   bool defer_ack_only_packets_ : 1 = false;
   bool unify_peer_address_and_path_validation_ : 1 =
diff --git a/quiche/quic/core/quic_connection_test.cc b/quiche/quic/core/quic_connection_test.cc
index 29b6185..6ac2128 100644
--- a/quiche/quic/core/quic_connection_test.cc
+++ b/quiche/quic/core/quic_connection_test.cc
@@ -21667,6 +21667,68 @@
   EXPECT_EQ(2u, writer_->packets_write_attempts());
 }
 
+TEST_P(QuicConnectionTest,
+       BatchProcessInitialPacketsWithScopedAckDeferrerBundlesSingleInitialAck) {
+  if (!connection_.SupportsMultiplePacketNumberSpaces()) {
+    return;
+  }
+  SetQuicReloadableFlag(quic_send_acks_after_on_can_write, true);
+  set_perspective(Perspective::IS_SERVER);
+  // QuicDispatcher allows deferring ACK-only packets when the client sends
+  // SDAO.
+  connection_.set_allow_deferring_ack_only_packets(true);
+  QuicConfig config;
+  config.SetInitialReceivedConnectionOptions({kSAOW});
+  EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
+  EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
+  EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
+  connection_.SetFromConfig(config);
+  QuicConnectionPeer::SetAddressValidated(&connection_);
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
+
+  // Simulate QuicDispatcher delivering a 2-packet ClientHello under a
+  // ScopedAckDeferrer. QuicDispatcher delivers the packet that completes the
+  // ClientHello before the buffered packets, so:
+  // - Packet 2 (the second fragment) is processed first and queues an INITIAL
+  //   ACK, but the ClientHello is not complete yet.
+  // - Packet 1 completes the ClientHello, causing the server to buffer INITIAL
+  //   CRYPTO (ServerHello) and install HANDSHAKE keys.
+  EXPECT_CALL(visitor_, OnCryptoFrame(_)).WillOnce(Return()).WillOnce([this]() {
+    connection_.SendCryptoDataWithString("shlo", 0, ENCRYPTION_INITIAL);
+    connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
+                             std::make_unique<TaggingEncrypter>(0x02));
+    connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
+  });
+  EXPECT_CALL(visitor_, OnCanWrite()).WillRepeatedly([this]() {
+    QuicConnection::ScopedEncryptionLevelContext context(&connection_,
+                                                         ENCRYPTION_INITIAL);
+    notifier_.OnCanWrite();
+  });
+  EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
+  EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
+
+  {
+    QuicConnection::ScopedAckDeferrer ack_deferrer(&connection_);
+    ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
+    // No standalone INITIAL ACK packet should be flushed after packet 2.
+    EXPECT_EQ(0u, writer_->packets_write_attempts());
+    ForceWillingAndAbleToWriteOnceForDeferSending();
+    ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
+  }
+  if (connection_.GetSendAlarm()->IsSet()) {
+    connection_.GetSendAlarm()->Fire();
+  }
+
+  // The INITIAL ACK for packets [1..2] is bundled with the INITIAL CRYPTO
+  // frame in a single INITIAL packet rather than sent as a separate ACK-only
+  // packet.
+  EXPECT_EQ(1u, writer_->packets_write_attempts());
+  ASSERT_EQ(1u, writer_->ack_frames().size());
+  EXPECT_EQ(QuicPacketNumber(2), LargestAcked(writer_->ack_frames()[0]));
+  EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(1)));
+  EXPECT_EQ(1u, writer_->crypto_frames().size());
+}
+
 }  // namespace
 }  // namespace test
 }  // namespace quic
diff --git a/quiche/quic/core/quic_dispatcher.cc b/quiche/quic/core/quic_dispatcher.cc
index e98e00e..0fc34f4 100644
--- a/quiche/quic/core/quic_dispatcher.cc
+++ b/quiche/quic/core/quic_dispatcher.cc
@@ -25,11 +25,13 @@
 #include "absl/container/flat_hash_set.h"
 #include "absl/strings/str_cat.h"
 #include "absl/strings/string_view.h"
+#include "absl/types/span.h"
 #include "quiche/quic/core/chlo_extractor.h"
 #include "quiche/quic/core/connection_id_generator.h"
 #include "quiche/quic/core/crypto/crypto_handshake_message.h"
 #include "quiche/quic/core/crypto/crypto_protocol.h"
 #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h"
+#include "quiche/quic/core/crypto/transport_parameters.h"
 #include "quiche/quic/core/frames/quic_connection_close_frame.h"
 #include "quiche/quic/core/frames/quic_frame.h"
 #include "quiche/quic/core/frames/quic_rst_stream_frame.h"
@@ -51,6 +53,7 @@
 #include "quiche/quic/core/quic_packets.h"
 #include "quiche/quic/core/quic_session.h"
 #include "quiche/quic/core/quic_stream_frame_data_producer.h"
+#include "quiche/quic/core/quic_tag.h"
 #include "quiche/quic/core/quic_time.h"
 #include "quiche/quic/core/quic_time_wait_list_manager.h"
 #include "quiche/quic/core/quic_types.h"
@@ -82,6 +85,28 @@
 // Minimal INITIAL packet length sent by clients is 1200.
 const QuicPacketLength kMinClientInitialPacketLength = 1200;
 
+// Returns true if quic_defer_ack_only_packets_for_queued_packets is enabled and
+// the client sent the SDAO connection option in |transport_params|.
+bool ShouldDeferAckOnlyPackets(const ParsedQuicVersion& version,
+                               absl::Span<const uint8_t> transport_params) {
+  if (!GetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets) ||
+      transport_params.empty()) {
+    return false;
+  }
+  TransportParameters params;
+  std::string error_details;
+  if (!ParseTransportParameters(
+          version, Perspective::IS_CLIENT, transport_params.data(),
+          transport_params.size(), &params, &error_details) ||
+      !params.google_connection_options.has_value() ||
+      !ContainsQuicTag(*params.google_connection_options, kSDAO)) {
+    return false;
+  }
+  QUIC_RELOADABLE_FLAG_COUNT_N(quic_defer_ack_only_packets_for_queued_packets,
+                               2, 2);
+  return true;
+}
+
 // An alarm that informs the QuicDispatcher to delete old sessions.
 class DeleteSessionsAlarm : public QuicAlarm::DelegateWithoutContext {
  public:
@@ -1185,6 +1210,11 @@
     if (session_ptr != nullptr) {
       OnNewSessionCreated(*session_ptr, packet_list.creation_time,
                           /*entire_chlo_buffered=*/true);
+      if (ShouldDeferAckOnlyPackets(
+              packet_list.version,
+              packet_list.tls_chlo_extractor.transport_params())) {
+        session_ptr->connection()->set_allow_deferring_ack_only_packets(true);
+      }
       DeliverPacketsToSession(packets, session_ptr.get());
     }
   }
@@ -1265,6 +1295,15 @@
   }
   OnNewSessionCreated(*session_ptr, packet_list.creation_time,
                       /*entire_chlo_buffered=*/false);
+  // If the client sent SDAO, defer ACK-only packets until the current packet
+  // and all queued packets have been processed, so pending ACKs are bundled
+  // with the ServerHello instead of being sent in standalone packets.
+  if (ShouldDeferAckOnlyPackets(
+          packet_info->version,
+          packet_list.tls_chlo_extractor.transport_params())) {
+    session_ptr->connection()->set_allow_deferring_ack_only_packets(true);
+  }
+  QuicConnection::ScopedAckDeferrer ack_deferrer(session_ptr->connection());
   // Process the current packet first, then deliver queued-up packets.
   // Note that multi-packet CHLOs, if received in packet number order, will
   // not be delivered in the same order. This needs to be fixed.
@@ -1287,6 +1326,7 @@
 
 void QuicDispatcher::DeliverPacketsToSession(
     const std::list<BufferedPacket>& packets, QuicSession* session) {
+  QuicConnection::ScopedAckDeferrer ack_deferrer(session->connection());
   for (const BufferedPacket& packet : packets) {
     session->ProcessUdpPacket(packet.self_address, packet.peer_address,
                               *(packet.packet));
diff --git a/quiche/quic/core/quic_dispatcher_test.cc b/quiche/quic/core/quic_dispatcher_test.cc
index 2877395..21c4f8f 100644
--- a/quiche/quic/core/quic_dispatcher_test.cc
+++ b/quiche/quic/core/quic_dispatcher_test.cc
@@ -610,8 +610,17 @@
     ProcessFirstFlight(version, client_address, connection_id);
   }
 
+  // Sends a multi-packet TLS ClientHello and verifies that all packets are
+  // delivered to the new session. If |send_sdao| is true, the client sends the
+  // SDAO connection option, and the dispatcher is expected to allow deferring
+  // ACK-only packets on the new connection if
+  // quic_defer_ack_only_packets_for_queued_packets is enabled. If |buffer_chlo|
+  // is true, the completed ClientHello is buffered and delivered via
+  // ProcessBufferedChlos().
   void TestTlsMultiPacketClientHello(bool add_reordering,
-                                     bool long_connection_id);
+                                     bool long_connection_id,
+                                     bool send_sdao = false,
+                                     bool buffer_chlo = false);
 
   void TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
       const QuicConnectionId& server_connection_id,
@@ -760,7 +769,8 @@
 }
 
 void QuicDispatcherTestBase::TestTlsMultiPacketClientHello(
-    bool add_reordering, bool long_connection_id) {
+    bool add_reordering, bool long_connection_id, bool send_sdao,
+    bool buffer_chlo) {
   if (!version_.IsIetfQuic()) {
     return;
   }
@@ -789,6 +799,9 @@
   std::string kCustomParameterValue(2000, '-');
   client_config.custom_transport_parameters_to_send()[kCustomParameterId] =
       kCustomParameterValue;
+  if (send_sdao) {
+    client_config.SetConnectionOptionsToSend({kSDAO});
+  }
   std::vector<std::unique_ptr<QuicReceivedPacket>> packets =
       GetFirstFlightOfPackets(version_, client_config, original_connection_id,
                               EmptyQuicConnectionId(),
@@ -807,7 +820,15 @@
   EXPECT_EQ(dispatcher_->NumSessions(), 0u)
       << "No session should be created before the rest of the CHLO arrives.";
 
-  // Processing the last packet should create the new session.
+  if (buffer_chlo) {
+    dispatcher_->ProcessBufferedChlos(0);
+    ProcessReceivedPacket(std::move(packets.back()), client_address, version_,
+                          original_connection_id);
+    EXPECT_EQ(dispatcher_->NumSessions(), 0u);
+  }
+
+  // Processing the last packet (or draining buffered CHLOs) should create the
+  // new session.
   EXPECT_CALL(
       *dispatcher_,
       CreateQuicSession(new_connection_id, _, client_address,
@@ -820,9 +841,21 @@
               ProcessUdpPacket(_, _, _))
       .Times(packets.size());
 
-  ProcessReceivedPacket(std::move(packets.back()), client_address, version_,
-                        original_connection_id);
+  if (buffer_chlo) {
+    dispatcher_->ProcessBufferedChlos(1);
+  } else {
+    ProcessReceivedPacket(std::move(packets.back()), client_address, version_,
+                          original_connection_id);
+  }
   EXPECT_EQ(dispatcher_->NumSessions(), 1u);
+  // SDAO is not detected for versions using the legacy transport parameters TLS
+  // extension (draft-29), because TlsChloExtractor only reads the RFC one.
+  const bool expect_defer_ack_only_packets =
+      send_sdao && !version_.UsesLegacyTlsExtension() &&
+      GetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets);
+  EXPECT_EQ(QuicConnectionPeer::GetAllowDeferringAckOnlyPackets(
+                session1_->connection()),
+            expect_defer_ack_only_packets);
 }
 
 TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHello) {
@@ -830,6 +863,38 @@
                                 /*long_connection_id=*/false);
 }
 
+TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithSdao) {
+  SetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets, true);
+  TestTlsMultiPacketClientHello(/*add_reordering=*/false,
+                                /*long_connection_id=*/false,
+                                /*send_sdao=*/true);
+}
+
+TEST_P(QuicDispatcherTestAllVersions,
+       TlsMultiPacketClientHelloBufferedWithSdao) {
+  SetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets, true);
+  TestTlsMultiPacketClientHello(/*add_reordering=*/false,
+                                /*long_connection_id=*/false,
+                                /*send_sdao=*/true,
+                                /*buffer_chlo=*/true);
+}
+
+TEST_P(QuicDispatcherTestAllVersions,
+       TlsMultiPacketClientHelloWithSdaoWithoutDeferAckOnlyPacketsFlag) {
+  SetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets, false);
+  TestTlsMultiPacketClientHello(/*add_reordering=*/false,
+                                /*long_connection_id=*/false,
+                                /*send_sdao=*/true);
+}
+
+TEST_P(QuicDispatcherTestAllVersions,
+       TlsMultiPacketClientHelloWithDeferAckOnlyPacketsFlagWithoutSdao) {
+  SetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets, true);
+  TestTlsMultiPacketClientHello(/*add_reordering=*/false,
+                                /*long_connection_id=*/false,
+                                /*send_sdao=*/false);
+}
+
 TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithReordering) {
   TestTlsMultiPacketClientHello(/*add_reordering=*/true,
                                 /*long_connection_id=*/false);
diff --git a/quiche/quic/core/tls_chlo_extractor.cc b/quiche/quic/core/tls_chlo_extractor.cc
index 4cc7f73..0055ad8 100644
--- a/quiche/quic/core/tls_chlo_extractor.cc
+++ b/quiche/quic/core/tls_chlo_extractor.cc
@@ -156,6 +156,11 @@
   cert_compression_algos_ = std::move(other.cert_compression_algos_);
   alpns_ = std::move(other.alpns_);
   server_name_ = std::move(other.server_name_);
+  if (GetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets)) {
+    QUIC_RELOADABLE_FLAG_COUNT_N(quic_defer_ack_only_packets_for_queued_packets,
+                                 1, 2);
+    transport_params_ = std::move(other.transport_params_);
+  }
   client_hello_bytes_ = std::move(other.client_hello_bytes_);
   return *this;
 }
diff --git a/quiche/quic/core/tls_chlo_extractor_test.cc b/quiche/quic/core/tls_chlo_extractor_test.cc
index ed1fce8..9739eb8 100644
--- a/quiche/quic/core/tls_chlo_extractor_test.cc
+++ b/quiche/quic/core/tls_chlo_extractor_test.cc
@@ -359,6 +359,13 @@
 
   EXPECT_EQ(other_extractor.state(), expected_state);
   ValidateChloDetails(&other_extractor);
+  if (GetQuicReloadableFlag(quic_defer_ack_only_packets_for_queued_packets) &&
+      (version_ == ParsedQuicVersion::RFCv1() ||
+       version_ == ParsedQuicVersion::RFCv2())) {
+    EXPECT_FALSE(other_extractor.transport_params().empty());
+  } else {
+    EXPECT_TRUE(other_extractor.transport_params().empty());
+  }
 }
 
 TEST_P(TlsChloExtractorTest, MoveAssignmentBetweenPackets) {
diff --git a/quiche/quic/test_tools/quic_connection_peer.cc b/quiche/quic/test_tools/quic_connection_peer.cc
index 49e3864..21c01ce 100644
--- a/quiche/quic/test_tools/quic_connection_peer.cc
+++ b/quiche/quic/test_tools/quic_connection_peer.cc
@@ -695,6 +695,12 @@
 }
 
 // static
+bool QuicConnectionPeer::GetAllowDeferringAckOnlyPackets(
+    QuicConnection* connection) {
+  return connection->allow_deferring_ack_only_packets_;
+}
+
+// static
 QuicConnection::ReceivedPacketInfo&
 QuicConnectionPeer::GetLastReceivedPacketInfo(QuicConnection* connection) {
   return connection->last_received_packet_info_;
diff --git a/quiche/quic/test_tools/quic_connection_peer.h b/quiche/quic/test_tools/quic_connection_peer.h
index 729593b..ad00142 100644
--- a/quiche/quic/test_tools/quic_connection_peer.h
+++ b/quiche/quic/test_tools/quic_connection_peer.h
@@ -285,6 +285,8 @@
   static void SetAllowDeferringAckOnlyPackets(QuicConnection* connection,
                                               bool allow);
 
+  static bool GetAllowDeferringAckOnlyPackets(QuicConnection* connection);
+
   static QuicConnection::ReceivedPacketInfo& GetLastReceivedPacketInfo(
       QuicConnection* connection);