Improve QUIC ACK Frequency frame handling and validation to draft-ietf-quic-ack-frequency-14.

Receiving `ACK_FREQUENCY` and `IMMEDIATE_ACK` frames previously lacked full protocol-violation enforcement, left `IMMEDIATE_ACK` state set across sent ACKs, mishandled `reordering_threshold` edge cases, and used off-by-one `ack_eliciting_threshold` defaults on the sender.

Deprecate `gfe2_reloadable_flag_quic_receive_ack_frequency` in favor of `gfe2_reloadable_flag_quic_receive_ack_frequency2`, gating `min_ack_delay` negotiation and consolidating frame-level validation in `QuicFramer`: reject unnegotiated `ACK_FREQUENCY` and `IMMEDIATE_ACK` frames with `QUIC_INVALID_FRAME_DATA`, and raise `IETF_QUIC_PROTOCOL_VIOLATION` when they arrive outside 1-RTT (`ENCRYPTION_FORWARD_SECURE`) encryption or with `requested_max_ack_delay` ≥ 16,384 ms.

Marking the flag enabling_blocked_by for now, so I can make follow-up changes without a new flag.

Protected by FLAGS_quic_reloadable_flag_quic_receive_ack_frequency2.

PiperOrigin-RevId: 1012247323
diff --git a/quiche/common/quiche_feature_flags_list.h b/quiche/common/quiche_feature_flags_list.h
index 682773d..195240c 100755
--- a/quiche/common/quiche_feature_flags_list.h
+++ b/quiche/common/quiche_feature_flags_list.h
@@ -60,7 +60,7 @@
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_pacing_remove_non_initial_burst, false, false, "If true, remove the non-initial burst in QUIC PacingSender.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_parse_cert_compression_algos_from_chlo, true, true, "If true, parse offered cert compression algorithms from received CHLOs.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_priority_respect_incremental, false, false, "If true, respect the incremental parameter of each stream in QuicWriteBlockedList.")
-QUICHE_FLAG(bool, quiche_reloadable_flag_quic_receive_ack_frequency, false, false, "When true, advertises support for ACK_FREQUENCY and IMMEDIATE_ACK from draft-ietf-quic-ack-frequency-10 and processes them correctly.")
+QUICHE_FLAG(bool, quiche_reloadable_flag_quic_receive_ack_frequency2, false, false, "When true, advertises support for ACK_FREQUENCY and IMMEDIATE_ACK from draft-ietf-quic-ack-frequency-14 and processes them correctly.")
 QUICHE_FLAG(bool, quiche_reloadable_flag_quic_reject_empty_cid_in_ncid, false, true, "If true, QUIC framer will reject NEW_CONNECTION_ID frames with empty connection IDs.")
 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.")
diff --git a/quiche/quic/core/quic_connection.cc b/quiche/quic/core/quic_connection.cc
index aae5715..2e79001 100644
--- a/quiche/quic/core/quic_connection.cc
+++ b/quiche/quic/core/quic_connection.cc
@@ -2271,10 +2271,6 @@
     return false;
   }
 
-  if (!can_receive_ack_frequency_immediate_ack_) {
-    QUIC_LOG_EVERY_N_SEC(ERROR, 120) << "Get unexpected AckFrequencyFrame.";
-    return false;
-  }
   if (frame.requested_max_ack_delay < local_min_ack_delay_) {
     QUIC_LOG_EVERY_N_SEC(ERROR, 120)
         << "Received AckFrequencyFrame with requested_max_ack_delay "
@@ -2284,16 +2280,8 @@
                     ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
     return false;
   }
-  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 3, 7);
-  if (auto packet_number_space =
-          QuicUtils::GetPacketNumberSpace(
-              last_received_packet_info_.decrypted_level) == APPLICATION_DATA) {
-    uber_received_packet_manager_.OnAckFrequencyFrame(frame);
-  } else {
-    QUIC_LOG_EVERY_N_SEC(ERROR, 120)
-        << "Get AckFrequencyFrame in packet number space "
-        << packet_number_space;
-  }
+  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 3, 8);
+  uber_received_packet_manager_.OnAckFrequencyFrame(frame);
   MaybeUpdateAckTimeout();
   return true;
 }
@@ -2309,19 +2297,8 @@
   if (!UpdatePacketContent(IMMEDIATE_ACK_FRAME)) {
     return false;
   }
-  if (!can_receive_ack_frequency_immediate_ack_) {
-    QUIC_LOG_EVERY_N_SEC(ERROR, 120) << "Got unexpected ImmediateAck Frame.";
-    return false;
-  }
-  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 1, 7);
-  if (last_received_packet_info_.decrypted_level == ENCRYPTION_FORWARD_SECURE) {
-    uber_received_packet_manager_.OnImmediateAckFrame();
-  } else {
-    QUIC_LOG_EVERY_N_SEC(ERROR, 120)
-        << "Got ImmediateAckFrame at EncryptionLevel "
-        << EncryptionLevelToString(last_received_packet_info_.decrypted_level);
-    return false;
-  }
+  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 1, 8);
+  uber_received_packet_manager_.OnImmediateAckFrame();
   should_last_packet_instigate_acks_ = false;
   MaybeUpdateAckTimeout();
   return true;
