Bundle non-INITIAL QUIC CRYPTO frames with other frames with the BCWF connection option.

During the QUIC handshake, `QuicPacketCreator` flushes before and after every `CRYPTO` frame at all encryption levels, and `QuicConnection::CanWrite` only suppresses mid-packet writes while `ENCRYPTION_INITIAL` keys are present. As a result, frames generated when processing the client's `HANDSHAKE` Finished flight (such as `NewSessionTicket` `CRYPTO` frames, `HANDSHAKE_DONE`, `NEW_TOKEN`, and `NEW_CONNECTION_ID`) are split across multiple 1-RTT packets and UDP packets.

When `gfe2_reloadable_flag_quic_bundle_crypto_with_other_frames` is enabled and the client sends the `BCWF` connection option:
- Allow non-`INITIAL` `CRYPTO` frames to share a packet with other frames in `QuicPacketCreator`, and only apply full handshake padding to `ENCRYPTION_INITIAL` packets.
- Suppress mid-packet writes in `QuicConnection::CanWrite` while `ENCRYPTION_HANDSHAKE` keys are present (including across coalesced `[HANDSHAKE, 1-RTT]` UDP packets that discard `HANDSHAKE` keys) so post-handshake frames generated during packet processing are bundled together.

Protected by quic_reloadable_flag_quic_bundle_crypto_with_other_frames.

PiperOrigin-RevId: 1034981704
diff --git a/quiche/common/quiche_feature_flags_list.h b/quiche/common/quiche_feature_flags_list.h
index 4335983..99f5f13 100644
--- a/quiche/common/quiche_feature_flags_list.h
+++ b/quiche/common/quiche_feature_flags_list.h
@@ -22,6 +22,7 @@
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_bbr_exit_startup_on_loss_network_param, false, true, "Enables adjustment of BBRv1's exit-startup-on-loss behavior on established connections via NetworkParams::enable_bbr_exit_startup_on_loss.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_block_until_settings_received_copt, false, false, "If enabled and a BSUS connection is received, blocks server connections until SETTINGS frame is received.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_bundle_crypto_retransmits, false, false, "When true, retransmissions of CRYPTO frames will be bundled in a single packet when possible.")
+QUICHE_FLAG(bool, quiche_reloadable_flag_quic_bundle_crypto_with_other_frames, false, false, "When true and the client sends the BCWF connection option, allow bundling non-INITIAL CRYPTO frames with other frames and suppress mid-packet writes while HANDSHAKE keys are present.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_clear_packet_on_serialization_failure, false, false, "If true, clear QuicPacketCreator state when serialization failure.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_clear_probing_data_on_reset_path_validation, false, false, "If true, clear probing_data_ in QuicPathValidator::ResetPathValidation() so a PATH_RESPONSE to a cancelled path validation can't validate a different path.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_client_check_blockage_before_on_can_write, false, false, "If true, quic clients will only call OnCanWrite() upon write events if the writer is unblocked.")
diff --git a/quiche/quic/core/crypto/crypto_protocol.h b/quiche/quic/core/crypto/crypto_protocol.h
index f8bc09b..cc149fb 100644
--- a/quiche/quic/core/crypto/crypto_protocol.h
+++ b/quiche/quic/core/crypto/crypto_protocol.h
@@ -532,6 +532,7 @@
 DEFINE_STATIC_QUIC_TAG(CPLP);  // Coalesce PING with last packet.
 DEFINE_STATIC_QUIC_TAG(PHSR);  // Prioritize handshake over stream
                                // retransmissions.
+DEFINE_STATIC_QUIC_TAG(BCWF);  // Bundle CRYPTO with other frames.
 
 // Stats collection tags
 DEFINE_STATIC_QUIC_TAG(EPID);  // Endpoint identifier.
diff --git a/quiche/quic/core/http/end_to_end_test.cc b/quiche/quic/core/http/end_to_end_test.cc
index 44708de..6371c12 100644
--- a/quiche/quic/core/http/end_to_end_test.cc
+++ b/quiche/quic/core/http/end_to_end_test.cc
@@ -146,8 +146,11 @@
 using spdy::SpdySettingsIR;
 using ::testing::_;
 using ::testing::Assign;
+using ::testing::Each;
 using ::testing::HasSubstr;
+using ::testing::IsEmpty;
 using ::testing::NiceMock;
+using ::testing::Not;
 using ::testing::UnorderedElementsAreArray;
 
 #ifndef NDEBUG
@@ -10034,6 +10037,72 @@
   SendSynchronousFooRequestAndCheckResponse();
 }
 
