Evict obsolete packets in BandwidthSampler::OnPacketSent.

`QuicSentPacketManager::PostProcessNewlyAckedPackets` invokes congestion control loss/ack callbacks before advancing `least_unacked` in `QuicUnackedPacketMap`. If a congestion controller is stashed across a peer address migration and later restored after packet numbers have advanced, acked or lost packets left in `BandwidthSampler` prevent its packet-number-indexed queue from advancing its front index, causing unbounded queue growth or exceeding `max_tracked_packets`. In addition, `Bbr2NetworkModel` previously passed `nullptr` for `unacked_packet_map` when constructing `BandwidthSampler` for BBRv2 and BBRv3.

When `quic_sampler_remove_obsolete_packets` is enabled, evict entries older than `QuicUnackedPacketMap::GetLeastUnacked()` in `BandwidthSampler::OnPacketSent` before checking `max_tracked_packets` and emplacing new packets, and plumb `unacked_packets` into `Bbr2NetworkModel` from `Bbr2Sender` and `Bbr3Sender`.

Protected by FLAGS_quic_reloadable_flag_quic_sampler_remove_obsolete_packets.

PiperOrigin-RevId: 1021256104
diff --git a/quiche/common/quiche_feature_flags_list.h b/quiche/common/quiche_feature_flags_list.h
index 6ae1f1d..d250e67 100644
--- a/quiche/common/quiche_feature_flags_list.h
+++ b/quiche/common/quiche_feature_flags_list.h
@@ -67,6 +67,7 @@
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_reject_unusable_ech_config, false, true, "When true, calls SSL_set_reject_unusable_ech_config in TlsClientHandshaker.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_require_handshake_confirmation, true, true, "If true, require handshake confirmation for QUIC connections, functionally disabling 0-rtt handshakes.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_reset_server_params_in_reset_ssl, false, false, "If true, reset server_params_ in TlsServerHandshaker::ResetSsl().")
+QUICHE_FLAG(bool, quiche_reloadable_flag_quic_sampler_remove_obsolete_packets, false, false, "When true, BandwidthSampler::OnPacketSent removes obsolete packets below QuicUnackedPacketMap::GetLeastUnacked() before emplacing new packets.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_send_acks_after_on_can_write, false, false, "When true, QuicConnection::OnCanWrite() calls visitor_->OnCanWrite() before SendAllPendingAcks() so outgoing data frames can opportunistically bundle pending ACKs first.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_test_peer_addr_change_after_normalize, false, false, "If true, QuicConnection::ProcessValidatedPacket will use normalized address to test peer address changes.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_testonly_default_false, false, false, "A testonly reloadable flag that will always default to false.")
diff --git a/quiche/quic/core/congestion_control/bandwidth_sampler.cc b/quiche/quic/core/congestion_control/bandwidth_sampler.cc
index d5fef80..1444ed2 100644
--- a/quiche/quic/core/congestion_control/bandwidth_sampler.cc
+++ b/quiche/quic/core/congestion_control/bandwidth_sampler.cc
@@ -213,6 +213,21 @@
     last_acked_packet_sent_time_ = sent_time;
   }
 