@@ -4293,7 +4270,7 @@
     // This AckFrequencyFrame is meant to only update the max_ack_delay. All
     // other values are set to the default.
     ack_frequency_frame.ack_eliciting_threshold =
-        kDefaultRetransmittablePacketsBeforeAck;
+        kDefaultRetransmittablePacketsBeforeAck - 1;
     ack_frequency_frame.reordering_threshold = 1;
     visitor_->SendAckFrequency(ack_frequency_frame);
     if (!connected_) {
diff --git a/quiche/quic/core/quic_connection.h b/quiche/quic/core/quic_connection.h
index e8a8d90..3c15a30 100644
--- a/quiche/quic/core/quic_connection.h
+++ b/quiche/quic/core/quic_connection.h
@@ -1363,7 +1363,7 @@
       PathValidationReason reason);
 
   void set_can_receive_ack_frequency_immediate_ack(bool can_receive) {
-    can_receive_ack_frequency_immediate_ack_ = can_receive;
+    framer_.set_process_ack_frequency(can_receive);
   }
 
   bool is_processing_packet() const { return framer_.is_processing_packet(); }
@@ -2530,8 +2530,6 @@
   // True if next packet is intended to consume remaining space in the
   // coalescer.
   bool fill_coalesced_packet_ : 1 = false;
-  // True if AckFrequencyFrame is supported.
-  bool can_receive_ack_frequency_immediate_ack_ : 1 = false;
   // Indicate whether coalescing is done.
   bool coalescing_done_ : 1 = false;
   // Indicate whether any ENCRYPTION_HANDSHAKE packet has been sent.
diff --git a/quiche/quic/core/quic_connection_test.cc b/quiche/quic/core/quic_connection_test.cc
index fae930a..4603f27 100644
--- a/quiche/quic/core/quic_connection_test.cc
+++ b/quiche/quic/core/quic_connection_test.cc
@@ -13491,7 +13491,7 @@
   // Send packet 101.
   SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
 
-  EXPECT_EQ(captured_frame.ack_eliciting_threshold, 10u);
+  EXPECT_EQ(captured_frame.ack_eliciting_threshold, 9u);
   EXPECT_EQ(captured_frame.requested_max_ack_delay,
             QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
 
@@ -13530,7 +13530,7 @@
 
   connection_.OnHandshakeComplete();
 
-  EXPECT_EQ(captured_frame.ack_eliciting_threshold, 2u);
+  EXPECT_EQ(captured_frame.ack_eliciting_threshold, 1u);
   EXPECT_EQ(captured_frame.requested_max_ack_delay,
             QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
 }
@@ -17103,6 +17103,118 @@
   EXPECT_FALSE(writer_->ack_frames().empty());
 }
 
