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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased

### Fixes
- Avoid resubmitting successful `AIOProducer` batches when a later batch fails during a flush.
- Fix `AvroDeserializer` rejecting messages of 5 bytes or fewer when the schema GUID is
sent in a header (`header_schema_id_serializer`), for example `int` keys or short
strings. The length check now runs where the schema id framing is parsed, so it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async def flush_buffer(self, target_topic: Optional[str] = None) -> None:
# Execute batches with cleanup
await self._execute_batches(batches, target_topic)
except Exception:
# Add batches back to buffer on failure
# Add only failed and unattempted batches back to buffer on failure
try:
self._add_batches_back_to_buffer(batches)
except Exception:
Expand All @@ -169,7 +169,7 @@ async def _execute_batches(self, batches: List[MessageBatch], target_topic: Opti
"""Execute batches and handle cleanup after successful execution

Args:
batches: List of batches to execute
batches: List of batches to execute; on failure, completed batches are removed
target_topic: Optional topic for selective buffer clearing

Returns:
Expand All @@ -179,12 +179,14 @@ async def _execute_batches(self, batches: List[MessageBatch], target_topic: Opti
Exception: If any batch execution fails
"""
# Execute each batch
for batch in batches:
for index, batch in enumerate(batches):
try:
# Execute batch using the Kafka executor
await self._kafka_executor.execute_batch(batch.topic, batch.messages, batch.partition)

except Exception as e:
# Successfully submitted batches must not be produced again on retry.
del batches[:index]
# Handle batch failure by failing all unresolved futures for this batch
self._handle_batch_failure(e, batch.futures)
# Re-raise the exception so caller knows the batch operation failed
Expand Down
44 changes: 44 additions & 0 deletions tests/test_producer_batch_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,50 @@ def test_add_batches_back_to_buffer_empty_batch(self):
self.assertEqual(self.batch_processor.get_buffer_size(), initial_size)


class TestBatchRetry(unittest.IsolatedAsyncioTestCase):
async def test_retry_excludes_successfully_submitted_batches(self):
for target_topic in (None, 'topic'):
for delivered in (False, True):
with self.subTest(target_topic=target_topic, delivered=delivered):
calls = []
failure = BufferError("queue full")

async def execute_batch(topic, messages, partition):
calls.append((topic, partition))
if len(calls) == 2:
raise failure
if delivered:
for message in messages:
message['callback'](None, message['value'])

executor = Mock()
executor.execute_batch = execute_batch
processor = ProducerBatchProcessor(executor)
futures = [asyncio.get_running_loop().create_future() for _ in range(3)]
for partition, future in enumerate(futures):
processor.add_message(
{'topic': 'topic', 'partition': partition, 'value': str(partition)}, future
)
try:
with self.assertRaises(BufferError):
await processor.flush_buffer(target_topic)
self.assertIs(futures[1].exception(), failure)
self.assertFalse(futures[2].done())
self.assertEqual(futures[0].done(), delivered)
self.assertEqual(processor.get_buffer_size(), 2)
self.assertEqual(processor._buffer_futures, futures[1:])

await processor.flush_buffer(target_topic)
self.assertEqual(calls, [('topic', 0), ('topic', 1), ('topic', 1), ('topic', 2)])
self.assertTrue(processor.is_buffer_empty())
finally:
for future in futures:
if future.done():
future.exception()
else:
future.cancel()


if __name__ == '__main__':
# Run all tests
unittest.main(verbosity=2)