+  if (remove_obsolete_packets_on_send_ && unacked_packet_map_ != nullptr &&
+      connection_state_map_.first_packet().IsInitialized() &&
+      unacked_packet_map_->GetLeastUnacked().IsInitialized() &&
+      connection_state_map_.first_packet() <
+          unacked_packet_map_->GetLeastUnacked()) {
+    QUIC_RELOADABLE_FLAG_COUNT_N(quic_sampler_remove_obsolete_packets, 1, 2);
+    if (packet_number - connection_state_map_.first_packet() >=
+        max_tracked_packets_) {
+      // Without removing obsolete packets, emplacing packet_number would cause
+      // connection_state_map_ to track more than max_tracked_packets_ entries.
+      QUIC_RELOADABLE_FLAG_COUNT_N(quic_sampler_remove_obsolete_packets, 2, 2);
+    }
+    RemoveObsoletePackets(unacked_packet_map_->GetLeastUnacked());
+  }
+
   if (connection_state_map_.entry_slots_used() > max_tracked_packets_) {
     if (unacked_packet_map_ != nullptr && !unacked_packet_map_->empty()) {
       QuicPacketNumber maybe_least_unacked =
diff --git a/quiche/quic/core/congestion_control/bandwidth_sampler.h b/quiche/quic/core/congestion_control/bandwidth_sampler.h
index e11e6bf..3232cda 100644
--- a/quiche/quic/core/congestion_control/bandwidth_sampler.h
+++ b/quiche/quic/core/congestion_control/bandwidth_sampler.h
@@ -616,9 +616,8 @@
   // Maximum number of tracked packets.
   const QuicPacketCount max_tracked_packets_;
 
-  // The main unacked packet map.  Used for outputting extra debugging details.
-  // May be null.
-  // TODO(vasilvv): remove this once it's no longer useful for debugging.
+  // The main unacked packet map. Used for removing obsolete packets and
+  // outputting extra debugging details. May be null.
   const QuicUnackedPacketMap* unacked_packet_map_;
 
   // Handles the actual bandwidth calculations, whereas the outer method handles
@@ -635,6 +634,9 @@
 
   // True if connection option 'BBRB' is set.
   bool limit_max_ack_height_tracker_by_send_rate_ = false;
+
+  const bool remove_obsolete_packets_on_send_ =
+      GetQuicReloadableFlag(quic_sampler_remove_obsolete_packets);
 };
 
 }  // namespace quic
diff --git a/quiche/quic/core/congestion_control/bbr2_misc.cc b/quiche/quic/core/congestion_control/bbr2_misc.cc
index 2ec5df5..2659425 100644
--- a/quiche/quic/core/congestion_control/bbr2_misc.cc
+++ b/quiche/quic/core/congestion_control/bbr2_misc.cc
@@ -84,16 +84,19 @@
 Bbr2NetworkModel::Bbr2NetworkModel(const Bbr2Params* params,
                                    QuicTime::Delta initial_rtt,
                                    QuicTime initial_rtt_timestamp,
-                                   const BandwidthSampler* old_sampler)
+                                   const BandwidthSampler* old_sampler,
+                                   const QuicUnackedPacketMap* unacked_packets)
     : params_(params),
       bandwidth_sampler_([](QuicRoundTripCount max_height_tracker_window_length,
-                            const BandwidthSampler* old_sampler) {
+                            const BandwidthSampler* old_sampler,
+                            const QuicUnackedPacketMap* unacked_packets) {
         if (old_sampler != nullptr) {
           return BandwidthSampler(*old_sampler);
         }
-        return BandwidthSampler(/*unacked_packet_map=*/nullptr,
+        return BandwidthSampler(unacked_packets,
                                 max_height_tracker_window_length);
-      }(params->initial_max_ack_height_filter_window, old_sampler)),
+      }(params->initial_max_ack_height_filter_window, old_sampler,
+                         unacked_packets)),
       min_rtt_filter_(initial_rtt, initial_rtt_timestamp),
       cwnd_gain_(params->startup_cwnd_gain),
       pacing_gain_(params->startup_pacing_gain) {}
diff --git a/quiche/quic/core/congestion_control/bbr2_misc.h b/quiche/quic/core/congestion_control/bbr2_misc.h
index 9d78bee..367e319 100644
--- a/quiche/quic/core/congestion_control/bbr2_misc.h
+++ b/quiche/quic/core/congestion_control/bbr2_misc.h
@@ -368,7 +368,8 @@
  public:
   Bbr2NetworkModel(const Bbr2Params* params, QuicTime::Delta initial_rtt,
                    QuicTime initial_rtt_timestamp,
-                   const BandwidthSampler* old_sampler);
+                   const BandwidthSampler* old_sampler,
+                   const QuicUnackedPacketMap* unacked_packets = nullptr);
 
   void OnPacketSent(QuicTime sent_time, QuicByteCount bytes_in_flight,
                     QuicPacketNumber packet_number, QuicByteCount bytes,
diff --git a/quiche/quic/core/congestion_control/bbr2_sender.cc b/quiche/quic/core/congestion_control/bbr2_sender.cc
index 730a781..e1a87ad 100644
--- a/quiche/quic/core/congestion_control/bbr2_sender.cc
+++ b/quiche/quic/core/congestion_control/bbr2_sender.cc
@@ -67,7 +67,8 @@
               max_cwnd_in_packets * kDefaultTCPMSS),
       model_(&params_, rtt_stats->SmoothedOrInitialRtt(),
              rtt_stats->last_update_time(),
-             old_sender ? &old_sender->sampler_ : nullptr),
+             old_sender != nullptr ? &old_sender->sampler_ : nullptr,
+             unacked_packets),
       initial_cwnd_(cwnd_limits().ApplyLimits(
           (old_sender) ? old_sender->GetCongestionWindow()
                        : (initial_cwnd_in_packets * kDefaultTCPMSS))),