+// Smoke test that 1-RTT and 0-RTT handshakes succeed with CRYPTO frame
+// bundling enabled.
+TEST_P(EndToEndTest, BundleCryptoWithOtherFrames) {
+  SetQuicReloadableFlag(quic_bundle_crypto_with_other_frames, true);
+  client_extra_copts_.push_back(kBCWF);
+  ASSERT_TRUE(Initialize());
+  if (!version_.IsIetfQuic()) {
+    return;
+  }
+  SendSynchronousFooRequestAndCheckResponse();
+  client_->Disconnect();
+
+  // Connect again using 0-RTT resumption.
+  client_->Connect();
+  SendSynchronousFooRequestAndCheckResponse();
+  EXPECT_TRUE(client_->client()->EarlyDataAccepted());
+  client_->Disconnect();
+}
+
+// Verifies that with BCWF, the server's post-handshake 1-RTT CRYPTO frame
+// (NewSessionTicket) is bundled into the same packet as HANDSHAKE_DONE.
+// Without BCWF, CRYPTO frames are always sent in their own packets.
+TEST_P(EndToEndTest, BundleCryptoWithOtherFramesBundlesHandshakeDone) {
+  if (!version_.IsIetfQuic()) {
+    ASSERT_TRUE(Initialize());
+    return;
+  }
+  SetQuicReloadableFlag(quic_bundle_crypto_with_other_frames, true);
+  client_extra_copts_.push_back(kBCWF);
+  int num_packets_received = 0;
+  std::vector<int> one_rtt_crypto_packets;
+  std::vector<int> handshake_done_packets;
+  NiceMock<MockQuicConnectionDebugVisitor> visitor;
+  ON_CALL(visitor, OnPacketHeader)
+      .WillByDefault(
+          [&](const QuicPacketHeader& /*header*/, QuicTime /*receive_time*/,
+              EncryptionLevel /*level*/) { ++num_packets_received; });
+  ON_CALL(visitor, OnCryptoFrame)
+      .WillByDefault([&](const QuicCryptoFrame& frame) {
+        if (frame.level == ENCRYPTION_FORWARD_SECURE) {
+          one_rtt_crypto_packets.push_back(num_packets_received);
+        }
+      });
+  ON_CALL(visitor, OnHandshakeDoneFrame)
+      .WillByDefault([&](const QuicHandshakeDoneFrame& /*frame*/) {
+        handshake_done_packets.push_back(num_packets_received);
+      });
+  connection_debug_visitor_ = &visitor;
+  ASSERT_TRUE(Initialize());
+  ASSERT_TRUE(client_->client()->WaitForHandshakeConfirmed());
+  SendSynchronousFooRequestAndCheckResponse();
+
+  server_thread_->Pause();
+  QuicConnection* server_connection = GetServerConnection();
+  EXPECT_NE(server_connection, nullptr);
+  if (server_connection != nullptr) {
+    EXPECT_TRUE(server_connection->bundle_crypto_with_other_frames());
+  }
+  server_thread_->Resume();
+  client_->Disconnect();
+
+  ASSERT_EQ(1u, handshake_done_packets.size());
+  EXPECT_THAT(one_rtt_crypto_packets, Not(IsEmpty()));
+  EXPECT_THAT(one_rtt_crypto_packets, Each(handshake_done_packets[0]));
+}
+
 }  // namespace
 }  // namespace test
 }  // namespace quic
diff --git a/quiche/quic/core/quic_connection.cc b/quiche/quic/core/quic_connection.cc
index 2a3376f..3bbb79a 100644
--- a/quiche/quic/core/quic_connection.cc
+++ b/quiche/quic/core/quic_connection.cc
@@ -635,6 +635,12 @@
        config.HasClientSentConnectionOption(kDAOP, perspective_))) {
     allow_deferring_ack_only_packets_ = true;
   }
+  if (version().IsIetfQuic() &&
+      GetQuicReloadableFlag(quic_bundle_crypto_with_other_frames) &&
+      config.HasClientSentConnectionOption(kBCWF, perspective_)) {
+    QUIC_RELOADABLE_FLAG_COUNT(quic_bundle_crypto_with_other_frames);
+    packet_creator_.set_bundle_crypto_with_other_frames(true);
+  }
 
   if (config.HasClientRequestedIndependentOption(kINVC, perspective_)) {
     send_connection_close_for_invalid_version_ = true;
@@ -2986,6 +2992,12 @@
                 << last_received_packet_info_.destination_address;
 
   ScopedPacketFlusher flusher(this);
+  had_handshake_keys_in_udp_packet_ =
+      bundle_crypto_with_other_frames() &&
+      framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE);
+  absl::Cleanup reset_had_handshake_keys = [this] {
+    had_handshake_keys_in_udp_packet_ = false;
+  };
   if (!framer_.ProcessPacket(packet)) {
     // If we are unable to decrypt this packet, it might be
     // because the CHLO or SHLO packet was lost.
@@ -3546,10 +3558,15 @@
   }
 
   if (version().IsIetfQuic() &&
-      framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL) &&
+      (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL) ||
+       (bundle_crypto_with_other_frames() &&
+        (had_handshake_keys_in_udp_packet_ ||
+         framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE)))) &&
       framer_.is_processing_packet()) {
-    // While we still have initial keys, suppress sending in mid of packet
-    // processing.
+    // While we still have (or started processing this UDP packet with) initial
+    // or handshake keys, suppress sending while packet processing so frames
+    // written while processing a coalesced [HANDSHAKE, 1-RTT] UDP packet do not
+    // precede buffered CRYPTO or HANDSHAKE_DONE frames.
     // TODO(fayang): always suppress sending while in the mid of packet
     // processing.
     QUIC_DVLOG(1) << ENDPOINT
diff --git a/quiche/quic/core/quic_connection.h b/quiche/quic/core/quic_connection.h
index e5011f5..921c7bc 100644
--- a/quiche/quic/core/quic_connection.h
+++ b/quiche/quic/core/quic_connection.h
@@ -1549,6 +1549,10 @@
     return enable_black_hole_avoidance_via_flow_label_;
   }
 
+  bool bundle_crypto_with_other_frames() const {
+    return packet_creator_.bundle_crypto_with_other_frames();
+  }
+
   void OnDiscardZeroRttDecryptionKeysAlarm() override;
   void OnIdleDetectorAlarm() override;
   void OnNetworkBlackholeDetectorAlarm() override;
@@ -2656,6 +2660,11 @@
   bool defer_ack_only_packets_ : 1 = false;
   bool unify_peer_address_and_path_validation_ : 1 =
       GetQuicReloadableFlag(quic_unify_peer_address_and_path_validation);
+  // True while ProcessUdpPacket() is processing a UDP packet that began with a
+  // HANDSHAKE encrypter installed and bundle_crypto_with_other_frames() true,
+  // so CanWrite() keeps suppressing mid-packet writes across coalesced or
+  // replayed 1-RTT packets after HANDSHAKE keys are discarded.
+  bool had_handshake_keys_in_udp_packet_ : 1 = false;
 };
 
 }  // namespace quic
