You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by kr...@apache.org on 2026/09/24 08:03:36 UTC

(iggy) 03/03: fix(gateways): accept idempotent Kafka producer batches

This is an automated email from the ASF dual-hosted git repository.

krishvishal pushed a commit to branch kafka-produce
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit 368a3f7307ac791b3901802dc9a9e3ce1161bc68
Author: Krishna Vishal <kr...@gmail.com>
AuthorDate: Thu Sep 24 11:37:50 2026 +0530

    fix(gateways): accept idempotent Kafka producer batches
    
    IDEMPOTENCE.md chose allocate only, so Produce ignores the producer id and a stock producer works once #4250 lands.
---
 gateways/kafka/README.md                          |  8 +++---
 gateways/kafka/docs/MANUAL_TESTING.md             |  2 +-
 gateways/kafka/src/protocol/handlers/produce.rs   | 21 ++++++++--------
 gateways/kafka/src/records.rs                     | 14 ++++-------
 gateways/kafka/tests/produce_real_bridge_tests.rs | 30 +++++++++++++++++++++++
 5 files changed, 51 insertions(+), 24 deletions(-)

diff --git a/gateways/kafka/README.md b/gateways/kafka/README.md
index 3bf74b4a9..d08969b83 100644
--- a/gateways/kafka/README.md
+++ b/gateways/kafka/README.md
@@ -77,8 +77,9 @@ Delivery through this gateway is **at-least-once**, and stays at-least-once acro
 restart. Transactions are not supported, and will not be. A retry after a timeout can write a
 record twice.
 