+TEST_P(QuicConnectionTest, AckFrequencyDoesNotDoubleCountPacket) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  connection_.set_can_receive_ack_frequency_immediate_ack(true);
+  QuicAckFrequencyFrame ack_frequency_frame;
+  ack_frequency_frame.sequence_number = 0;
+  ack_frequency_frame.ack_eliciting_threshold = 2;
+  ack_frequency_frame.requested_max_ack_delay =
+      QuicTime::Delta::FromMilliseconds(25);
+  ack_frequency_frame.reordering_threshold = 1;
+  // A PING frame followed by ACK_FREQUENCY(ack_eliciting_threshold=2) in a
+  // single packet counts as one ack-eliciting packet and updates the threshold
+  // for subsequent packets.
+  QuicFrames frames;
+  frames.push_back(QuicFrame(QuicPingFrame()));
+  frames.push_back(QuicFrame(&ack_frequency_frame));
+  writer_->framer()->Reset();
+  ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
+  EXPECT_TRUE(writer_->ack_frames().empty());
+
+  // The second ack-eliciting packet still delays the ACK because
+  // ack_eliciting_threshold=2 requires 3 ack-eliciting packets.
+  ProcessFramePacketAtLevel(2, QuicFrame(QuicPingFrame()),
+                            ENCRYPTION_FORWARD_SECURE);
+  EXPECT_TRUE(writer_->ack_frames().empty());
+
+  // The third ack-eliciting packet reaches ack_eliciting_threshold=2 and
+  // triggers an immediate ACK.
+  ProcessFramePacketAtLevel(3, QuicFrame(QuicPingFrame()),
+                            ENCRYPTION_FORWARD_SECURE);
+  EXPECT_FALSE(writer_->ack_frames().empty());
+}
+
+TEST_P(QuicConnectionTest, UnexpectedAckFrequencyClosesConnection) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  connection_.set_can_receive_ack_frequency_immediate_ack(false);
+  QuicAckFrequencyFrame ack_frequency_frame;
+  EXPECT_CALL(visitor_,
+              OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
+  ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
+                            ENCRYPTION_FORWARD_SECURE);
+  EXPECT_FALSE(connection_.connected());
+  TestConnectionCloseQuicErrorCode(QUIC_INVALID_FRAME_DATA);
+}
+
+TEST_P(QuicConnectionTest, UnexpectedImmediateAckClosesConnection) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  connection_.set_can_receive_ack_frequency_immediate_ack(false);
+  EXPECT_CALL(visitor_,
+              OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
+  ProcessFramePacketAtLevel(1, QuicFrame(QuicImmediateAckFrame()),
+                            ENCRYPTION_FORWARD_SECURE);
+  EXPECT_FALSE(connection_.connected());
+  TestConnectionCloseQuicErrorCode(QUIC_INVALID_FRAME_DATA);
+}
+
+TEST_P(QuicConnectionTest, AckFrequencyMaxAckDelayTooLargeClosesConnection) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
+  connection_.set_can_receive_ack_frequency_immediate_ack(true);
+  QuicAckFrequencyFrame ack_frequency_frame;
+  ack_frequency_frame.requested_max_ack_delay =
+      QuicTime::Delta::FromMilliseconds(1u << 14);
+  EXPECT_CALL(visitor_,
+              OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
+  ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
+                            ENCRYPTION_FORWARD_SECURE);
+  EXPECT_FALSE(connection_.connected());
+  TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
+}
+
+TEST_P(QuicConnectionTest, AckFrequencyAtWrongEncryptionLevelClosesConnection) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  set_perspective(Perspective::IS_SERVER);
+  connection_.set_can_receive_ack_frequency_immediate_ack(true);
+  QuicAckFrequencyFrame ack_frequency_frame;
+  EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
+  EXPECT_CALL(visitor_,
+              OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
+  ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
+                            ENCRYPTION_ZERO_RTT);
+  EXPECT_FALSE(connection_.connected());
+  TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
+}
+
+TEST_P(QuicConnectionTest, ImmediateAckAtWrongEncryptionLevelClosesConnection) {
+  if (!version().IsIetfQuic()) {
+    return;
+  }
+  set_perspective(Perspective::IS_SERVER);
+  connection_.set_can_receive_ack_frequency_immediate_ack(true);
+  EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
+  EXPECT_CALL(visitor_,
+              OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
+  ProcessFramePacketAtLevel(1, QuicFrame(QuicImmediateAckFrame()),
+                            ENCRYPTION_ZERO_RTT);
+  EXPECT_FALSE(connection_.connected());
+  TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
+}
+
 TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
   if (!version().IsIetfQuic()) {
     return;
diff --git a/quiche/quic/core/quic_constants.h b/quiche/quic/core/quic_constants.h
index 46bc6fc..c6c679d 100644
--- a/quiche/quic/core/quic_constants.h
+++ b/quiche/quic/core/quic_constants.h
@@ -151,6 +151,11 @@
 // frequency).
 inline constexpr uint32_t kDefaultMinAckDelayTimeMs = 5;
 
+// Exclusive upper bound on the requested max_ack_delay in an ACK_FREQUENCY
+// frame, matching the 2^14 ms limit on the max_ack_delay transport parameter.
+inline constexpr QuicTime::Delta kMaxAckFrequencyMaxAckDelay =
+    QuicTime::Delta::FromMilliseconds(1 << 14);
+
 // Default shift of the ACK delay in the IETF QUIC ACK frame.
 inline constexpr uint32_t kDefaultAckDelayExponent = 3;
 
diff --git a/quiche/quic/core/quic_framer.cc b/quiche/quic/core/quic_framer.cc
index 582efce..a6c4883 100644
--- a/quiche/quic/core/quic_framer.cc
+++ b/quiche/quic/core/quic_framer.cc
@@ -439,6 +439,7 @@
       local_max_receive_timestamps_per_ack_(0),
       peer_receive_timestamps_exponent_(0),
       local_receive_timestamps_exponent_(0),
+      process_ack_frequency_(false),
       process_reset_stream_at_(false),
       creation_time_(creation_time),
       support_key_update_for_connection_(false),
@@ -2823,6 +2824,9 @@
              frame_type == IETF_ACK_ECN || frame_type == IETF_PING ||
              frame_type == IETF_PADDING || frame_type == IETF_CONNECTION_CLOSE;
     case ENCRYPTION_ZERO_RTT:
+      // IETF_ACK_FREQUENCY and IETF_IMMEDIATE_ACK are also disallowed in 0-RTT,
+      // and are checked in ProcessIetfFrameData after checking
+      // process_ack_frequency_.
       return !(
           IsIetfAckFrame(frame_type) || frame_type == IETF_HANDSHAKE_DONE ||
           frame_type == IETF_NEW_TOKEN || frame_type == IETF_PATH_RESPONSE ||
@@ -3187,10 +3191,24 @@
           break;
         }
         case IETF_ACK_FREQUENCY: {
+          if (!process_ack_frequency_) {
+            set_detailed_error("ACK_FREQUENCY not enabled.");
+            return RaiseError(QUIC_INVALID_FRAME_DATA);
+          }
+          if (decrypted_level != ENCRYPTION_FORWARD_SECURE) {
+            set_detailed_error(
+                absl::StrCat("ACK_FREQUENCY is unexpected at encryption level ",
+                             EncryptionLevelToString(decrypted_level)));
+            return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
+          }
           QuicAckFrequencyFrame frame;
           if (!ProcessAckFrequencyFrame(reader, &frame)) {
             return RaiseError(QUIC_INVALID_FRAME_DATA);
           }
+          if (frame.requested_max_ack_delay >= kMaxAckFrequencyMaxAckDelay) {
+            set_detailed_error("Invalid max_ack_delay_us.");
+            return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
+          }
           QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ack frequency frame "
                         << frame;
           if (!visitor_->OnAckFrequencyFrame(frame)) {
@@ -3201,6 +3219,16 @@
           break;
         }
         case IETF_IMMEDIATE_ACK: {
+          if (!process_ack_frequency_) {
+            set_detailed_error("IMMEDIATE_ACK not enabled.");
+            return RaiseError(QUIC_INVALID_FRAME_DATA);
+          }
+          if (decrypted_level != ENCRYPTION_FORWARD_SECURE) {
+            set_detailed_error(
+                absl::StrCat("IMMEDIATE_ACK is unexpected at encryption level ",
+                             EncryptionLevelToString(decrypted_level)));
+            return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
+          }
           // IMMEDIATE_ACK has no payload.
           QuicImmediateAckFrame frame;
           QUIC_DVLOG(2) << ENDPOINT << "Processing IETF immediate ack frame "
@@ -3424,11 +3452,6 @@
     set_detailed_error("Unable to read max_ack_delay_us.");
     return false;
   }
-  constexpr uint64_t kMaxAckDelayUsBound = 1u << 24;
-  if (max_ack_delay_us > kMaxAckDelayUsBound) {
-    set_detailed_error("Invalid max_ack_delay_us.");
-    return false;
-  }
   frame->requested_max_ack_delay =
       QuicTime::Delta::FromMicroseconds(max_ack_delay_us);
 
diff --git a/quiche/quic/core/quic_framer.h b/quiche/quic/core/quic_framer.h
index 433deb1..811bd10 100644
--- a/quiche/quic/core/quic_framer.h
+++ b/quiche/quic/core/quic_framer.h
@@ -344,6 +344,11 @@
     peer_receive_timestamps_exponent_ = exponent;
   }
 
+  // Allows enabling ACK_FREQUENCY and IMMEDIATE_ACK frame processing.
+  void set_process_ack_frequency(bool process_ack_frequency) {
+    process_ack_frequency_ = process_ack_frequency;
+  }
+
   bool process_reset_stream_at() const { return process_reset_stream_at_; }
 
   // Allows enabling RESET_STREAM_AT frame processing.
@@ -1153,6 +1158,8 @@
   mutable uint32_t peer_receive_timestamps_exponent_;
   // The exponent to use when reading ACK receive timestamps.
   mutable uint32_t local_receive_timestamps_exponent_;
+  // If true, process ACK_FREQUENCY and IMMEDIATE_ACK frames.
+  bool process_ack_frequency_;
   // If true, process RESET_STREAM_AT frames.
   bool process_reset_stream_at_;
   // The creation time of the connection, used to calculate timestamps.
diff --git a/quiche/quic/core/quic_framer_test.cc b/quiche/quic/core/quic_framer_test.cc
index 65a9e3d..87607d8 100644
--- a/quiche/quic/core/quic_framer_test.cc
+++ b/quiche/quic/core/quic_framer_test.cc
@@ -5301,6 +5301,7 @@
   if (!VersionIsIetfQuic(framer_.transport_version())) {
     return;
   }
+  framer_.set_process_ack_frequency(true);
 
   QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
   EXPECT_TRUE(framer_.ProcessPacket(encrypted));
@@ -5319,6 +5320,156 @@
   EXPECT_EQ(0u, frame->reordering_threshold);
 }
 
+TEST_P(QuicFramerTest, ParseAckFrequencyFrameNotEnabled) {
+  SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE);
+  // clang-format off
+  unsigned char packet[] = {
+     // type (short header, 4 byte packet number)
+     0x43,
+     // connection_id
+     0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+     // packet number
+     0x12, 0x34, 0x56, 0x78,
+
+     // ack frequency frame type
+     0x40, 0xAF,
+     // sequence_number
+     0x11,
+     // ack_eliciting_threshold
+     0x02,
+     // max_ack_delay_us = 2'5000 us
+     0x80, 0x00, 0x61, 0xA8,
+     // reordering_threshold = 0 (ignore order)
+     0x00
+  };
+  // clang-format on
+
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+
+  QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
+  EXPECT_FALSE(framer_.ProcessPacket(encrypted));
+  EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA));
+  EXPECT_EQ("ACK_FREQUENCY not enabled.", framer_.detailed_error());
+  EXPECT_TRUE(visitor_.ack_frequency_frames_.empty());
+}
+
+TEST_P(QuicFramerTest, ParseAckFrequencyFrameLargeMaxAckDelay) {
+  SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE);
+  // clang-format off
+  unsigned char valid_packet[] = {
+     // type (short header, 4 byte packet number)
+     0x43,
+     // connection_id
+     0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+     // packet number
+     0x12, 0x34, 0x56, 0x78,
+
+     // ack frequency frame type
+     0x40, 0xAF,
+     // sequence_number
+     0x11,
+     // ack_eliciting_threshold
+     0x02,
+     // max_ack_delay_us = 16'383'999 us ((1 << 14) * 1000 - 1 = 0x00F9FFFF,
+     // varint 0x80F9FFFF)
+     0x80, 0xF9, 0xFF, 0xFF,
+     // reordering_threshold = 1
+     0x01
+  };
+  unsigned char invalid_packet[] = {
+     // type (short header, 4 byte packet number)
+     0x43,
+     // connection_id
+     0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+     // packet number
+     0x12, 0x34, 0x56, 0x79,
+
+     // ack frequency frame type
+     0x40, 0xAF,
+     // sequence_number
+     0x11,
+     // ack_eliciting_threshold
+     0x02,
+     // max_ack_delay_us = 16'384'000 us ((1 << 14) * 1000 = 0x00FA0000,
+     // varint 0x80FA0000)
+     0x80, 0xFA, 0x00, 0x00,
+     // reordering_threshold = 1
+     0x01
+  };
+  // clang-format on
+
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  framer_.set_process_ack_frequency(true);
+
+  QuicEncryptedPacket valid_encrypted(AsChars(valid_packet),
+                                      std::size(valid_packet), false);
+  EXPECT_TRUE(framer_.ProcessPacket(valid_encrypted));
+  EXPECT_THAT(framer_.error(), IsQuicNoError());
+  ASSERT_EQ(1u, visitor_.ack_frequency_frames_.size());
+  EXPECT_EQ((1u << 14) * kNumMicrosPerMilli - 1,
+            visitor_.ack_frequency_frames_.front()
+                ->requested_max_ack_delay.ToMicroseconds());
+
+  QuicEncryptedPacket invalid_encrypted(AsChars(invalid_packet),
+                                        std::size(invalid_packet), false);
+  EXPECT_FALSE(framer_.ProcessPacket(invalid_encrypted));
+  EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION));
+  EXPECT_EQ("Invalid max_ack_delay_us.", framer_.detailed_error());
+  EXPECT_EQ(1u, visitor_.ack_frequency_frames_.size());
+}
+
+TEST_P(QuicFramerTest, ParseAckFrequencyFrameInZeroRtt) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  SetDecrypterLevel(ENCRYPTION_ZERO_RTT);
+  framer_.set_process_ack_frequency(true);
+  // clang-format off
+  unsigned char packet[] = {
+    // public flags (long header with packet type ZERO_RTT_PROTECTED and
+    // 4-byte packet number)
+    0xD3,
+    // version
+    QUIC_VERSION_BYTES,
+    // destination connection ID length
+    0x08,
+    // destination connection ID
+    0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+    // source connection ID length
+    0x08,
+    // source connection ID
+    0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11,
+    // long header packet length (4-byte PN + 9-byte ACK_FREQUENCY frame = 13)
+    0x0D,
+    // packet number
+    0x12, 0x34, 0x56, 0x00,
+    // ack frequency frame type
+    0x40, 0xAF,
+    // sequence_number
+    0x11,
+    // ack_eliciting_threshold
+    0x02,
+    // max_ack_delay_us = 25'000 us
+    0x80, 0x00, 0x61, 0xA8,
+    // reordering_threshold = 1
+    0x01,
+  };
+  // clang-format on
+
+  ReviseFirstByteByVersion(packet);
+  QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
+  EXPECT_FALSE(framer_.ProcessPacket(encrypted));
+  EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION));
+  EXPECT_EQ(
+      "ACK_FREQUENCY is unexpected at encryption level ENCRYPTION_ZERO_RTT",
+      framer_.detailed_error());
+  EXPECT_TRUE(visitor_.ack_frequency_frames_.empty());
+}
+
 TEST_P(QuicFramerTest, ParseImmediateAckFrame) {
   SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE);
   // clang-format off