diff --git a/quiche/quic/core/quic_connection_test.cc b/quiche/quic/core/quic_connection_test.cc
index 554ad80..70a9714 100644
--- a/quiche/quic/core/quic_connection_test.cc
+++ b/quiche/quic/core/quic_connection_test.cc
@@ -1578,6 +1578,27 @@
     }
   }
 
+  void EnableBundleCryptoWithOtherFrames(bool flag_enabled = true,
+                                         bool send_copt = true) {
+    SetQuicReloadableFlag(quic_bundle_crypto_with_other_frames, flag_enabled);
+    set_perspective(Perspective::IS_SERVER);
+    QuicConfig config;
+    if (send_copt) {
+      QuicConfigPeer::SetReceivedConnectionOptions(&config, {kBCWF});
+    }
+    EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
+    EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
+    EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
+    connection_.SetFromConfig(config);
+    connection_.SetEncrypter(
+        ENCRYPTION_HANDSHAKE,
+        std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
+    connection_.SetEncrypter(
+        ENCRYPTION_FORWARD_SECURE,
+        std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
+    connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  }
+
   void TestClientRetryHandling(bool invalid_retry_tag,
                                bool missing_original_id_in_config,
                                bool wrong_original_id_in_config,
@@ -21871,6 +21892,59 @@
   EXPECT_EQ(1u, writer_->crypto_frames().size());
 }
 
+TEST_P(QuicConnectionTest, BundleCryptoWithOtherFramesDisabledWhenFlagFalse) {
+  if (!connection_.SupportsMultiplePacketNumberSpaces()) {
+    return;
+  }
+  EnableBundleCryptoWithOtherFrames(/*flag_enabled=*/false,
+                                    /*send_copt=*/true);
+  EXPECT_FALSE(connection_.bundle_crypto_with_other_frames());
+}
+
+TEST_P(QuicConnectionTest,
+       BundleCryptoWithOtherFramesDisabledWithoutConnectionOption) {
+  if (!connection_.SupportsMultiplePacketNumberSpaces()) {
+    return;
+  }
+  EnableBundleCryptoWithOtherFrames(/*flag_enabled=*/true,
+                                    /*send_copt=*/false);
+  EXPECT_FALSE(connection_.bundle_crypto_with_other_frames());
+}
+
+TEST_P(QuicConnectionTest,
+       SuppressesMidPacketWriteInCoalescedPacketAfterHandshakeKeysDropped) {
+  if (!connection_.SupportsMultiplePacketNumberSpaces()) {
+    return;
+  }
+  EnableBundleCryptoWithOtherFrames();
+  EXPECT_TRUE(connection_.bundle_crypto_with_other_frames());
+  writer_->set_perspective(Perspective::IS_SERVER);
+  QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
+  QuicConnectionPeer::SetAddressValidated(&connection_);
+  connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
+
+  EXPECT_CALL(visitor_, OnCryptoFrame(_))
+      .WillOnce([this](const QuicCryptoFrame&) {
+        EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
+        // Simulate TlsServerHandshaker::FinishHandshake() discarding HANDSHAKE
+        // keys while processing the leading HANDSHAKE packet of a coalesced
+        // [HANDSHAKE, 1-RTT] UDP packet.
+        connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
+      });
+  EXPECT_CALL(visitor_, OnStreamFrame(_))
+      .WillOnce([this](const QuicStreamFrame&) {
+        EXPECT_FALSE(connection_.framer().HasEncrypterOfEncryptionLevel(
+            ENCRYPTION_HANDSHAKE));
+        EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
+      });
+
+  QuicCryptoFrame handshake_crypto(ENCRYPTION_HANDSHAKE, 0, "ClientFinished");
+  ProcessCoalescedPacket(
+      {{1, QuicFrames{QuicFrame(&handshake_crypto)}, ENCRYPTION_HANDSHAKE},
+       {2, QuicFrames{QuicFrame(frame1_)}, ENCRYPTION_FORWARD_SECURE}});
+  EXPECT_TRUE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
+}
+
 }  // namespace
 }  // namespace test
 }  // namespace quic
