Neuter initial packet in the coalescer when discarding initial keys.

PiperOrigin-RevId: 328808677
Change-Id: I34a3dbc33c52146fb88d65c60cdfc5ca8bcf1cf7
diff --git a/quic/core/quic_packet_creator.cc b/quic/core/quic_packet_creator.cc
index 358a4ae..0bf8bdc 100644
--- a/quic/core/quic_packet_creator.cc
+++ b/quic/core/quic_packet_creator.cc
@@ -544,6 +544,7 @@
     }
   }
   SerializePacket(QuicOwnedPacketBuffer(buffer, nullptr), buffer_len);
+  // TODO(b/166255274): report unrecoverable error on serialization failures.
   const size_t encrypted_length = packet_.encrypted_length;
   // Clear frames in packet_. No need to DeleteFrames since frames are owned by
   // initial_packet.
@@ -739,6 +740,10 @@
 
 void QuicPacketCreator::SerializePacket(QuicOwnedPacketBuffer encrypted_buffer,
                                         size_t encrypted_buffer_len) {
+  const bool use_queued_frames_cleaner = GetQuicReloadableFlag(
+      quic_neuter_initial_packet_in_coalescer_with_initial_key_discarded);
+  ScopedQueuedFramesCleaner cleaner(use_queued_frames_cleaner ? this : nullptr);
+
   DCHECK_LT(0u, encrypted_buffer_len);
   QUIC_BUG_IF(queued_frames_.empty() && pending_padding_bytes_ == 0)
       << "Attempt to serialize empty packet";
@@ -810,7 +815,9 @@
   }
 
   packet_size_ = 0;
-  queued_frames_.clear();
+  if (!use_queued_frames_cleaner) {
+    queued_frames_.clear();
+  }
   packet_.encrypted_buffer = encrypted_buffer.buffer;
   packet_.encrypted_length = encrypted_length;
 
@@ -1976,6 +1983,17 @@
   creator_->SetDefaultPeerAddress(old_peer_address_);
 }
 
+QuicPacketCreator::ScopedQueuedFramesCleaner::ScopedQueuedFramesCleaner(
+    QuicPacketCreator* creator)
+    : creator_(creator) {}
+
+QuicPacketCreator::ScopedQueuedFramesCleaner::~ScopedQueuedFramesCleaner() {
+  if (creator_ == nullptr) {
+    return;
+  }
+  creator_->queued_frames_.clear();
+}
+
 void QuicPacketCreator::set_encryption_level(EncryptionLevel level) {
   DCHECK(level == packet_.encryption_level || !HasPendingFrames())
       << "Cannot update encryption level from " << packet_.encryption_level