diff --git a/quiche/quic/core/congestion_control/bbr3_sender.cc b/quiche/quic/core/congestion_control/bbr3_sender.cc
index 4fe8829..e024049 100644
--- a/quiche/quic/core/congestion_control/bbr3_sender.cc
+++ b/quiche/quic/core/congestion_control/bbr3_sender.cc
@@ -42,7 +42,8 @@
               max_cwnd_in_packets * kDefaultTCPMSS),
       model_(&params_, rtt_stats->SmoothedOrInitialRtt(),
              rtt_stats->last_update_time(),
-             old_sender ? &old_sender->sampler_ : nullptr),
+             old_sender != nullptr ? &old_sender->sampler_ : nullptr,
+             unacked_packets),
       initial_cwnd_(params_.cwnd_limits.ApplyLimits(
           (old_sender) ? old_sender->GetCongestionWindow()
                        : (initial_cwnd_in_packets * kDefaultTCPMSS))),
diff --git a/quiche/quic/core/quic_connection_test.cc b/quiche/quic/core/quic_connection_test.cc
index 635644b..31f8dcf 100644
--- a/quiche/quic/core/quic_connection_test.cc
+++ b/quiche/quic/core/quic_connection_test.cc
@@ -2347,6 +2347,124 @@
   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
 }
 
