From c87f9a5f99fbf84e3070fbcd2737db7089677eb8 Mon Sep 17 00:00:00 2001 From: W <184799977+waw666waw666@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:39:22 +0800 Subject: [PATCH] Consumer: keep raising record errors instead of spinning in poll() When a deserializer (or a per-record CRC check) failed in the middle of a fetched batch, the error was raised once and the record generator was left exhausted but still in line. The next poll() then looped forever in fetched_records(), taking no records and never returning, regardless of timeout_ms. Keep raising the same error until the partition records are drained, and skip records below the fetch offset before validating or deserializing them, so seeking past a bad record in the middle of a batch lets the consumer continue. --- kafka/consumer/fetcher.py | 47 +++++++++++------------- test/consumer/test_fetcher.py | 69 +++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 25 deletions(-) diff --git a/kafka/consumer/fetcher.py b/kafka/consumer/fetcher.py index 919be87c9..9ceef5aa5 100644 --- a/kafka/consumer/fetcher.py +++ b/kafka/consumer/fetcher.py @@ -1613,23 +1613,9 @@ def __init__(self, fetch_offset, tp, records, ) self.metric_aggregator = metric_aggregator self.check_crcs = check_crcs - self.record_iterator = itertools.dropwhile( - self._maybe_skip_record, - self._unpack_records(tp, records, key_deserializer, value_deserializer)) + self.record_iterator = self._unpack_records(tp, records, key_deserializer, value_deserializer) self.on_drain = on_drain - self._next_inline_exception = None - - def _maybe_skip_record(self, record): - # When fetching an offset that is in the middle of a - # compressed batch, we will get all messages in the batch. - # But we want to start 'take' at the fetch_offset - # (or the next highest offset in case the message was compacted) - if record.offset < self.fetch_offset: - log.debug("Skipping message offset: %s (expecting %s)", - record.offset, self.fetch_offset) - return True - else: - return False + self._cached_exception = None # For truthiness evaluation def __bool__(self): @@ -1638,27 +1624,28 @@ def __bool__(self): def drain(self): if self.record_iterator is not None: self.record_iterator = None - self._next_inline_exception = None + self._cached_exception = None if self.metric_aggregator: self.metric_aggregator.record(self.topic_partition, self.bytes_read, self.records_read) self.on_drain(self) - def _maybe_raise_next_inline_exception(self): - if self._next_inline_exception: - exc, self._next_inline_exception = self._next_inline_exception, None - raise exc - def take(self, n=None): - self._maybe_raise_next_inline_exception() + # A generator cannot be resumed after it raises, so once unpacking + # fails (corrupt record, deserializer error) there is nothing left + # to iterate. Keep raising the same error until the records are + # drained, e.g. because the user seeks past the failed offset. + if self._cached_exception is not None: + raise self._cached_exception records = [] try: # Note that records.extend(iter) will extend partially when exception raised mid-stream records.extend(itertools.islice(self.record_iterator, 0, n)) except Exception as e: + self._cached_exception = e if not records: raise e - # To be thrown in the next call of this method - self._next_inline_exception = e + # Records before the failed one are returned now; the error is + # raised by the next call. return records def _unpack_records(self, tp, records, key_deserializer, value_deserializer): @@ -1706,6 +1693,16 @@ def _unpack_records(self, tp, records, key_deserializer, value_deserializer): continue for record in batch: + # When fetching an offset that is in the middle of a + # batch, we will get all messages in the batch. + # But we want to start 'take' at the fetch_offset + # (or the next highest offset in case the message was compacted). + # Skip before validating or deserializing, so a bad record + # that the user has seeked past does not fail the fetch again. + if record.offset < self.fetch_offset: + log.debug("Skipping message offset: %s (expecting %s)", + record.offset, self.fetch_offset) + continue if self.check_crcs and not record.validate_crc(): raise Errors.CorruptRecordError( "Record for partition %s at offset %s failed crc check" % ( diff --git a/test/consumer/test_fetcher.py b/test/consumer/test_fetcher.py index 6ead36575..4621a130e 100644 --- a/test/consumer/test_fetcher.py +++ b/test/consumer/test_fetcher.py @@ -836,6 +836,75 @@ def test__unpack_records_corrupted(mocker): assert len(records) == 2 with pytest.raises(Errors.CorruptRecordError): part_records.take(10) + # The error is not lost: it is raised again until the records are drained + with pytest.raises(Errors.CorruptRecordError): + part_records.take(10) + + +class _FailingDeserializer(Deserializer): + def deserialize(self, topic, headers, data): + if data == b'bad': + raise ValueError('cannot deserialize') + return data + + +def test_partition_records_keeps_raising_deserialization_error(): + tp = TopicPartition('foo', 0) + messages = [(None, b'a', None), (None, b'bad', None), (None, b'c', None)] + memory_records = MemoryRecords(_build_record_batch(messages)) + part_records = Fetcher.PartitionRecords( + 0, tp, memory_records, value_deserializer=_FailingDeserializer()) + assert [r.value for r in part_records.take(10)] == [b'a'] + assert part_records.next_fetch_offset == 1 + for _ in range(3): + with pytest.raises(ValueError): + part_records.take(10) + assert part_records + assert part_records.next_fetch_offset == 1 + part_records.drain() + assert not part_records + + +@pytest.mark.timeout(10, method='signal') +def test_fetched_records_keeps_raising_deserialization_error(fetcher, topic): + fetcher.config['value_deserializer'] = _FailingDeserializer() + tp = TopicPartition(topic, 0) + msgs = [(None, b'a', None), (None, b'b', None), (None, b'bad', None), (None, b'c', None)] + fetcher._completed_fetches.append(_build_completed_fetch(tp, msgs)) + + records, _ = fetcher.fetched_records() + assert [r.value for r in records[tp]] == [b'a', b'b'] + assert fetcher._subscriptions.position(tp).offset == 2 + + # Every later call raises again (rather than returning nothing while the + # partition records stay in line, which made fetched_records() loop forever) + for _ in range(3): + with pytest.raises(ValueError): + fetcher.fetched_records() + assert fetcher._subscriptions.position(tp).offset == 2 + + +def test_fetched_records_seek_past_bad_record_in_batch(fetcher, topic): + fetcher.config['value_deserializer'] = _FailingDeserializer() + tp = TopicPartition(topic, 0) + msgs = [(None, b'a', None), (None, b'bad', None), (None, b'c', None), (None, b'd', None)] + fetcher._completed_fetches.append(_build_completed_fetch(tp, msgs)) + + records, _ = fetcher.fetched_records() + assert [r.value for r in records[tp]] == [b'a'] + with pytest.raises(ValueError): + fetcher.fetched_records() + + # Skip the bad record. The broker returns the whole batch again for + # the next fetch, starting before the requested offset. + fetcher._subscriptions.seek(tp, 2) + records, _ = fetcher.fetched_records() + assert records == {} + fetcher._completed_fetches.append( + _build_completed_fetch(tp, msgs)._replace(fetched_offset=2)) + records, _ = fetcher.fetched_records() + assert [r.value for r in records[tp]] == [b'c', b'd'] + assert fetcher._subscriptions.position(tp).offset == 4 def test__parse_fetched_data(fetcher, topic, mocker):