diff --git a/quiche/quic/core/quic_packet_creator.cc b/quiche/quic/core/quic_packet_creator.cc
index ea05ad1..3c13099 100644
--- a/quiche/quic/core/quic_packet_creator.cc
+++ b/quiche/quic/core/quic_packet_creator.cc
@@ -1576,14 +1576,27 @@
 size_t QuicPacketCreator::GenerateRemainingCryptoFrames(
     EncryptionLevel level, size_t write_length, QuicStreamOffset offset,
     size_t total_bytes_consumed) {
+  bool full_padding = fully_pad_crypto_handshake_packets_;
+  if (bundle_crypto_with_other_frames_ && level != ENCRYPTION_INITIAL) {
+    // Only INITIAL packets need full padding. When bundling, padding HANDSHAKE
+    // packets would waste the server's amplification budget.
+    full_padding = false;
+  }
   while (
       total_bytes_consumed < write_length &&
       delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, IS_HANDSHAKE)) {
     QuicFrame frame;
     if (!ConsumeCryptoDataToFillCurrentPacket(
             level, write_length - total_bytes_consumed,
-            offset + total_bytes_consumed, fully_pad_crypto_handshake_packets_,
+            offset + total_bytes_consumed, full_padding,
             next_transmission_type_, &frame)) {
+      if (bundle_crypto_with_other_frames_ && HasPendingFrames()) {
+        // When bundling, prior retransmittable frames (or an earlier CRYPTO
+        // frame) may have filled the current packet. Flush it and retry on an
+        // empty packet.
+        FlushCurrentPacket();
+        continue;
+      }
       // The only pending data in the packet is non-retransmittable frames.
       // I'm assuming here that they won't occupy so much of the packet that a
       // CRYPTO frame won't fit.
@@ -1603,8 +1616,19 @@
       return 0;
     }
     total_bytes_consumed += frame.crypto_frame->data_length;
-    if (level != ENCRYPTION_INITIAL ||
-        frame.crypto_frame->data_length < write_length) {
+    bool should_flush = false;
+    if (!bundle_crypto_with_other_frames_) {
+      should_flush = level != ENCRYPTION_INITIAL ||
+                     frame.crypto_frame->data_length < write_length;
+    } else {
+      // When bundling, flush intermediate packets (and multi-packet INITIAL
+      // flights), but leave the final non-full packet open so other frames can
+      // join it.
+      should_flush = total_bytes_consumed < write_length ||
+                     (level == ENCRYPTION_INITIAL &&
+                      frame.crypto_frame->data_length < write_length);
+    }
+    if (should_flush) {
       FlushCurrentPacket();
     }
   }
@@ -1744,7 +1768,8 @@
   // TODO(nharper): Once we have separate packet number spaces, everything
   // should be driven by encryption level, and we should stop flushing in this
   // spot.
-  if (HasPendingRetransmittableFrames() && level != ENCRYPTION_INITIAL) {
+  if (!bundle_crypto_with_other_frames_ && HasPendingRetransmittableFrames() &&
+      level != ENCRYPTION_INITIAL) {
     FlushCurrentPacket();
   }
 
@@ -1758,7 +1783,7 @@
   }
 
   // Don't allow the handshake to be bundled with other retransmittable frames.
-  if (level != ENCRYPTION_INITIAL) {
+  if (!bundle_crypto_with_other_frames_ && level != ENCRYPTION_INITIAL) {
     FlushCurrentPacket();
   }
 
diff --git a/quiche/quic/core/quic_packet_creator.h b/quiche/quic/core/quic_packet_creator.h
index c843753..0399f5a 100644
--- a/quiche/quic/core/quic_packet_creator.h
+++ b/quiche/quic/core/quic_packet_creator.h
@@ -534,6 +534,13 @@
     }
   }
 