+// Regression test for b/389056732 and b/501452262.
+TEST_P(QuicConnectionTest,
+       ClientIpAndPortChangesDoNotCauseBandwidthSamplerGrowth) {
+  set_perspective(Perspective::IS_SERVER);
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  SetQuicFlag(quic_max_tracked_packet_count, 50);
+  SetQuicReloadableFlag(quic_sampler_remove_obsolete_packets, true);
+  manager_->SetSendAlgorithm(kBBR);
+  const SendAlgorithmInterface* initial_send_algorithm =
+      connection_.sent_packet_manager().GetSendAlgorithm();
+
+  QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
+  SetClientConnectionId(TestConnectionId(1));
+  connection_.CreateConnectionIdManager();
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
+  connection_.NeuterUnencryptedPackets();
+  EXPECT_CALL(visitor_, GetHandshakeState())
+      .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
+  EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(AnyNumber());
+  EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
+  EXPECT_CALL(visitor_, MaybeSendAddressToken()).Times(AnyNumber());
+  QuicConnectionPeer::SetAddressValidated(&connection_);
+
+  QuicConnectionId server_cid0 = connection_.connection_id();
+  if (server_cid0.IsEmpty()) {
+    return;
+  }
+  QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
+  QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
+                                              QuicSocketAddress());
+
+  QuicIpAddress initial_ip;
+  ASSERT_TRUE(initial_ip.FromString("192.0.2.1"));
+  const QuicSocketAddress kInitialAddr(initial_ip, /*port=*/12345);
+  QuicStreamOffset stream_offset = 0;
+
+  auto send_and_ack_on_address = [&](const QuicSocketAddress& addr,
+                                     int packets_to_send = 18) {
+    for (int p = 0; p < packets_to_send; ++p) {
+      connection_.SendStreamDataWithString(1, "a", stream_offset++, NO_FIN);
+      clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
+      QuicAckFrame ack = InitAckFrame(creator_->packet_number());
+      ProcessFramesPacketWithAddresses(
+          {QuicFrame(&ack), QuicFrame(QuicPaddingFrame())}, kSelfAddress, addr,
+          ENCRYPTION_FORWARD_SECURE);
+    }
+  };
+
+  peer_creator_.SetServerConnectionId(server_cid0);
+  ProcessFramesPacketWithAddresses({QuicFrame(frame1_)}, kSelfAddress,
+                                   kInitialAddr, ENCRYPTION_FORWARD_SECURE);
+  send_and_ack_on_address(kInitialAddr, /*packets_to_send=*/1);
+
+  // 1. With quic_sampler_remove_obsolete_packets enabled, a client changing
+  // across external IPs and ports stashes the validated path's BBR send
+  // algorithm (which has an obsolete acked packet in connection_state_map_) and
+  // advances packet numbers past max_tracked_packets_. When the client returns
+  // to its initial IP and restores the stashed BandwidthSampler, OnPacketSent
+  // evicts the obsolete entries before emplacing new packets.
+  QuicIpAddress current_ip = initial_ip;
+  for (int i = 0; i < 60; ++i) {
+    ASSERT_TRUE(
+        current_ip.FromString(absl::StrCat("198.51.100.", 1 + (i % 200))));
+    const QuicSocketAddress hop_addr(current_ip,
+                                     static_cast<uint16_t>(20000 + i));
+    ProcessFramesPacketWithAddresses(
+        {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())},
+        kSelfAddress, hop_addr, ENCRYPTION_FORWARD_SECURE);
+    send_and_ack_on_address(hop_addr);
+  }
+
+  const QuicSocketAddress kReturnAddr1(initial_ip, /*port=*/54321);
+  ProcessFramesPacketWithAddresses(
+      {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
+      kReturnAddr1, ENCRYPTION_FORWARD_SECURE);
+  EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
+            initial_send_algorithm);
+  connection_.SendStreamDataWithString(1, "a", stream_offset++, NO_FIN);
+  send_and_ack_on_address(kReturnAddr1, /*packets_to_send=*/1);
+
+  // 2. With quic_sampler_remove_obsolete_packets disabled, the same client IP
+  // and port changes cause the restored BandwidthSampler to resize
+  // connection_state_map_ across the entire packet-number gap upon sending,
+  // triggering quic_bug_10437_1.
+  SetQuicReloadableFlag(quic_sampler_remove_obsolete_packets, false);
+  manager_->SetSendAlgorithm(kCubicBytes);
+  manager_->SetSendAlgorithm(kBBR);
+  const SendAlgorithmInterface* unfixed_send_algorithm =
+      connection_.sent_packet_manager().GetSendAlgorithm();
+  send_and_ack_on_address(kReturnAddr1, /*packets_to_send=*/1);
+
+  for (int i = 0; i < 60; ++i) {
+    ASSERT_TRUE(
+        current_ip.FromString(absl::StrCat("198.51.100.", 1 + (i % 200))));
+    const QuicSocketAddress hop_addr(current_ip,
+                                     static_cast<uint16_t>(30000 + i));
+    ProcessFramesPacketWithAddresses(
+        {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())},
+        kSelfAddress, hop_addr, ENCRYPTION_FORWARD_SECURE);
+    send_and_ack_on_address(hop_addr);
+  }
+
+  const QuicSocketAddress kReturnAddr2(initial_ip, /*port=*/54322);
+  ProcessFramesPacketWithAddresses(
+      {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
+      kReturnAddr2, ENCRYPTION_FORWARD_SECURE);
+  EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
+            unfixed_send_algorithm);
+  connection_.SendStreamDataWithString(1, "a", stream_offset++, NO_FIN);
+  EXPECT_QUIC_BUG(
+      connection_.SendStreamDataWithString(1, "a", stream_offset++, NO_FIN),
+      "BandwidthSampler in-flight packet map has exceeded maximum number of "
+      "tracked packets");
+}
+
 TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
   if (!version().IsIetfQuic()) {
     return;
diff --git a/quiche/quic/core/quic_sent_packet_manager_test.cc b/quiche/quic/core/quic_sent_packet_manager_test.cc
index b4bbfb6..193b4dc 100644
--- a/quiche/quic/core/quic_sent_packet_manager_test.cc
+++ b/quiche/quic/core/quic_sent_packet_manager_test.cc
@@ -36,6 +36,7 @@
 #include "quiche/quic/core/quic_time.h"
 #include "quiche/quic/core/quic_types.h"
 #include "quiche/quic/core/quic_unacked_packet_map.h"
+#include "quiche/quic/platform/api/quic_expect_bug.h"
 #include "quiche/quic/platform/api/quic_flags.h"
 #include "quiche/quic/platform/api/quic_test.h"
 #include "quiche/quic/test_tools/mock_clock.h"
@@ -1504,6 +1505,87 @@
                                    ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
 }
 
