Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 22 additions & 25 deletions kafka/consumer/fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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" % (
Expand Down
69 changes: 69 additions & 0 deletions test/consumer/test_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading