You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "krishvishal (via GitHub)" <gi...@apache.org> on 2026/09/24 08:08:11 UTC

[PR] feat(gateways): send Kafka records to Iggy from the Produce handler [iggy]

krishvishal opened a new pull request, #4282:
URL: https://github.com/apache/iggy/pull/4282

   Part of #3535. With `IGGY_KAFKA_BRIDGE_ENABLED=true`, Produce now writes decoded records to Iggy using the codec from #4229 and bridge from #3533, replacing the record-dropping stub.
   
   **#3535 remains open:** its first acceptance criterion requires a real producer run. That waits for Metadata (#3534, PR #4258), which lets clients discover the topic and reach Produce.
   
   ### Writes and responses
   
   - Each partition entry normally becomes one `send_messages` call, routed to the client-selected `Partitioning::partition_id`, without balanced partitioning. Every batch is decoded into one Iggy message per record per `docs/BRIDGE_MAPPING.md`; batches are not stored as opaque bytes.
   - Partitions respond independently: a failure gets its own error code without losing other partitions' offsets. Base offsets come from send confirmations. `log_start_offset` is always `-1`, avoiding an extra round trip for a field producers do not read.
   - Produce never creates topics. Missing topics and send-side `ResourceNotFound` errors return `UNKNOWN_TOPIC_OR_PARTITION` (3).
   - Idempotent batches are accepted, but producer id, epoch and sequence are ignored, following the “allocate only” decision in `docs/IDEMPOTENCE.md`. #4250 enables default Java producers to start. Retries are not deduplicated; delivery remains at-least-once.
   
   ### Validation
   
   | Condition | Behavior |
   |---|---|
   | Multiple batches in one partition, or more records than declared | `INVALID_RECORD` (87) |
   | Transactional or control batch | `UNSUPPORTED_VERSION` (35), stopping the producer |
   | zstd compression | Supported from Produce v7; older versions return `UNSUPPORTED_COMPRESSION_TYPE` (76) |
   | `acks` = 0, 1 or -1 | Same write path |
   | Any other `acks` | `INVALID_REQUIRED_ACKS` (21) |
   
   The README documents every field and code. `ERROR_*` constants in `api.rs` now take their values from the `kafka-protocol` `ResponseError` table, preventing numeric typos.
   
   ### Limits and failure handling
   
   - **Deadline:** honors `timeout_ms`, capped at 20 seconds. Expired partitions return `REQUEST_TIMED_OUT` (7).
   - **Decode budget:** each request allows `max_frame_size` decompressed bytes and `max_frame_size / 64` records, with four requests decoding concurrently. A partition exceeding the budget alone returns `MESSAGE_TOO_LARGE` (10); one that fits alone but exceeds the remaining budget returns `NOT_LEADER_OR_FOLLOWER` (6) for retry. Large or compressed batches decode on a blocking thread.
   - **SDK backpressure:** only one send runs inside the SDK at a time because an active send cannot be cancelled. A send outliving its deadline retains the slot for up to 45 seconds. Others wait in the gateway until their own deadlines, then return 7, rather than queuing inside the SDK.
   - **Send size:** `IGGY_KAFKA_IGGY_MAX_MESSAGE_SIZE` (default `64MiB`) mirrors Iggy's `message_bus.max_message_size`; larger partitions return 10.
   - **Timestamp span:** an Iggy send supports timestamps at most `u32::MAX` microseconds apart (~71 minutes). Wider spans require multiple sends; if a later send fails, retrying can duplicate earlier records.
   - **Unknown write outcome:** send-side `Disconnected`, `EmptyResponse`, `TcpError` and `StaleClient` return 7 rather than 6. The SDK does not resend; records may already be stored.
   - **Ordering:** each Kafka connection handles one request at a time, but retries with multiple requests in flight can place a failed batch after later batches. The README requires `max.in.flight.requests.per.connection=1` for strict ordering.
   
   ### Tests and remaining work
   
   `tests/produce_real_bridge_tests.rs` adds 22 real-`iggy-server` tests to the `kafka_bridge` nextest group. They submit Kafka wire bytes and read records through the Iggy SDK, so matching mapping errors in both directions cannot hide a failure. They call `handle_request_bounded` directly, bypassing the TCP listener.
   
   After #4258 merges, run `kcat -P` and a default `kafka-console-producer.sh` through the gateway, record the results in row G2 of `docs/MANUAL_TESTING.md`, and close #3535. The console producer also requires InitProducerId from #4250, or `enable.idempotence=false`.
   
   #4250 also changes the Produce stub in `produce.rs`; if it merges first, rebase this branch and preserve its `transactional_id` guard. Other Produce TODOs, including a client pool, remain in `docs/SCOPE.md`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(gateways): send Kafka records to Iggy from the Produce handler [iggy]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #4282:
URL: https://github.com/apache/iggy/pull/4282#issuecomment-5810388817

   ## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/4282?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 87.33%. Comparing base ([`a131a2d`](https://app.codecov.io/gh/apache/iggy/commit/a131a2d32dd5d8dd2b1192522852445b925b09c4?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b5f53e6`](https://app.codecov.io/gh/apache/iggy/commit/b5f53e6f77c68f00ad8f4a7fc8779d44fb7ab745?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 1 commits behind head on master.
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master    #4282      +/-   ##
   ============================================
   - Coverage     87.65%   87.33%   -0.33%     
     Complexity     1576     1576              
   ============================================
     Files          1284     1282       -2     
     Lines        225457   225209     -248     
     Branches     188820   188782      -38     
   ============================================
   - Hits         197626   196685     -941     
   - Misses        23101    23788     +687     
   - Partials       4730     4736       +6     
   ```
   
   | [Components](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [Rust Core](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `88.76% <ø> (ø)` | |
   | [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `68.70% <ø> (ø)` | |
   | [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `77.35% <ø> (ø)` | |
   | [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `90.97% <ø> (ø)` | |
   | [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.67% <ø> (ø)` | |
   | [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `90.76% <ø> (-5.61%)` | :arrow_down: |
   | [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/4282/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `70.05% <ø> (ø)` | |
   [see 53 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/4282/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(gateways): send Kafka records to Iggy from the Produce handler [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #4282:
URL: https://github.com/apache/iggy/pull/4282#discussion_r4092877519


##########
gateways/kafka/src/records.rs:
##########
@@ -665,78 +782,99 @@ impl Write for BudgetedWriter<'_> {
     }
 }
 
-/// Decodes every record batch a Produce partition entry carries.
-///
-/// A partition's `records` field is one blob that holds one or more batches back to back, so
-/// this drains `buf` rather than reading a single batch.
+/// Whether a partition may hold zstd. Produce allows it from v7.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Zstd {
+    Allowed,
+    Refused,
+}
+
+/// Whether the first batch in `blob` is compressed. Byte 22 is the low byte of its attributes.
+#[must_use]
+pub fn is_compressed(blob: &[u8]) -> bool {
+    blob.get(22)
+        .is_some_and(|attributes| attributes & 0b111 != 0)
+}
+
+/// Decodes the one record batch a Produce partition carries.
 ///
 /// # Errors
 ///
-/// Returns an error when a batch is malformed, when it declares more records than the request
-/// can hold, when it is a control or transactional batch, or when the request decompresses to
-/// more than `budget` allows.
-pub fn decode_batches(buf: &mut Bytes, budget: &DecompressionBudget) -> Result<Vec<Record>> {
-    preflight(buf, budget)?;
-
-    let mut records = Vec::new();
-    while buf.has_remaining() {
-        let set = RecordBatchDecoder::decode_with_custom_compression(
-            buf,
-            Some(|compressed: &mut Bytes, compression| decompress(compressed, compression, budget)),
-        )
-        .map_err(|error| budget.reason(&error.to_string()))?;
-        records.extend(set.records);
+/// 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 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,
+    zstd: Zstd,
+) -> Result<Vec<Record>> {
+    budget.start_entry();
+    preflight(buf, budget, zstd)?;
+    if !buf.has_remaining() {
+        return Ok(Vec::new());
+    }
+
+    let walked = Cell::new(0);
+    let set = RecordBatchDecoder::decode_with_custom_compression(
+        buf,
+        Some(
+            |compressed: &mut Bytes, compression| -> anyhow::Result<Bytes> {
+                let (records, count) = decompress(compressed, compression, budget)?;
+                walked.set(count);
+                Ok(records)
+            },
+        ),
+    )
+    .map_err(|error| budget.reason(&error.to_string()))?;
+    // The decoder stops at the declared count and drops the rest.
+    if set.records.len() != walked.get() {
+        return Err(RecordCodecError::RecordCountMismatch {
+            declared: set.records.len(),
+            walked: walked.get(),
+        });
     }
-    Ok(records)
+    Ok(set.records)

Review Comment:
   Trailing bytes after the single v2 batch are silently dropped and the partition answers success.
   `decode_batch_info` breaks on the first non-v2 magic (`kafka-protocol-0.18.0/src/records.rs:501-504`), so `preflight` sees one batch, the decoder reads one, and nothing checks what is left.
   Probe: `[valid v2 batch][>=17 bytes, byte 16 != 2]` returns `Ok(1)` with the tail still in `buf`. Only tails under 17 B error.
   Master's `decode_batches` looped `while buf.has_remaining()`, so this is new, and it contradicts the "several batches -> 87" rule.
   Fix: `if buf.has_remaining() { return Err(RecordCodecError::Batch(..)) }` after decode, or treat a non-v2 magic in `preflight` as an error (cheaper, runs before decompression).



##########
gateways/kafka/src/records.rs:
##########
@@ -639,24 +734,46 @@ impl DecompressionBudget {
 /// An `io::Write` sink that stops at the budget rather than after it.
 ///
 /// Charging the output once it exists is too late: the decompressor has already allocated it.
+/// Past the budget it counts and drops the bytes, to tell "too large" (10) from "retry" (6).
 struct BudgetedWriter<'a> {
     out: BytesMut,
     budget: &'a DecompressionBudget,
+    spilled: usize,
 }
 
 impl<'a> BudgetedWriter<'a> {
     fn new(budget: &'a DecompressionBudget) -> Self {
         Self {
             out: BytesMut::new(),
             budget,
+            spilled: 0,
         }
     }
+
+    /// Charges `len` bytes. `false` once past the budget: counted, not kept.
+    fn admit(&mut self, len: usize) -> io::Result<bool> {
+        if self.spilled == 0 && self.budget.take(len) {
+            return Ok(true);
+        }
+        self.spilled = self.spilled.saturating_add(len);

Review Comment:
   Once the request budget is spent, every later compressed partition is still inflated up to `max_frame_size` before `into_output` answers 6. `check_alone` only trips past `bytes`.
   8 MiB of zstd zeros is ~300 B and `MAX_REQUEST_ELEMENTS` allows 4096 partitions, so a ~1.3 MB request costs ~32 GiB of inflate CPU, bounded only by the 20 s deadline.
   Four such connections hold all `PRODUCE_SLOTS`, and every legit Produce times out with 7. The old `charge` refused at the first over-budget write.
   Fix: after the first `RequestBudgetSpent` in a request, answer 6 for later partitions without decoding. The retry alone still gets a correct 10. Don't trust gzip ISIZE as a size hint, since the client writes it.



##########
gateways/kafka/src/protocol/handlers/produce.rs:
##########
@@ -62,48 +105,465 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
     // (still advertised as the min in ApiVersions per KAFKA-18659) can be neither decoded nor
     // encoded by the crate - there is no parseable response at these versions regardless of
     // body content. `acks` is always the first i16 on the wire there (`transactional_id` was
-    // added in v3), so it's peeked by hand: acks=0 must keep the connection open per the wire
-    // protocol's fire-and-forget rule even though no response can ever be encoded for it.
+    // added in v3), so it's peeked by hand.
     if api_version < 3 {
         let acks = match body.get(0..2) {
             Some(&[hi, lo]) => Some(i16::from_be_bytes([hi, lo])),
             _ => None,
         };
         return match acks {
-            Some(0) | None => HandleOutcome::NoResponse,
+            // No bridge: nothing is stored at any version, so keep the connection.
+            Some(ACKS_NONE) | None if state.bridge.is_none() => HandleOutcome::NoResponse,
+            // With a bridge, v3+ stores records. Close so the client sees these were not.
+            Some(ACKS_NONE) | None => HandleOutcome::Close,
             Some(_) => unsupported_version_response(API_KEY_PRODUCE, api_version, |v| {
                 encode_error_response(v, ERROR_UNSUPPORTED_VERSION)
             }),
         };
     }
-    match decode_guarded::<ProduceRequest>(api_version, body, |v, b| {
+    let request = match decode_guarded::<ProduceRequest>(api_version, body, |v, b| {
         validate_produce_shape(v, b, state.max_frame_size)
     }) {
-        // acks=0 is fire-and-forget: the client isn't reading a response, so
-        // sending one desyncs the next correlation id it expects.
-        Ok(req) if req.acks == 0 => HandleOutcome::NoResponse,
-        // `api_version` is always in `[3, supported_max]` here: the `< 3` case returned above,
-        // and the `> max` case returned at the top of this function - so it is always within
-        // `SUPPORTED_RANGES`' Produce row and an `is_supported_version` re-check can never fail.
-        Ok(req) => respond_or_close(encode_response(api_version, &req), "Produce"),
+        Ok(request) => request,
         Err(error) => {
-            // `kafka_protocol` decodes the whole request in one shot; a failure anywhere gives
-            // no partial-field access, so `acks` is unknowable here (unlike the pre-migration
-            // field-by-field decoder, which could still know `acks` on a later-field failure).
-            // Responding risks desyncing an acks=0 fire-and-forget client's correlation stream,
-            // so every Produce decode failure now stays silent - a behavior change from the
-            // hand-rolled decoder, which answered with INVALID_REQUEST when `acks` was known and
-            // nonzero.
-            // debug!, not warn!: the body is attacker-controlled, not operator-actionable, and
-            // a client looping malformed bodies on one connection (never disconnected - this
-            // arm returns NoResponse) has no rate limit here.
-            tracing::debug!(%error, "failed to decode Produce request (no response)");
+            // `acks` is unknown, so no reply is safe. Close, as Kafka does.
+            tracing::debug!(%error, "failed to decode Produce request, closing");
+            return HandleOutcome::Close;
+        }
+    };
+
+    let Some(bridge) = state.bridge.as_deref() else {
+        return stub_outcome(api_version, &request);
+    };
+
+    // `acks=0` is legal, so a request failing this check is one the client waits on.
+    if !matches!(request.acks, ACKS_NONE | ACKS_LEADER | ACKS_ALL) {
+        tracing::debug!(
+            acks = request.acks,
+            "Produce request names an unknown acks value"
+        );
+        return respond_or_close(
+            encode_uniform_response(api_version, &request, ERROR_INVALID_REQUIRED_ACKS),
+            "Produce",
+        );
+    }
+
+    // Before planning, not after: the client waits through decompression too.
+    let deadline = Deadline::new(request.timeout_ms);
+    let Ok(Ok(_slot)) = tokio::time::timeout_at(deadline.at, state.produce_slots.acquire()).await
+    else {
+        tracing::debug!("Produce deadline passed while waiting for a slot");
+        return if request.acks == ACKS_NONE {
+            HandleOutcome::Close
+        } else {
+            respond_or_close(
+                encode_uniform_response(api_version, &request, ERROR_REQUEST_TIMED_OUT),
+                "Produce",
+            )
+        };
+    };
+    let budget = DecompressionBudget::new(
+        state.max_frame_size,
+        state.max_frame_size / FRAME_BYTES_PER_RECORD,
+    );
+    let zstd = if api_version >= ZSTD_MIN_VERSION {
+        Zstd::Allowed
+    } else {
+        Zstd::Refused
+    };
+    let responses = write_request(bridge, &request, budget, zstd, deadline).await;
+
+    // Kafka closes an `acks=0` connection on any error, so the client refreshes metadata.
+    if request.acks == ACKS_NONE {
+        let failed = responses
+            .iter()
+            .flat_map(|topic| &topic.partition_responses)
+            .any(|partition| partition.error_code != ERROR_NONE);
+        return if failed {
+            HandleOutcome::Close
+        } else {
             HandleOutcome::NoResponse
+        };
+    }
+    respond_or_close(encode_written_response(api_version, responses), "Produce")
+}
+
+/// No bridge: answer retriable so clients keep their data instead of trusting a discarded write.
+fn stub_outcome(api_version: i16, request: &ProduceRequest) -> HandleOutcome {
+    // acks=0 is fire-and-forget: the client isn't reading a response, so
+    // sending one desyncs the next correlation id it expects.
+    if request.acks == ACKS_NONE {
+        return HandleOutcome::NoResponse;
+    }
+    respond_or_close(encode_response(api_version, request), "Produce")
+}
+
+/// When a request stops writing.
+#[derive(Clone, Copy)]
+struct Deadline {
+    at: tokio::time::Instant,
+    /// This gateway's ceiling set it, not the client's `timeout_ms`.
+    ceiling: bool,
+}
+
+impl Deadline {
+    fn new(timeout_ms: i32) -> Self {
+        let wait = request_timeout(timeout_ms);
+        Self {
+            at: tokio::time::Instant::now() + wait,
+            ceiling: wait == MAX_REQUEST_DEADLINE,
+        }
+    }
+
+    fn passed(self) -> bool {
+        tokio::time::Instant::now() >= self.at
+    }
+}
+
+/// Why a partition was not written. `message` reaches the client from Produce v8.
+struct Refusal {
+    code: i16,
+    message: Option<String>,
+}
+
+impl From<i16> for Refusal {
+    fn from(code: i16) -> Self {
+        Self {
+            code,
+            message: None,
+        }
+    }
+}
+
+impl From<RecordCodecError> for Refusal {
+    fn from(error: RecordCodecError) -> Self {
+        Self {
+            code: record_error_code(&error),
+            message: Some(error.to_string()),
         }
     }
 }
 
-/// Well-formed Produce response with a single placeholder topic/partition.
+/// Converts and sends one partition at a time, in request order.
+///
+/// One budget for the whole request, so many partitions cannot each take the full allowance.
+/// Only one partition's messages live at a time. The budget is owned here and borrowed only in
+/// sync calls: a borrow held across an await makes the connection task `!Send`.
+///
+/// Sequential: the one `IggyClient` behind the bridge is lockstep, so concurrent sends would
+/// just queue on its stream mutex (see the README's "Concurrency ceiling").
+async fn write_request(
+    bridge: &IggyBridge,
+    request: &ProduceRequest,
+    budget: DecompressionBudget,
+    zstd: Zstd,
+    deadline: Deadline,
+) -> Vec<TopicProduceResponse> {
+    let max_send = bridge.max_send_bytes();
+    let mut topics = Vec::with_capacity(request.topic_data.len());
+    for topic in &request.topic_data {
+        let name = topic.name.as_str();
+        let target = bridge.topic_target(name);
+        let mut responses = Vec::with_capacity(topic.partition_data.len());
+        for partition in &topic.partition_data {
+            let outcome = match &target {
+                // Skip the decode. The answer is 7 either way.
+                Ok(_) if deadline.passed() => Err(ERROR_REQUEST_TIMED_OUT.into()),
+                Ok(target) => {
+                    let planned = plan(&budget, zstd, name, partition, max_send);
+                    match planned {
+                        Ok((id, messages)) => {
+                            send_runs(bridge, target, name, id, messages, deadline)
+                                .await
+                                .map_err(Refusal::from)
+                        }
+                        Err(refusal) => Err(refusal),
+                    }
+                }
+                Err(error) => Err(refusal_code(name, error).into()),
+            };
+            responses.push(partition_outcome(partition.index, outcome));
+            // Planning is sync CPU work. Let other connections on this worker run.
+            tokio::task::yield_now().await;
+        }
+        topics.push(
+            TopicProduceResponse::default()
+                .with_name(topic.name.clone())
+                .with_partition_responses(responses),
+        );
+    }
+    topics
+}
+
+/// [`plan_partition`], off the async worker for a large or compressed partition, so other
+/// connections keep running. On a current-thread runtime it runs in place.
+fn plan(
+    budget: &DecompressionBudget,
+    zstd: Zstd,
+    kafka_topic: &str,
+    partition: &PartitionProduceData,
+    max_send: u64,
+) -> std::result::Result<(u32, Vec<IggyMessage>), Refusal> {
+    let run = || plan_partition(budget, zstd, kafka_topic, partition, max_send);
+    let heavy = partition
+        .records
+        .as_ref()
+        .is_some_and(|blob| blob.len() >= BLOCKING_PLAN_BYTES || is_compressed(blob));
+    if heavy && Handle::current().runtime_flavor() == RuntimeFlavor::MultiThread {
+        tokio::task::block_in_place(run)
+    } else {
+        run()
+    }
+}
+
+fn partition_outcome(
+    index: i32,
+    outcome: std::result::Result<Option<u64>, Refusal>,
+) -> PartitionProduceResponse {
+    match outcome {
+        // An offset past `i64::MAX` has no response field to fit in, so it reads as unknown
+        // rather than as a saturated number a client would take for a real position.
+        Ok(base_offset) => partition_response(index, ERROR_NONE).with_base_offset(
+            base_offset.map_or(UNKNOWN_OFFSET, |offset| {
+                i64::try_from(offset).unwrap_or(UNKNOWN_OFFSET)
+            }),
+        ),
+        Err(Refusal { code, message }) => {
+            partition_response(index, code).with_error_message(message.map(StrBytes::from_string))
+        }
+    }
+}
+
+/// One partition's batch in, its messages out. A batch that cannot be mapped is refused whole,
+/// never half-stored.
+fn plan_partition(
+    budget: &DecompressionBudget,
+    zstd: Zstd,
+    kafka_topic: &str,
+    partition: &PartitionProduceData,
+    max_send: u64,
+) -> std::result::Result<(u32, Vec<IggyMessage>), Refusal> {
+    // The records are not what is wrong with a negative index, so not `INVALID_RECORD`.
+    let Ok(partition_id) = u32::try_from(partition.index) else {
+        return Err(ERROR_UNKNOWN_TOPIC_OR_PARTITION.into());
+    };
+    // Nothing to append. Answering success would name an offset for a write that never happened.
+    let Some(blob) = partition.records.as_ref() else {
+        return Err(ERROR_INVALID_RECORD.into());
+    };
+    let refuse = |error: RecordCodecError| {
+        tracing::debug!(%error, kafka_topic, partition_id, "refused a Produce record batch");
+        Refusal::from(error)
+    };
+
+    // The clone is a refcount, and `decode_batch` drains what it is given.
+    let records = decode_batch(&mut blob.clone(), budget, zstd).map_err(refuse)?;
+    // An empty blob decodes to no batch rather than to an error, so this rules on it.
+    if records.is_empty() {
+        return Err(ERROR_INVALID_RECORD.into());
+    }
+
+    let mut messages = Vec::with_capacity(records.len());
+    let mut size = 0u64;
+    for record in &records {
+        let message = to_iggy(record).map_err(refuse)?;
+        size = size.saturating_add(message.get_size_bytes().as_bytes_u64());
+        messages.push(message);
+    }
+    // Over this, Iggy drops the frame, and the client retries on 7 until it gives up.
+    if size > max_send {
+        tracing::debug!(
+            size,
+            kafka_topic,
+            partition_id,
+            "Produce partition too large for one Iggy send"
+        );
+        return Err(ERROR_MESSAGE_TOO_LARGE.into());
+    }
+    Ok((partition_id, messages))
+}
+
+/// The shorter of the client's `timeout_ms` and this gateway's ceiling.
+///
+/// Honoring the client's budget narrows, not closes, the window for its retry to duplicate a
+/// write still running here: this clock starts when the request is read, after any pipelined one.
+/// A non-positive value means no preference, not "fail without trying".
+fn request_timeout(timeout_ms: i32) -> Duration {
+    u64::try_from(timeout_ms)
+        .ok()
+        .filter(|ms| *ms > 0)
+        .map_or(MAX_REQUEST_DEADLINE, Duration::from_millis)
+        .min(MAX_REQUEST_DEADLINE)
+}
+
+/// Splits `messages` into in-order runs whose timestamp span fits one Iggy send.
+///
+/// A record with no timestamp stores 0, so next to real timestamps it starts a new run.
+fn send_spans(messages: &[IggyMessage]) -> Vec<Range<usize>> {
+    let mut spans = Vec::with_capacity(1);
+    let mut start = 0;
+    let (mut low, mut high) = (u64::MAX, 0u64);
+    for (index, message) in messages.iter().enumerate() {
+        let timestamp = message.header.origin_timestamp;
+        let (next_low, next_high) = (low.min(timestamp), high.max(timestamp));
+        if next_high - next_low > MAX_SEND_SPAN_MICROS {

Review Comment:
   The client controls the number of sends per partition. Alternating timestamps more than 71 min apart, or -1 (stored as 0) mixed with real ones, give one Iggy send per record.
   At 131072 records that is 131k sequential round trips through the single global `send_slot` and 131k one-message batches on the server, all inside one `PRODUCE_SLOTS` permit.
   Each run also re-acquires the FIFO slot (`send_runs` -> `send_in_slot`), so another connection's send can land between runs and one Kafka batch ends up non-contiguous.
   Fix: clamp `origin_timestamp` into one span and carry the real timestamp in a `kafka.ts`-style header, so each partition stays one send. Rejecting with 87 past a cap would permanently refuse legitimate backfill.
   If you hold one permit across runs instead, cap the runs first, or one partition can hold the global slot for the whole deadline.



##########
gateways/kafka/src/records.rs:
##########
@@ -639,24 +734,46 @@ impl DecompressionBudget {
 /// An `io::Write` sink that stops at the budget rather than after it.
 ///
 /// Charging the output once it exists is too late: the decompressor has already allocated it.
+/// Past the budget it counts and drops the bytes, to tell "too large" (10) from "retry" (6).
 struct BudgetedWriter<'a> {
     out: BytesMut,
     budget: &'a DecompressionBudget,
+    spilled: usize,
 }
 
 impl<'a> BudgetedWriter<'a> {
     fn new(budget: &'a DecompressionBudget) -> Self {
         Self {
             out: BytesMut::new(),
             budget,
+            spilled: 0,
         }
     }
+
+    /// Charges `len` bytes. `false` once past the budget: counted, not kept.
+    fn admit(&mut self, len: usize) -> io::Result<bool> {
+        if self.spilled == 0 && self.budget.take(len) {
+            return Ok(true);
+        }
+        self.spilled = self.spilled.saturating_add(len);
+        self.budget.check_alone(self.spilled)?;
+        Ok(false)
+    }
+
+    /// The output, or a refusal if any of it spilled.
+    fn into_output(self) -> io::Result<Bytes> {
+        if self.spilled > 0 {
+            return Err(self.budget.refuse(RecordCodecError::RequestBudgetSpent));

Review Comment:
   A refused partition keeps what `take` already debited from `remaining`: neither this path nor the `preflight` `charge_records` refunds it.
   So one oversized or spilled partition starves every partition after it in the same request.
   With Java defaults (`max.request.size` 1 MB) and zstd/gzip on JSON-like data (>8x ratio), the 8 MiB decompressed budget is hit on ordinary traffic, so trailing partitions get 6 on every request.
   Each 6 is an `InvalidMetadataException` in Java and librdkafka, so a metadata refresh storm follows once Metadata lands.
   Fix: refund the entry's charge on refusal, and size the budget as a ratio of the frame or make it configurable.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(gateways): send Kafka records to Iggy from the Produce handler [iggy]

Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal merged PR #4282:
URL: https://github.com/apache/iggy/pull/4282


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org