From 2a378d359980380b9913853d54e83b10729375d5 Mon Sep 17 00:00:00 2001 From: Edson Henrique Date: Mon, 26 Oct 2026 20:23:53 -0400 Subject: [PATCH 1/3] Normalize producer memoryviews to byte-oriented buffers --- kafka/producer/kafka.py | 6 +++ test/producer/test_producer.py | 75 +++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/kafka/producer/kafka.py b/kafka/producer/kafka.py index 9a548aacd..a9decda38 100644 --- a/kafka/producer/kafka.py +++ b/kafka/producer/kafka.py @@ -960,6 +960,12 @@ def send(self, topic, value=None, key=None, headers=None, partition=None, timest if type(value_bytes) not in (bytes, bytearray, memoryview, type(None)): raise TypeError("Unsupported type for serialized value: %s" % type(value_bytes)) + # Partitioners and record lengths operate on bytes, not buffer elements. + if isinstance(key_bytes, memoryview): + key_bytes = key_bytes.cast('B') if key_bytes.c_contiguous else key_bytes.tobytes() + if isinstance(value_bytes, memoryview): + value_bytes = value_bytes.cast('B') if value_bytes.c_contiguous else value_bytes.tobytes() + if self._metadata.partitions_for_topic(topic) is None: try: self._wait_on_metadata(topic, self.config['max_block_ms']) diff --git a/test/producer/test_producer.py b/test/producer/test_producer.py index 1917155ec..77ee5edd5 100644 --- a/test/producer/test_producer.py +++ b/test/producer/test_producer.py @@ -1,14 +1,17 @@ import gc import platform import threading +from array import array +from ctypes import c_uint32 from unittest.mock import MagicMock import pytest from kafka import KafkaProducer -from kafka.errors import KafkaConfigurationError -from kafka.partitioner import Partitioner, StickyPartitioner +from kafka.errors import KafkaConfigurationError, MessageSizeTooLargeError +from kafka.partitioner import DefaultPartitioner, Partitioner, StickyPartitioner from kafka.producer.transaction_manager import TransactionManager, ProducerIdAndEpoch +from kafka.record.memory_records import MemoryRecordsBuilder from test.mock_broker import MockBroker @@ -134,6 +137,74 @@ def _success_result(): False, True, False) +@pytest.mark.parametrize('magic,api_version', [(0, (0, 9)), (1, (0, 10)), (2, (0, 11))]) +@pytest.mark.parametrize('field', ['key', 'value']) +@pytest.mark.parametrize('data_factory', [ + pytest.param(lambda: memoryview(array('H', [0x1234, 0x5678])), id='typed'), + pytest.param(lambda: memoryview(bytearray(b'abcd')).cast('B', [2, 2]), id='multidimensional'), + pytest.param(lambda: memoryview(c_uint32(0x12345678)), id='scalar'), + pytest.param(lambda: memoryview(b'abcdef')[::2], id='strided-bytes'), + pytest.param(lambda: memoryview(array('H', [1, 2, 3]))[::2], id='strided-typed'), + pytest.param(lambda: memoryview(b'abcdef')[::-1], id='reversed'), + pytest.param(lambda: memoryview(b'abcdef')[1:4], id='offset-byte-view'), + pytest.param(lambda: memoryview(array('H')), id='empty-typed'), + pytest.param(lambda: memoryview(b'bytes'), id='byte-view'), + pytest.param(lambda: b'bytes', id='bytes'), + pytest.param(lambda: bytearray(b'bytes'), id='bytearray'), + pytest.param(lambda: None, id='none'), +]) +def test_send_buffer_payload_matches_its_bytes(data_factory, field, magic, api_version): + """Accepted views must reach partitioning and record encoding as bytes.""" + original = data_factory() + data = {'key': b'key', 'value': b'value'} + data[field] = original + expected = {name: bytes(value) if value is not None else None for name, value in data.items()} + partitioner = DefaultPartitioner() + with _producer_for_send_test(partitioner) as producer: + producer.config['api_version'] = api_version + producer._accumulator.append.return_value = _success_result() + producer.send('t', timestamp_ms=1000, **data) + tp, timestamp, key, value, headers = producer._accumulator.append.call_args.args + + # Exercise actual wire encoding/decoding after the public send path. + # The broker and accumulator are test doubles; this isn't a broker test. + builder = MemoryRecordsBuilder(magic, compression_type=0, batch_size=10000) + builder.append(timestamp, key, value, headers) + builder.close() + batch = builder.records().next_batch() + assert batch.validate_crc() + record, = list(batch) + assert record.key == expected['key'] + assert record.value == expected['value'] + assert producer._estimate_size_in_bytes(key, value) == producer._estimate_size_in_bytes( + expected['key'], expected['value']) + if expected['key'] is not None: + assert tp.partition == partitioner.partition( + 't', data['key'], expected['key'], data['value'], expected['value'], producer._metadata) + + serialized = key if field == 'key' else value + if isinstance(original, memoryview): + assert bytes(serialized) == bytes(original) + if original.c_contiguous: + assert isinstance(serialized, memoryview) + assert serialized.obj is original.obj + else: + assert serialized is original + + +@pytest.mark.parametrize('api_version', [(0, 9), (0, 10), (0, 11)]) +def test_send_memoryview_checks_byte_size_limit(api_version): + """Typed views must not bypass the configured serialized record size bound.""" + value = memoryview(array('H', range(100))) + with _producer_for_send_test(DefaultPartitioner()) as producer: + producer.config['api_version'] = api_version + producer.config['max_request_size'] = producer._estimate_size_in_bytes(b'key', bytes(value)) - 1 + producer._accumulator.append.return_value = _success_result() + with pytest.raises(MessageSizeTooLargeError): + producer.send('t', key=b'key', value=value) + producer._accumulator.append.assert_not_called() + + def test_send_null_key_triggers_on_new_batch_via_abort_retry(): """KIP-480 Java-faithful flow: a null-key send whose accumulator has no in-progress batch must invoke ``partitioner.on_new_batch`` (rotate From e7f5c1de318c7bbbfaae8bfd7abd8947f0c3da4e Mon Sep 17 00:00:00 2001 From: Edson Henrique Date: Mon, 26 Oct 2026 20:48:33 -0400 Subject: [PATCH 2/3] Use fixture request budget for refresh-loop reuse test The two mock bootstraps check refresh-loop identity rather than handshake speed. Use the existing fixture request_timeout_ms for both calls, retaining the real bootstrap operations and identity assertions. Production timeouts and the memoryview regressions are unchanged. --- test/test_cluster.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_cluster.py b/test/test_cluster.py index e4a4b726d..2cf72a984 100644 --- a/test/test_cluster.py +++ b/test/test_cluster.py @@ -532,8 +532,10 @@ def test_refresh_loop_spawned_once(self, manager): """Calling bootstrap() multiple times must not spawn multiple refresh loop tasks.""" cluster = manager.cluster - manager.bootstrap(timeout_ms=100) + # This checks refresh-loop identity, not a 100 ms bootstrap speed limit. + timeout_ms = manager.config['request_timeout_ms'] + manager.bootstrap(timeout_ms=timeout_ms) future = cluster._refresh_loop_future assert future is not None - manager.bootstrap(timeout_ms=100) + manager.bootstrap(timeout_ms=timeout_ms) assert cluster._refresh_loop_future is future From 0292046ca2f77e29c05df502766a5cc5dc0dc1be Mon Sep 17 00:00:00 2001 From: Edson Henrique Date: Wed, 11 Nov 2026 15:21:25 -0500 Subject: [PATCH 3/3] Prevent broker fixture listener port collisions Kafka 4.3 CI failed during SCRAM fixture setup because the broker and controller were both assigned port 46927. Exclude the paired listener port during initial allocation and broker startup retries. Keep rejected sockets bound until selection finishes, and close every socket on errors. Add deterministic unit controls for repeated port allocation, explicit broker ports and cleanup. All four controls fail before the repair and pass afterwards; the local non-integration suite passes 2838 tests with one existing skip, and pylint passes. These checks use CPython 3.13 on macOS; they do not run the Linux Kafka/Java integration job locally. --- test/integration/fixtures.py | 24 ++++++---- test/test_integration_fixtures.py | 76 +++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 8 deletions(-) create mode 100644 test/test_integration_fixtures.py diff --git a/test/integration/fixtures.py b/test/integration/fixtures.py index c6f018de5..8b8c39a6c 100644 --- a/test/integration/fixtures.py +++ b/test/integration/fixtures.py @@ -140,12 +140,20 @@ def _extract_topic_command_error(stdout): return '' -def get_open_port(): - sock = socket.socket() - sock.bind(("127.0.0.1", 0)) - port = sock.getsockname()[1] - sock.close() - return port +def get_open_port(exclude=()): + sockets = [] + try: + while True: + sock = socket.socket() + sockets.append(sock) + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + if port not in exclude: + return port + # Keep excluded ports bound so the next bind cannot reuse them. + finally: + for sock in sockets: + sock.close() def gen_ssl_resources(directory): @@ -398,7 +406,7 @@ def __init__(self, host, port, broker_id, zookeeper=None, zk_chroot=None, else: self.auto_port = False self.port = port - self.controller_port = get_open_port() + self.controller_port = get_open_port(exclude=(self.port,)) self.cluster_id = self._gen_cluster_id() self.broker_id = broker_id @@ -606,7 +614,7 @@ def start(self): # so we will try a different port on each retry # unless the fixture was passed a specific port if self.auto_port: - self.port = get_open_port() + self.port = get_open_port(exclude=(self.controller_port,)) self.out('Attempting to start on port %d (try #%d)' % (self.port, tries)) self.render_template(properties_template, properties, vars(self)) diff --git a/test/test_integration_fixtures.py b/test/test_integration_fixtures.py new file mode 100644 index 000000000..c90caa8e8 --- /dev/null +++ b/test/test_integration_fixtures.py @@ -0,0 +1,76 @@ +import pytest + +from test.integration import fixtures + + +class PortSocket: + def __init__(self, port, sockets): + self.port = port + self.sockets = sockets + self.bound = False + self.closed = False + + def bind(self, address): + assert address == ('127.0.0.1', 0) + assert not any(sock.bound and not sock.closed and sock.port == self.port + for sock in self.sockets) + self.bound = True + + def getsockname(self): + return ('127.0.0.1', self.port) + + def close(self): + self.closed = True + + +def port_sockets(monkeypatch, ports): + sockets = [] + ports = iter(ports) + + def socket(): + sock = PortSocket(next(ports), sockets) + sockets.append(sock) + return sock + + monkeypatch.setattr(fixtures.socket, 'socket', socket) + return sockets + + +def test_get_open_port_keeps_excluded_ports_bound_until_selection(monkeypatch): + sockets = port_sockets(monkeypatch, [12345, 23456]) + original_getsockname = PortSocket.getsockname + + def getsockname(self): + if self.port == 23456: + assert not sockets[0].closed + return original_getsockname(self) + + monkeypatch.setattr(PortSocket, 'getsockname', getsockname) + assert fixtures.get_open_port(exclude=(12345,)) == 23456 + assert all(sock.closed for sock in sockets) + + +def test_get_open_port_closes_socket_when_bind_fails(monkeypatch): + sockets = port_sockets(monkeypatch, [12345]) + + def fail_bind(self, address): + raise OSError('bind failed') + + monkeypatch.setattr(PortSocket, 'bind', fail_bind) + with pytest.raises(OSError, match='bind failed'): + fixtures.get_open_port() + assert all(sock.closed for sock in sockets) + + +@pytest.mark.parametrize('port,ports', [ + (None, [12345, 12345, 23456]), + (12345, [12345, 23456]), +]) +def test_broker_and_controller_ports_are_distinct(monkeypatch, tmp_path, port, ports): + sockets = port_sockets(monkeypatch, ports) + monkeypatch.setattr(fixtures, 'env_kafka_version', lambda: (4, 3, 0)) + monkeypatch.setattr(fixtures.Fixture, 'kafka_root', str(tmp_path)) + broker = fixtures.KafkaFixture('localhost', port, 0) + assert broker.port == 12345 + assert broker.controller_port == 23456 + assert all(sock.closed for sock in sockets)