@@ -5338,6 +5489,7 @@
   if (!VersionIsIetfQuic(framer_.transport_version())) {
     return;
   }
+  framer_.set_process_ack_frequency(true);
 
   QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
   EXPECT_TRUE(framer_.ProcessPacket(encrypted));
@@ -5351,6 +5503,73 @@
   ASSERT_EQ(1u, visitor_.immediate_ack_frames_.size());
 }
 
+TEST_P(QuicFramerTest, ParseImmediateAckFrameNotEnabled) {
+  SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE);
+  // clang-format off
+  unsigned char packet[] = {
+     // type (short header, 4 byte packet number)
+     0x43,
+     // connection_id
+     0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+     // packet number
+     0x12, 0x34, 0x56, 0x78,
+
+     // immediate ack frame type
+     0x1F,
+  };
+  // clang-format on
+
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+
+  QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
+  EXPECT_FALSE(framer_.ProcessPacket(encrypted));
+  EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA));
+  EXPECT_EQ("IMMEDIATE_ACK not enabled.", framer_.detailed_error());
+  EXPECT_TRUE(visitor_.immediate_ack_frames_.empty());
+}
+
+TEST_P(QuicFramerTest, ParseImmediateAckFrameInZeroRtt) {
+  if (!VersionIsIetfQuic(framer_.transport_version())) {
+    return;
+  }
+  SetDecrypterLevel(ENCRYPTION_ZERO_RTT);
+  framer_.set_process_ack_frequency(true);
+  // clang-format off
+  unsigned char packet[] = {
+    // public flags (long header with packet type ZERO_RTT_PROTECTED and
+    // 4-byte packet number)
+    0xD3,
+    // version
+    QUIC_VERSION_BYTES,
+    // destination connection ID length
+    0x08,
+    // destination connection ID
+    0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
+    // source connection ID length
+    0x08,
+    // source connection ID
+    0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11,
+    // long header packet length (4-byte PN + 1-byte IMMEDIATE_ACK frame = 5)
+    0x05,
+    // packet number
+    0x12, 0x34, 0x56, 0x00,
+    // immediate ack frame type
+    0x1F,
+  };
+  // clang-format on
+
+  ReviseFirstByteByVersion(packet);
+  QuicEncryptedPacket encrypted(AsChars(packet), std::size(packet), false);
+  EXPECT_FALSE(framer_.ProcessPacket(encrypted));
+  EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION));
+  EXPECT_EQ(
+      "IMMEDIATE_ACK is unexpected at encryption level ENCRYPTION_ZERO_RTT",
+      framer_.detailed_error());
+  EXPECT_TRUE(visitor_.immediate_ack_frames_.empty());
+}
+
 TEST_P(QuicFramerTest, ParseResetStreamAtFrame) {
   SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE);
   // clang-format off