+  void set_bundle_crypto_with_other_frames(bool value) {
+    bundle_crypto_with_other_frames_ = value;
+  }
+  bool bundle_crypto_with_other_frames() const {
+    return bundle_crypto_with_other_frames_;
+  }
+
  private:
   friend class test::QuicPacketCreatorPeer;
 
@@ -760,6 +767,8 @@
 
   // If true, the current packet should append 0xc813 to end of the datagram.
   bool append_scone_indicator_ = false;
+
+  bool bundle_crypto_with_other_frames_ = false;
 };
 
 }  // namespace quic
diff --git a/quiche/quic/core/quic_packet_creator_test.cc b/quiche/quic/core/quic_packet_creator_test.cc
index a1ccc2d..3a8f353 100644
--- a/quiche/quic/core/quic_packet_creator_test.cc
+++ b/quiche/quic/core/quic_packet_creator_test.cc
@@ -3188,6 +3188,136 @@
 }
 
 TEST_F(QuicPacketCreatorMultiplePacketsTest,
+       ConsumeCryptoDataBundlesWithOtherFrames) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  creator_.set_bundle_crypto_with_other_frames(true);
+  creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
+  delegate_.SetCanWriteAnything();
+
+  EXPECT_CALL(delegate_, OnSerializedPacket(_))
+      .Times(2)
+      .WillRepeatedly(
+          Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket));
+
+  // Packet 0: CRYPTO frame followed by STREAM frame.
+  const std::string data = "new session ticket";
+  EXPECT_EQ(data.length(),
+            creator_.ConsumeCryptoData(ENCRYPTION_FORWARD_SECURE, data, 0));
+  EXPECT_TRUE(creator_.HasPendingFrames());
+  EXPECT_TRUE(creator_.HasPendingRetransmittableFrames());
+
+  QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
+      framer_.transport_version(), Perspective::IS_CLIENT);
+  QuicConsumedData consumed = creator_.ConsumeData(stream_id, "foo", 0, NO_FIN);
+  EXPECT_EQ(3u, consumed.bytes_consumed);
+  creator_.FlushCurrentPacket();
+  ASSERT_EQ(1u, packets_.size());
+
+  // Packet 1: STREAM frame queued before CRYPTO frame.
+  consumed = creator_.ConsumeData(stream_id, "bar", 3, FIN);
+  EXPECT_EQ(3u, consumed.bytes_consumed);
+  EXPECT_TRUE(consumed.fin_consumed);
+  EXPECT_TRUE(creator_.HasPendingRetransmittableFrames());
+  EXPECT_EQ(data.length(), creator_.ConsumeCryptoData(ENCRYPTION_FORWARD_SECURE,
+                                                      data, data.length()));
+  creator_.Flush();
+
+  ASSERT_EQ(2u, packets_.size());
+  PacketContents contents;
+  contents.num_crypto_frames = 1;
+  contents.num_stream_frames = 1;
+  contents.num_padding_frames = 0;
+  for (size_t i = 0; i < 2; ++i) {
+    CheckPacketContains(contents, i);
+    EXPECT_LT(packets_[i].encrypted_length, kDefaultMaxPacketSize);
+  }
+}
+
+TEST_F(QuicPacketCreatorMultiplePacketsTest,
+       ConsumeCryptoDataFlushesWhenFirstCryptoFrameFillsPacket) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  creator_.set_bundle_crypto_with_other_frames(true);
+  creator_.SetEncrypter(
+      ENCRYPTION_HANDSHAKE,
+      std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
+  creator_.set_encryption_level(ENCRYPTION_HANDSHAKE);
+  delegate_.SetCanWriteAnything();
+
+  EXPECT_CALL(delegate_, OnSerializedPacket(_))
+      .Times(2)
+      .WillRepeatedly(
+          Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket));
+
+  const size_t min_frame_size =
+      QuicFramer::GetMinCryptoFrameSize(1000, creator_.BytesFree());
+  const std::string first_data(creator_.BytesFree() - min_frame_size, 'a');
+  EXPECT_EQ(first_data.length(),
+            creator_.ConsumeCryptoData(ENCRYPTION_HANDSHAKE, first_data, 1000));
+  EXPECT_TRUE(creator_.HasPendingFrames());
+  EXPECT_EQ(0u, creator_.BytesFree());
+
+  const std::string second_data = "second crypto frame";
+  EXPECT_EQ(second_data.length(), creator_.ConsumeCryptoData(
+                                      ENCRYPTION_HANDSHAKE, second_data, 3000));
+  creator_.Flush();
+
+  ASSERT_EQ(2u, packets_.size());
+  EXPECT_LT(packets_[1].encrypted_length, kDefaultMaxPacketSize);
+}
+
+TEST_F(QuicPacketCreatorMultiplePacketsTest,
+       ConsumeCryptoDataDoesNotFlushFullPacketWhenNotBundling) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  // Verifies the flush-and-retry in GenerateRemainingCryptoFrames() is limited
+  // to bundling; without bundling, the legacy QUIC_BUG behavior is unchanged.
+  creator_.set_bundle_crypto_with_other_frames(false);
+  delegate_.SetCanWriteAnything();
+
+  const size_t min_frame_size =
+      QuicFramer::GetMinCryptoFrameSize(1000, creator_.BytesFree());
+  const std::string first_data(creator_.BytesFree() - min_frame_size, 'a');
+  EXPECT_EQ(first_data.length(),
+            creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, first_data, 1000));
+  EXPECT_TRUE(creator_.HasPendingFrames());
+  EXPECT_EQ(0u, creator_.BytesFree());
+
+  EXPECT_QUIC_BUG(
+      EXPECT_EQ(0u, creator_.ConsumeCryptoData(ENCRYPTION_INITIAL,
+                                               "second crypto frame", 3000)),
+      "Failed to ConsumeCryptoData");
+}
+
+TEST_F(QuicPacketCreatorMultiplePacketsTest,
+       ConsumeCryptoDataFlushesMultiPacketInitialWhenBundling) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  creator_.set_bundle_crypto_with_other_frames(true);
+  delegate_.SetCanWriteAnything();
+
+  EXPECT_CALL(delegate_, OnSerializedPacket(_))
+      .Times(2)
+      .WillRepeatedly(
+          Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket));
+
+  // INITIAL CRYPTO data spanning two packets is flushed immediately, even when
+  // bundling, so the last INITIAL packet is not left open.
+  const std::string data(1500, 'a');
+  EXPECT_EQ(data.length(),
+            creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, data, 0));
+  EXPECT_FALSE(creator_.HasPendingFrames());
+  ASSERT_EQ(2u, packets_.size());
+  EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].encrypted_length);
+  EXPECT_EQ(kDefaultMaxPacketSize, packets_[1].encrypted_length);
+}
+
+TEST_F(QuicPacketCreatorMultiplePacketsTest,
        ChaosProtection_Enabled_OnePacket) {
   TestChaosProtection(
       /*chaos_protection_enabled=*/true, /*crypto_data_length=*/1000,
diff --git a/quiche/quic/test_tools/quic_test_utils.h b/quiche/quic/test_tools/quic_test_utils.h
index ba5ff28..233e9e9 100644
--- a/quiche/quic/test_tools/quic_test_utils.h
+++ b/quiche/quic/test_tools/quic_test_utils.h
@@ -1380,6 +1380,9 @@
 
   MOCK_METHOD(void, OnCryptoFrame, (const QuicCryptoFrame&), (override));
 
+  MOCK_METHOD(void, OnHandshakeDoneFrame, (const QuicHandshakeDoneFrame&),
+              (override));
+
   MOCK_METHOD(void, OnRstStreamFrame, (const QuicRstStreamFrame&), (override));
 
   MOCK_METHOD(void, OnConnectionCloseFrame, (const QuicConnectionCloseFrame&),