-Java producers must set `enable.idempotence=false`. The gateway does not serve `InitProducerId`
-yet ([#3545](https://github.com/apache/iggy/issues/3545)), and it refuses idempotent batches.
+Java producers must set `enable.idempotence=false` until the gateway serves `InitProducerId`
+([#3545](https://github.com/apache/iggy/issues/3545)). Produce already stores idempotent batches.
+It ignores their producer id, epoch and sequence, so it does not deduplicate a retry.
 
 Iggy deduplicates writes on its own partition plane, and that does not close this gap, because it
 guards the hop from the gateway to Iggy rather than the hop from the producer to the gateway.
@@ -111,6 +112,7 @@ answers for itself.
 | Topics | Creates none. Missing: 3. Bad name: 17. |
 | `timeout_ms` | Honored, max 20 s. Past it: 7. |
 | Compression | gzip, snappy, lz4. zstd from v7, else 76. |
+| Producer id, epoch, sequence | Ignored, so a retry writes twice. |
 | Timestamps over about 71 min apart | Several sends. A failure after the first can duplicate on retry. |
 | Several batches in one partition | 87, as Kafka. |
 | More records than the batch declares | 87, as Kafka. |
@@ -123,7 +125,7 @@ answers for itself.
 | ---- | ---- | ------ |
 | 10 | Record, send or partition too large, even alone | Java splits multi-record batches. Else fails. |
 | 87 | Record the gateway cannot map. Reason in `error_message` from v8. | Fails. |
-| 35 | Transactional, control or idempotent batch | Fails. |
+| 35 | Transactional or control batch | Fails. |
 | 6 | Earlier partitions used the request budget, and this one fits alone. Nothing written. | Retries. |
 | 7 | Deadline passed, or connection lost mid-send. May be written. | Retries. Can duplicate. |
 
diff --git a/gateways/kafka/docs/MANUAL_TESTING.md b/gateways/kafka/docs/MANUAL_TESTING.md
index 57844c3d4..0e94f643a 100644
--- a/gateways/kafka/docs/MANUAL_TESTING.md
+++ b/gateways/kafka/docs/MANUAL_TESTING.md
@@ -209,7 +209,7 @@ Record kcat version and exact error strings in your test log. G1 passing is the
 | 17 | INVALID_TOPIC_EXCEPTION | Produce with a bridge: bad topic name |
 | 21 | INVALID_REQUIRED_ACKS | Produce with a bridge: `acks` is not 0, 1 or -1 |
 | 29 | TOPIC_AUTHORIZATION_FAILED | Produce with a bridge: Iggy user lacks permission |
-| 35 | UNSUPPORTED_VERSION | **ApiVersions only** (KIP-511 exception), plus Produce with a bridge: transactional, control or idempotent batch. Every other API key's out-of-range version closes the connection instead - see Category B |
+| 35 | UNSUPPORTED_VERSION | **ApiVersions only** (KIP-511 exception), plus Produce with a bridge: transactional or control batch. Every other API key's out-of-range version closes the connection instead - see Category B |
 | 37 | INVALID_PARTITIONS | CreateTopics: partition count `0` or `< -1` (or any non-positive on v2–v3) |
 | 38 | INVALID_REPLICATION_FACTOR | CreateTopics: replication factor `0` or `< -1` (or any non-positive on v2–v3) |
 | 41 | NOT_CONTROLLER | CreateTopics stub (topic not created) |
diff --git a/gateways/kafka/src/protocol/handlers/produce.rs b/gateways/kafka/src/protocol/handlers/produce.rs
index 073ba224b..5f0d08a3e 100644
--- a/gateways/kafka/src/protocol/handlers/produce.rs
+++ b/gateways/kafka/src/protocol/handlers/produce.rs
@@ -532,11 +532,11 @@ const fn record_error_code(error: &RecordCodecError) -> i16 {
         // Earlier partitions spent the request budget. This one fits alone, and nothing was
         // written.
         RecordCodecError::RequestBudgetSpent => ERROR_NOT_LEADER_OR_FOLLOWER,
-        // Transactional, control or idempotent. 35 is a fatal code for these producers, so
-        // they stop instead of retrying forever.
-        RecordCodecError::TransactionalBatch
-        | RecordCodecError::ControlBatch
-        | RecordCodecError::IdempotentBatch => ERROR_UNSUPPORTED_VERSION,
+        // Transactional or control. 35 is a fatal code for these producers, so they stop instead
+        // of retrying forever.
+        RecordCodecError::TransactionalBatch | RecordCodecError::ControlBatch => {
+            ERROR_UNSUPPORTED_VERSION
+        }
         RecordCodecError::ZstdTooEarly => ERROR_UNSUPPORTED_COMPRESSION_TYPE,
         // `IggyMessage::new`'s other refusal is an empty payload, which the codec never builds.
         RecordCodecError::Iggy(_)
@@ -754,17 +754,17 @@ mod tests {
     }
 
     #[test]
-    fn given_an_idempotent_batch_when_planned_should_answer_unsupported_version() {
+    fn given_an_idempotent_batch_when_planned_should_convert_it() {
         let mut records = [record(0, b"v")];
         records[0].producer_id = 7;
         records[0].producer_epoch = 0;
         records[0].sequence = 0;
         let batch = compressed_batch(&records, Compression::None);
 
-        assert_eq!(
-            planned(&entry(0, Some(batch))).unwrap_err(),
-            ERROR_UNSUPPORTED_VERSION
-        );
+        let (_, messages) =
+            planned(&entry(0, Some(batch))).expect("a stock Java producer sends this batch");
+        assert_eq!(messages.len(), 1);
+        assert_eq!(messages[0].payload.as_ref(), b"v");
     }
 
     #[test]
@@ -974,7 +974,6 @@ mod tests {
         for error in [
             RecordCodecError::TransactionalBatch,
             RecordCodecError::ControlBatch,
-            RecordCodecError::IdempotentBatch,
         ] {
             assert_eq!(record_error_code(&error), ERROR_UNSUPPORTED_VERSION);
         }
diff --git a/gateways/kafka/src/records.rs b/gateways/kafka/src/records.rs
index 03f3c9380..0044c4773 100644
--- a/gateways/kafka/src/records.rs
+++ b/gateways/kafka/src/records.rs
@@ -150,8 +150,6 @@ pub enum RecordCodecError {
     TransactionalBatch,
     #[error("control batches are not supported")]
     ControlBatch,
-    #[error("idempotent batches are not supported, set enable.idempotence=false")]
-    IdempotentBatch,
     #[error("partition decompresses to {size} bytes, over the {limit} byte request budget")]
     BudgetExceeded { size: usize, limit: usize },
     #[error("partition needs {count} record slots, over the {limit} slot request budget")]
@@ -803,8 +801,8 @@ pub fn is_compressed(blob: &[u8]) -> bool {
 /// # Errors
 ///
 /// Returns an error when the blob holds more than one batch, when the batch is malformed or holds
-/// a record count other than the one it declares, when it is a control, transactional or
-/// idempotent batch, when it is zstd and `zstd` refuses it, or when it passes `budget`.
+/// a record count other than the one it declares, when it is a control or transactional batch,
+/// when it is zstd and `zstd` refuses it, or when it passes `budget`.
 pub fn decode_batch(
     buf: &mut Bytes,
     budget: &DecompressionBudget,
@@ -843,8 +841,9 @@ pub fn decode_batch(
 /// - One batch per partition, as Kafka requires from Produce v3.
 /// - The decoder reserves from `record_count` (`kafka-protocol-0.18.0/src/records.rs:517`), so
 ///   the count must fit the blob, plus the full budget when compressed.
-/// - Control, transactional and idempotent batches are refused: a stored message cannot carry
-///   their flags, and nothing here stops a duplicate.
+/// - Control and transactional batches are refused: a stored message cannot carry their flags.
+///   An idempotent batch passes, its producer id, epoch and sequence ignored, because a stock
+///   Java producer is idempotent. `IDEMPOTENCE.md` has why a retry is then not deduplicated.
 fn preflight(buf: &Bytes, budget: &DecompressionBudget, zstd: Zstd) -> Result<()> {
     let infos = RecordBatchDecoder::decode_batch_info(&mut buf.clone())
         .map_err(|error| RecordCodecError::Batch(error.to_string()))?;
@@ -859,9 +858,6 @@ fn preflight(buf: &Bytes, budget: &DecompressionBudget, zstd: Zstd) -> Result<()
     if info.control {
         return Err(RecordCodecError::ControlBatch);
     }
-    if info.producer_id != NO_PRODUCER_ID {
-        return Err(RecordCodecError::IdempotentBatch);
-    }
     if zstd == Zstd::Refused && info.compression == Compression::Zstd {
         return Err(RecordCodecError::ZstdTooEarly);
     }
diff --git a/gateways/kafka/tests/produce_real_bridge_tests.rs b/gateways/kafka/tests/produce_real_bridge_tests.rs
index d8404c283..97737c572 100644
--- a/gateways/kafka/tests/produce_real_bridge_tests.rs
+++ b/gateways/kafka/tests/produce_real_bridge_tests.rs
@@ -668,6 +668,36 @@ async fn given_a_transactional_batch_when_handled_should_answer_unsupported_vers
     );
 }
 
+#[tokio::test]
+#[serial]
+async fn given_an_idempotent_batch_sent_twice_when_handled_should_store_both_copies() {
+    let data_dir = tempfile::tempdir().expect("tempdir");
+    let server = TestServer::spawn(data_dir.path()).await;
+    let state = gateway_with_topic(&server, 1).await;
+
+    let mut records = [record(0, None, b"v", &[])];
+    records[0].producer_id = 7;
+    records[0].producer_epoch = 0;
+    records[0].sequence = 0;
+    let entries = [(0, batch(&records, Compression::None))];
+
+    assert_eq!(
+        produce(&state, 3, -1, TOPIC, &entries).await,
+        vec![(0, ERROR_NONE, 0)],
+        "a stock Java producer is idempotent, so its batches must land"
+    );
+    assert_eq!(
+        produce(&state, 3, -1, TOPIC, &entries).await,
+        vec![(0, ERROR_NONE, 1)],
+        "the sequence is ignored, so a resend never answers DUPLICATE_SEQUENCE_NUMBER (46)"
+    );
+    assert_eq!(
+        stored(&server, 0, 10).await.len(),
+        2,
+        "a retry writes twice until the producer pool in IDEMPOTENCE.md lands"
+    );
+}
+
 #[tokio::test]
 #[serial]
 async fn given_no_bridge_when_handled_should_still_answer_the_retriable_stub() {