diff --git a/quiche/quic/core/quic_packet_creator.cc b/quiche/quic/core/quic_packet_creator.cc
index ec31f43..794ba2d 100644
--- a/quiche/quic/core/quic_packet_creator.cc
+++ b/quiche/quic/core/quic_packet_creator.cc
@@ -2011,12 +2011,12 @@
        frame.type != PATH_RESPONSE_FRAME &&
        frame.type != PATH_CHALLENGE_FRAME && frame.type != STOP_SENDING_FRAME &&
        frame.type != DATAGRAM_FRAME && frame.type != NEW_TOKEN_FRAME &&
-       frame.type != RETIRE_CONNECTION_ID_FRAME &&
-       frame.type != ACK_FREQUENCY_FRAME))
+       frame.type != RETIRE_CONNECTION_ID_FRAME))
       << ENDPOINT << frame.type << " not allowed at "
       << packet_.encryption_level;
-  QUICHE_DCHECK(packet_.encryption_level == ENCRYPTION_FORWARD_SECURE ||
-                frame.type != IMMEDIATE_ACK_FRAME);
+  QUICHE_DCHECK(
+      packet_.encryption_level == ENCRYPTION_FORWARD_SECURE ||
+      (frame.type != ACK_FREQUENCY_FRAME && frame.type != IMMEDIATE_ACK_FRAME));
 
   if (frame.type == STREAM_FRAME) {
     if (MaybeCoalesceStreamFrame(frame.stream_frame)) {
diff --git a/quiche/quic/core/quic_received_packet_manager.cc b/quiche/quic/core/quic_received_packet_manager.cc
index be2037e..2878af8 100644
--- a/quiche/quic/core/quic_received_packet_manager.cc
+++ b/quiche/quic/core/quic_received_packet_manager.cc
@@ -304,7 +304,7 @@
 
   if (ack_now_) {
     // An IMMEDIATE_ACK frame arrived. Send an ack immediately.
-    QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 2, 7);
+    QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 2, 8);
     ack_timeout_ = now;
     return;
   }