+// Regression test for b/389056732 and b/501452262.
+TEST_F(QuicSentPacketManagerTest,
+       BandwidthSamplerRemovesObsoletePacketsAcrossMigrations) {
+  for (CongestionControlType cc_type :
+       {CongestionControlType::kBBR, CongestionControlType::kBBRv2,
+        CongestionControlType::kBBRv3}) {
+    for (bool remove_obsolete : {false, true}) {
+      SetQuicReloadableFlag(quic_sampler_remove_obsolete_packets,
+                            remove_obsolete);
+      SetQuicFlag(quic_max_tracked_packet_count, 50);
+
+      QuicConnectionStats stats;
+      QuicSentPacketManager manager(Perspective::IS_SERVER, &clock_,
+                                    QuicRandom::GetInstance(), &stats, cc_type);
+      StrictMock<MockSessionNotifier> notifier;
+      EXPECT_CALL(notifier, IsFrameOutstanding(_)).WillRepeatedly(Return(true));
+      EXPECT_CALL(notifier, HasUnackedCryptoData())
+          .WillRepeatedly(Return(false));
+      manager.SetSessionNotifier(&notifier);
+
+      auto send_packet = [&](uint64_t packet_number) {
+        SerializedPacket packet(QuicPacketNumber(packet_number),
+                                PACKET_4BYTE_PACKET_NUMBER, nullptr,
+                                kDefaultLength, false, false);
+        packet.encryption_level = ENCRYPTION_FORWARD_SECURE;
+        manager.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
+                             HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
+        clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
+      };
+      auto ack_range = [&](uint64_t start, uint64_t end, uint64_t ack_pn) {
+        manager.OnAckFrameStart(QuicPacketNumber(end - 1),
+                                QuicTime::Delta::Zero(), clock_.Now());
+        manager.OnAckRange(QuicPacketNumber(start), QuicPacketNumber(end));
+        EXPECT_EQ(
+            PACKETS_NEWLY_ACKED,
+            manager.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(ack_pn),
+                                  ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
+      };
+
+      // Send packets 1..4 and ACK 2..4 so packet 1 is declared lost.
+      // QuicSentPacketManager::PostProcessNewlyAckedPackets runs
+      // MaybeInvokeCongestionEvent before
+      // unacked_packets_.RemoveObsoletePackets advances least_unacked past 1,
+      // leaving packet 1 in the original BandwidthSampler's
+      // connection_state_map_.
+      for (uint64_t pn = 1; pn <= 4; ++pn) {
+        send_packet(pn);
+      }
+      clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
+      ack_range(2, 5, /*ack_pn=*/1);
+      EXPECT_EQ(QuicPacketNumber(5), manager.GetLeastUnacked());
+
+      // Swap out the original send algorithm on connection migration.
+      std::unique_ptr<SendAlgorithmInterface> old_send_algorithm =
+          manager.OnConnectionMigration(/*reset_send_algorithm=*/true);
+      ASSERT_NE(old_send_algorithm, nullptr);
+
+      // Advance packet numbers on the new send algorithm past
+      // max_tracked_packets_ (50 + 1000 = 1050).
+      uint64_t ack_pn = 2;
+      for (uint64_t pn = 5; pn <= 1100; ++pn) {
+        send_packet(pn);
+        ack_range(pn, pn + 1, ack_pn++);
+      }
+      EXPECT_EQ(QuicPacketNumber(1101), manager.GetLeastUnacked());
+
+      // Restore the original send algorithm and send new packets.
+      manager.SetSendAlgorithm(old_send_algorithm.release());
+      send_packet(1101);
+      if (remove_obsolete) {
+        send_packet(1102);
+      } else {
+        EXPECT_QUIC_BUG(
+            send_packet(1102),
+            "BandwidthSampler in-flight packet map has exceeded maximum "
+            "number of tracked packets");
+      }
+    }
+  }
+}
+
 // Tests that ResetCongestionControlUponPeerAddressChange() resets send
 // algorithm and RTT. And unACK'ed packets are handled correctly.
 TEST_F(QuicSentPacketManagerTest,