@@ -314,8 +314,8 @@
       last_sent_largest_acked_ >= QuicPacketNumber(reordering_threshold_) &&
       (last_received_packet_number <=
        last_sent_largest_acked_ - reordering_threshold_)) {
-    if (reordering_threshold_ > 1) {
-      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 7, 7);
+    if (AckFrequencyFrameReceived()) {
+      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 7, 8);
     }
     // Ack immediately if the received packet number is less than or equal to
     // largest acked - reordering threshold.
@@ -344,7 +344,7 @@
     return;
   }
 
-  if (reordering_threshold_ == 1) {
+  if (!AckFrequencyFrameReceived()) {
     // Default behavior, not updated by ACK_FREQUENCY.
     if (HasNewMissingPackets()) {
       ack_timeout_ = now;
@@ -358,12 +358,12 @@
       // on the next packet arrival, send an ACK.
       // This is an extreme case; it would be unsurprising if it never happened
       // in production.
-      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 6, 7);
+      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 6, 8);
       ack_timeout_ = now;
       return;
     }
     if (ReorderingExceedsThreshold()) {
-      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 5, 7);
+      QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 5, 8);
       ack_timeout_ = now;
       return;
     }
@@ -404,12 +404,12 @@
 }
 
 bool QuicReceivedPacketManager::ReorderingExceedsThreshold() const {
-  if (reordering_threshold_ <= 1) {  // flag is not enabled, or there is no
-                                     // threshold.
+  QUICHE_DCHECK(AckFrequencyFrameReceived());
+  if (reordering_threshold_ == 0) {
     return false;
   }
   // Cannot get here unless an ACK_FREQUENCY frame was received.
-  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency, 4, 7);
+  QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 4, 8);
   if (!HasMissingPackets() ||
       GetLargestObserved() < QuicPacketNumber(reordering_threshold_)) {
     return false;
@@ -417,9 +417,9 @@
   // Find the next missing packet.
   QuicPacketNumber smallest_unreported_missing;
   if (last_sent_largest_acked_.IsInitialized() &&
-      last_sent_largest_acked_ >= QuicPacketNumber(reordering_threshold_)) {
+      last_sent_largest_acked_ + 1 >= QuicPacketNumber(reordering_threshold_)) {
     smallest_unreported_missing =
-        last_sent_largest_acked_ - reordering_threshold_ + 1;
+        last_sent_largest_acked_ + 1 - reordering_threshold_;
   }
   // All ACK ranges before peer_least_packet_awaiting_ack_ have already been
   // deleted, so this is the lowest packet number that has receive state.
diff --git a/quiche/quic/core/quic_received_packet_manager.h b/quiche/quic/core/quic_received_packet_manager.h
index a4d9c20..75615db 100644
--- a/quiche/quic/core/quic_received_packet_manager.h
+++ b/quiche/quic/core/quic_received_packet_manager.h
@@ -88,10 +88,7 @@
   virtual bool HasNewMissingPackets() const;
 
   // Returns true if the lowest packet number beyond largest_acked_ is more
-  // than reordering_threshold_ behind largest_unacked. Used only when
-  // reordering_threshold_ > 1.
-  // TODO(martinduke): This code can be used for reordering_threshold_ == 1
-  // as well, once we have full confidence in it.
+  // than reordering_threshold_ behind largest_unacked.
   bool ReorderingExceedsThreshold() const;
 
   virtual bool ack_frame_updated() const;
diff --git a/quiche/quic/core/quic_received_packet_manager_test.cc b/quiche/quic/core/quic_received_packet_manager_test.cc
index 233f270..b45a0a8 100644
--- a/quiche/quic/core/quic_received_packet_manager_test.cc
+++ b/quiche/quic/core/quic_received_packet_manager_test.cc
@@ -1137,6 +1137,23 @@
   RecordPacketReceipt(99, clock_.ApproximateNow());
   MaybeUpdateAckTimeout(kInstigateAck, 99);
   CheckAckTimeout(clock_.ApproximateNow());
+
+  // Packet 101 is missing; receiving Packet 102 hits reordering_threshold = 1
+  // and triggers a single immediate ACK via ReorderingExceedsThreshold().
+  RecordPacketReceipt(102, clock_.ApproximateNow());
+  MaybeUpdateAckTimeout(kInstigateAck, 102);
+  CheckAckTimeout(clock_.ApproximateNow());
+
+  // Packet 101 was already reported missing, so Packet 103 does not trigger
+  // another immediate ACK.
+  RecordPacketReceipt(103, clock_.ApproximateNow());
+  MaybeUpdateAckTimeout(kInstigateAck, 103);
+  CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime);
+
+  // Filling the hole (Packet 101) triggers an immediate ACK.
+  RecordPacketReceipt(101, clock_.ApproximateNow());
+  MaybeUpdateAckTimeout(kInstigateAck, 101);
+  CheckAckTimeout(clock_.ApproximateNow());
 }
 
 TEST_F(QuicReceivedPacketManagerTest,
diff --git a/quiche/quic/core/quic_sent_packet_manager.cc b/quiche/quic/core/quic_sent_packet_manager.cc
index 9898f7b..ba2cff1 100644
--- a/quiche/quic/core/quic_sent_packet_manager.cc
+++ b/quiche/quic/core/quic_sent_packet_manager.cc
@@ -685,7 +685,6 @@
   return !peer_min_ack_delay_.IsInfinite() && handshake_finished_;
 }
 
-// TODO(martinduke): Update to include reordering threshold.
 QuicAckFrequencyFrame QuicSentPacketManager::GetUpdatedAckFrequencyFrame()
     const {
   QuicAckFrequencyFrame frame;
@@ -695,7 +694,7 @@
     return frame;
   }
 
-  frame.ack_eliciting_threshold = kMaxRetransmittablePacketsBeforeAck;
+  frame.ack_eliciting_threshold = kMaxRetransmittablePacketsBeforeAck - 1;
   auto rtt = use_smoothed_rtt_in_ack_delay_ ? rtt_stats_.SmoothedOrInitialRtt()
                                             : rtt_stats_.MinOrInitialRtt();
   frame.requested_max_ack_delay = rtt * kPeerAckDecimationDelay;
@@ -706,6 +705,8 @@
   frame.requested_max_ack_delay =
       std::max(frame.requested_max_ack_delay,
                QuicTime::Delta::FromMilliseconds(kDefaultMinAckDelayTimeMs));
+  frame.reordering_threshold =
+      uber_loss_algorithm_.GetPacketReorderingThreshold();
   return frame;
 }
 
diff --git a/quiche/quic/core/quic_sent_packet_manager_test.cc b/quiche/quic/core/quic_sent_packet_manager_test.cc
index b0265c4..a4a423d 100644
--- a/quiche/quic/core/quic_sent_packet_manager_test.cc
+++ b/quiche/quic/core/quic_sent_packet_manager_test.cc
@@ -3168,7 +3168,8 @@
   EXPECT_EQ(frame.requested_max_ack_delay,
             std::max(rtt_stats->min_rtt() * 0.25,
                      QuicTime::Delta::FromMilliseconds(1u)));
-  EXPECT_EQ(frame.ack_eliciting_threshold, 10u);
+  EXPECT_EQ(frame.ack_eliciting_threshold, 9u);
+  EXPECT_EQ(frame.reordering_threshold, kDefaultPacketReorderingThreshold);
 }
 #endif
 
diff --git a/quiche/quic/core/quic_session.cc b/quiche/quic/core/quic_session.cc
index f38880c..5248dd1 100644
--- a/quiche/quic/core/quic_session.cc
+++ b/quiche/quic/core/quic_session.cc
@@ -249,8 +249,9 @@
         config()->SetActiveConnectionIdLimitToSend(5);
       }
     }
-  } else if (GetQuicReloadableFlag(quic_receive_ack_frequency) &&
+  } else if (GetQuicReloadableFlag(quic_receive_ack_frequency2) &&
              connection_->version().IsIetfQuic()) {
+    QUIC_RELOADABLE_FLAG_COUNT_N(quic_receive_ack_frequency2, 8, 8);
     config()->SetMinAckDelayDraft10Ms(kDefaultMinAckDelayTimeMs);
   }
   connection_->CreateConnectionIdManager();
diff --git a/quiche/quic/core/quic_session_test.cc b/quiche/quic/core/quic_session_test.cc
index 4e20fc0..54d51ae 100644
--- a/quiche/quic/core/quic_session_test.cc
+++ b/quiche/quic/core/quic_session_test.cc
@@ -3613,9 +3613,8 @@
   if (!VersionIsIetfQuic(transport_version())) {
     return;
   }
-  SetQuicReloadableFlag(quic_receive_ack_frequency, true);
   session_.Initialize();
-  if (GetQuicReloadableFlag(quic_receive_ack_frequency)) {
+  if (GetQuicReloadableFlag(quic_receive_ack_frequency2)) {
     EXPECT_EQ(session_.config()->GetMinAckDelayDraft10ToSendMs(),
               kDefaultMinAckDelayTimeMs);
   } else {
diff --git a/quiche/quic/test_tools/quic_connection_peer.cc b/quiche/quic/test_tools/quic_connection_peer.cc
index c30a98e..865e2b7 100644
--- a/quiche/quic/test_tools/quic_connection_peer.cc
+++ b/quiche/quic/test_tools/quic_connection_peer.cc
@@ -628,7 +628,7 @@
 // static
 bool QuicConnectionPeer::CanReceiveAckFrequencyFrames(
     QuicConnection* connection) {
-  return connection->can_receive_ack_frequency_immediate_ack_;
+  return QuicFramerPeer::process_ack_frequency(connection->framer_);
 }
 
 // static
diff --git a/quiche/quic/test_tools/quic_framer_peer.h b/quiche/quic/test_tools/quic_framer_peer.h
index 9cbd7c7..b309b41 100644
--- a/quiche/quic/test_tools/quic_framer_peer.h
+++ b/quiche/quic/test_tools/quic_framer_peer.h
@@ -52,6 +52,10 @@
       QuicFramer* framer, uint64_t current_received_frame_type) {
     framer->current_received_frame_type_ = current_received_frame_type;
   }
+
+  static bool process_ack_frequency(const QuicFramer& framer) {
+    return framer.process_ack_frequency_;
+  }
 };
 
 }  // namespace test
diff --git a/quiche/quic/test_tools/simple_quic_framer.cc b/quiche/quic/test_tools/simple_quic_framer.cc
index cf8df8b..7972850 100644
--- a/quiche/quic/test_tools/simple_quic_framer.cc
+++ b/quiche/quic/test_tools/simple_quic_framer.cc
@@ -363,6 +363,7 @@
 SimpleQuicFramer::SimpleQuicFramer()
     : framer_(AllSupportedVersions(), QuicTime::Zero(), Perspective::IS_SERVER,
               kQuicDefaultConnectionIdLength) {
+  framer_.set_process_ack_frequency(true);
   framer_.set_process_reset_stream_at(true);
 }
 
@@ -370,6 +371,7 @@
     const ParsedQuicVersionVector& supported_versions)
     : framer_(supported_versions, QuicTime::Zero(), Perspective::IS_SERVER,
               kQuicDefaultConnectionIdLength) {
+  framer_.set_process_ack_frequency(true);
   framer_.set_process_reset_stream_at(true);
 }
 
@@ -377,6 +379,7 @@
     const ParsedQuicVersionVector& supported_versions, Perspective perspective)
     : framer_(supported_versions, QuicTime::Zero(), perspective,
               kQuicDefaultConnectionIdLength) {
+  framer_.set_process_ack_frequency(true);
   framer_.set_process_reset_stream_at(true);
 }