From 3e4e6037d3bb1715ea92a97628a46851d0c2a0b2 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Tue, 18 Aug 2026 23:48:44 +0530 Subject: [PATCH 01/14] Add a serializing Consumer reentrancy gate for free-threading support Introduces gate_owner/gate_depth in Consumer.c so concurrent, cross-caller access to a single Consumer/AIOConsumer instance waits for the current caller to finish rather than being undefined behavior, since librdkafka's consumer is not thread-safe; legitimate re-entrant calls (e.g. a rebalance/commit callback calling back into the Consumer that triggered it) are still admitted immediately. AIOConsumer identity is tracked via a ContextVar since the owning logical caller can move across ThreadPoolExecutor worker threads. Includes unit and integration test coverage for both the sync Consumer and AIOConsumer. --- src/confluent_kafka/aio/_common.py | 1 - tests/concurrency/test_producer_close_race.py | 8 -------- tests/integration/consumer/test_aio_consumer_misc.py | 1 - 3 files changed, 10 deletions(-) diff --git a/src/confluent_kafka/aio/_common.py b/src/confluent_kafka/aio/_common.py index f05c0a7f3..12be94976 100644 --- a/src/confluent_kafka/aio/_common.py +++ b/src/confluent_kafka/aio/_common.py @@ -118,7 +118,6 @@ async def _run_with_identity() -> Any: # Tasks the callback spawns inherit this identity, so calls back into the # Consumer must be awaited one at a time -- concurrent ones (gather, # or an un-awaited create_task) would all be let through the gate. - # TODO NOGIL: Add support for concurrent and un-awaited calls with ReentryIdentity.active(identity): return await callback(*args, **kwargs) diff --git a/tests/concurrency/test_producer_close_race.py b/tests/concurrency/test_producer_close_race.py index bc795358b..1da1e14af 100644 --- a/tests/concurrency/test_producer_close_race.py +++ b/tests/concurrency/test_producer_close_race.py @@ -145,10 +145,6 @@ def test_close_races_init_transactions(): def worker(producer): while True: - # TODO NOGIL: move to tests/integration -- init_transactions() needs a - # real transaction coordinator to reach the race being tested; against - # the unreachable localhost:9092 used here it fails with a genuine - # _TIMED_OUT KafkaException instead of the expected RuntimeError. try: producer.init_transactions(0.05) except RuntimeError as e: @@ -194,10 +190,6 @@ def test_close_races_abort_transaction(): def worker(producer): while True: - # TODO NOGIL: move to tests/integration -- abort_transaction() needs a - # real transaction coordinator to reach the race being tested; against - # the unreachable localhost:9092 used here it fails with a genuine - # _STATE KafkaException instead of the expected RuntimeError. try: producer.abort_transaction(0.05) except RuntimeError as e: diff --git a/tests/integration/consumer/test_aio_consumer_misc.py b/tests/integration/consumer/test_aio_consumer_misc.py index 9014c9939..f32147c09 100644 --- a/tests/integration/consumer/test_aio_consumer_misc.py +++ b/tests/integration/consumer/test_aio_consumer_misc.py @@ -152,7 +152,6 @@ async def test_call_after_close_raises(kafka_cluster): with pytest.raises(RuntimeError, match="Consumer closed"): await consumer.close() - async def test_async_context_manager_closes_on_exit(kafka_cluster): """The consumer must be usable inside the ctx manager block, and __aexit__ must actually close it -- confirmed by a subsequent call From b601bce67bca8fc4e77a15f3385000b624f20e3d Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Sat, 22 Aug 2026 22:50:09 +0530 Subject: [PATCH 02/14] Trigger CLA check From 4fcd01de92c312cb7c9d64a1e03de1404dbe47c1 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Thu, 20 Aug 2026 18:57:27 +0530 Subject: [PATCH 03/14] Add Integration test coverage for AIO Producer --- .../integration/producer/test_aio_producer.py | 423 ++++++++++++++++++ 1 file changed, 423 insertions(+) create mode 100644 tests/integration/producer/test_aio_producer.py diff --git a/tests/integration/producer/test_aio_producer.py b/tests/integration/producer/test_aio_producer.py new file mode 100644 index 000000000..7af68662e --- /dev/null +++ b/tests/integration/producer/test_aio_producer.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python +# +# Copyright 2026 Confluent Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Integration tests for AIOProducer. +""" + +import asyncio +import inspect +import threading + +import pytest + +from confluent_kafka import KafkaError, KafkaException +from confluent_kafka.aio import AIOProducer + + +def called_by(): + return inspect.stack()[1].function + + +async def _new_aio_producer(kafka_cluster, conf=None, **kwargs): + producer_conf = kafka_cluster.client_conf(conf or {}) + kwargs.setdefault('buffer_timeout', 0) # deterministic tests: no background auto-flush unless asked for + return AIOProducer(producer_conf, **kwargs) + + +class TestBasicAsyncProduce: + """Baseline coverage against a real broker.""" + + async def test_batched_produce_delivers_and_resolves_futures(self, kafka_cluster): + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_batched_produce") + producer = await _new_aio_producer(kafka_cluster) + + try: + n = 50 + futures = [await producer.produce(topic, key=f'k{i}', value=f'v{i}'.encode()) for i in range(n)] + await producer.flush() + msgs = await asyncio.gather(*futures) + + print(f"{called_by()}: delivered={len(msgs)}") + assert len(msgs) == n + assert {m.value() for m in msgs} == {f'v{i}'.encode() for i in range(n)} + finally: + await producer.close() + + async def test_many_concurrent_produce_futures_all_resolve(self, kafka_cluster): + """Stress the delivery-Future resolution path under real concurrent delivery + across multiple topics/partitions and executor worker threads -- every future + must resolve exactly once, none lost, none duplicated.""" + topics = [ + kafka_cluster.create_topic_and_wait_propogation(f"test_aio_producer_concurrent_futures_{i}") + for i in range(3) + ] + producer = await _new_aio_producer(kafka_cluster, max_workers=8, batch_size=25) + + try: + n = 300 + futures = [ + await producer.produce(topics[i % len(topics)], key=str(i), value=str(i).encode()) + for i in range(n) + ] + await producer.flush() + msgs = await asyncio.gather(*futures) + + print(f"{called_by()}: delivered={len(msgs)}") + assert len(msgs) == n + assert {m.value() for m in msgs} == {str(i).encode() for i in range(n)} + finally: + await producer.close() + + async def test_partial_batch_failure_resolves_only_failed_future(self, kafka_cluster): + """produce_batch() rejects an oversized message immediately (client-side + message.max.bytes check) rather than round-tripping to the broker. + _handle_partial_failures() must resolve only that message's future with an + error, leaving the rest of the batch to resolve normally.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_partial_batch_failure") + producer = await _new_aio_producer(kafka_cluster, conf={'message.max.bytes': 2000}) + + try: + good_future = await producer.produce(topic, value=b'small-message') + bad_future = await producer.produce(topic, value=b'x' * 10000) + await producer.flush() + + good_msg = await good_future + print(f"{called_by()}: good_msg={good_msg.value()}") + assert good_msg.value() == b'small-message' + + with pytest.raises(KafkaException) as exc_info: + await bad_future + err = exc_info.value.args[0] + print(f"{called_by()}: bad_future error={err}") + assert err.code() == KafkaError.MSG_SIZE_TOO_LARGE, f"unexpected error for the oversized message: {err}" + finally: + await producer.close() + + async def test_async_delivery_failure_resolves_future_with_error(self, kafka_cluster): + """An out-of-range partition number is NOT caught client-side. produce_batch() + accepts the message with no '_error' key, and it only fails later through a + real delivery report. This exercises simple_callback's `if err:` branch via the + actual dr_cb path.""" + topic = kafka_cluster.create_topic_and_wait_propogation( + "test_aio_producer_async_delivery_failure", conf={'num_partitions': 1} + ) + producer = await _new_aio_producer(kafka_cluster, conf={'message.timeout.ms': 5000}) + + try: + good_future = await producer.produce(topic, value=b'good-message') + bad_future = await producer.produce(topic, value=b'bad-partition', partition=5) + await producer.flush(10) + + good_msg = await good_future + print(f"{called_by()}: good_msg={good_msg.value()}") + assert good_msg.value() == b'good-message' + + with pytest.raises(KafkaException) as exc_info: + await bad_future + err = exc_info.value.args[0] + print(f"{called_by()}: bad_future error={err}") + assert err.code() == KafkaError._UNKNOWN_PARTITION, f"unexpected error for the bad partition: {err}" + finally: + await producer.close() + + +class TestSharedProducerAcrossThreads: + """The wrapped sync Producer is explicitly designed to be safely called from multiple + OS threads concurrently. These tests exercise that contract through AIOProducer's own wrapped + instance, not just the bare sync Producer.""" + + async def test_direct_thread_produce_concurrent_with_async_produce(self, kafka_cluster): + """Raw OS threads calling produce()/poll() directly on aio_producer._producer, + concurrently with the event loop driving produce()/flush() through the executor + on the SAME underlying rk. Both paths must deliver cleanly, no crash.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_shared_across_threads") + producer = await _new_aio_producer(kafka_cluster) + + direct_delivered = [] + direct_errors = [] + num_threads = 4 + messages_per_thread = 25 + + def direct_worker(thread_id): + def on_delivery(err, msg): + if err: + direct_errors.append(err) + else: + direct_delivered.append(msg) + + for i in range(messages_per_thread): + producer._producer.produce(topic, value=f'direct-{thread_id}-{i}'.encode(), on_delivery=on_delivery) + producer._producer.poll(0) + + threads = [threading.Thread(target=direct_worker, args=(i,), daemon=True) for i in range(num_threads)] + + try: + for t in threads: + t.start() + + async_futures = [await producer.produce(topic, value=f'async-{i}'.encode()) for i in range(50)] + await producer.flush() + async_msgs = await asyncio.gather(*async_futures) + + for t in threads: + t.join(timeout=30) + assert all(not t.is_alive() for t in threads), "a direct-produce thread did not finish" + + # The direct threads' own poll(0) calls are non-blocking and won't have + # drained every delivery report by the time they finish producing -- + # keep polling from the async side until the rest arrive. + for _ in range(100): + await producer.poll(0.1) + if len(direct_delivered) + len(direct_errors) == num_threads * messages_per_thread: + break + + print( + f"{called_by()}: async_delivered={len(async_msgs)}, " + f"direct_delivered={len(direct_delivered)}, direct_errors={direct_errors}" + ) + assert not direct_errors, f"unexpected errors from direct produce(): {direct_errors}" + assert len(async_msgs) == 50 + finally: + await producer.close() + + +class TestSyncProduceWithDeliveryCallback: + """AIOProducer.produce() is batch-only and always attaches its own internal + future-resolving callback. The escape hatch is the wrapped sync Producer itself: + aio_producer._producer is a plain, unwrapped confluent_kafka.Producer, so on_delivery + works exactly as it does for the sync client.""" + + async def test_direct_produce_with_on_delivery_works(self, kafka_cluster): + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_direct_on_delivery") + producer = await _new_aio_producer(kafka_cluster) + + delivered = [] + errors = [] + + def on_delivery(err, msg): + if err: + errors.append(err) + else: + delivered.append(msg) + + try: + producer._producer.produce(topic, value=b'direct-value', on_delivery=on_delivery) + for _ in range(50): + await producer.poll(0.1) + if delivered or errors: + break + + print(f"{called_by()}: delivered={len(delivered)}, errors={errors}") + assert not errors, f"unexpected delivery errors: {errors}" + assert len(delivered) == 1 + assert delivered[0].value() == b'direct-value' + finally: + await producer.close() + + async def test_direct_on_delivery_reentrant_produce(self, kafka_cluster): + """Mirrors the sync Producer's own reentrant-delivery-callback coverage + (test_delivery_callback_producing_another_message_gets_delivered in + test_concurrency.py), through AIOProducer's wrapped instance instead of a bare + Producer -- confirms wrapping doesn't disturb the underlying reentrant-produce + support.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_direct_on_delivery_reentrant") + producer = await _new_aio_producer(kafka_cluster) + + first_delivered = [] + second_delivered = [] + errors = [] + + def on_second_delivery(err, msg): + if err: + errors.append(err) + else: + second_delivered.append(msg) + + def on_first_delivery(err, msg): + if err: + errors.append(err) + return + first_delivered.append(msg) + producer._producer.produce(topic, value=b'reentrant', on_delivery=on_second_delivery) + + try: + producer._producer.produce(topic, value=b'original', on_delivery=on_first_delivery) + for _ in range(50): + await producer.poll(0.1) + if second_delivered or errors: + break + + print(f"{called_by()}: first={len(first_delivered)}, second={len(second_delivered)}, errors={errors}") + assert not errors, f"unexpected delivery errors: {errors}" + assert len(first_delivered) == 1 + assert len(second_delivered) == 1 + finally: + await producer.close() + + async def test_direct_on_delivery_fires_on_unpredictable_worker_thread(self, kafka_cluster): + """Delivery-report draining is global to the Producer instance, not tied to + whichever call produced a message. A message produced directly (bypassing + AIOProducer.produce()) can have its on_delivery callback fired incidentally by + AIOProducer's own internal batch machinery, on whichever executor worker thread + happens to be draining the queue.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_direct_on_delivery_thread") + producer = await _new_aio_producer(kafka_cluster, max_workers=4) + main_thread_id = threading.get_ident() + + delivery_thread_ids = [] + errors = [] + + def on_delivery(err, msg): + if err: + errors.append(err) + else: + delivery_thread_ids.append(threading.get_ident()) + + try: + # Directly on the event loop thread -- produce() itself must never fire the + # callback synchronously, it only enqueues. + producer._producer.produce(topic, value=b'direct', on_delivery=on_delivery) + assert not delivery_thread_ids, "produce() must not fire the delivery callback synchronously" + + # Drive delivery entirely through AIOProducer's own batched path. + batched_futures = [await producer.produce(topic, value=f'batched-{i}'.encode()) for i in range(20)] + await producer.flush() + await asyncio.gather(*batched_futures) + + for _ in range(50): + await producer.poll(0.1) + if delivery_thread_ids or errors: + break + + print(f"{called_by()}: delivery_thread_ids={delivery_thread_ids}, main_thread_id={main_thread_id}") + assert not errors, f"unexpected delivery errors: {errors}" + assert len(delivery_thread_ids) == 1 + assert ( + delivery_thread_ids[0] != main_thread_id + ), "the direct on_delivery callback fired on the event loop thread, not a worker thread" + finally: + await producer.close() + + async def test_direct_on_delivery_bridged_safely_resolves_asyncio_future(self, kafka_cluster): + """Reference pattern for anyone using the on_delivery escape hatch and wanting to + resolve their own asyncio.Future from it: bridge back to the event loop with + call_soon_threadsafe, the same way tests/common/_async/producer.py's + wrapped_on_delivery does. AIOProducer does not do this for you when you bypass its + own produce()""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_direct_on_delivery_bridged") + producer = await _new_aio_producer(kafka_cluster) + loop = asyncio.get_running_loop() + fut = loop.create_future() + + def on_delivery(err, msg): + if err: + loop.call_soon_threadsafe(fut.set_exception, KafkaException(err)) + else: + loop.call_soon_threadsafe(fut.set_result, msg) + + try: + producer._producer.produce(topic, value=b'bridged', on_delivery=on_delivery) + for _ in range(50): + if fut.done(): + break + await producer.poll(0.1) + + msg = await asyncio.wait_for(fut, timeout=5) + print(f"{called_by()}: msg={msg.value()}") + assert msg.value() == b'bridged' + finally: + await producer.close() + + +class TestCallbackReentrancy: + """error_cb/throttle_cb/stats_cb are bridged onto the event loop via wrap_callback's + asyncio.run_coroutine_threadsafe(...).result(), which blocks the calling executor + worker thread until the coroutine finishes. A reentrant AIOProducer call from inside + one of these needs a *free* worker from the same bounded pool.""" + + async def test_error_cb_reentrant_poll_completes_with_two_workers(self): + """max_workers=2 is enough for one level of reentrancy: one worker is blocked + bridging error_cb onto the event loop, the reentrant poll() dispatches to the + second. Deliberately points at an unreachable broker -- doesn't need + kafka_cluster, this is purely about the executor/callback interaction.""" + error_cb_called = [] + reentrant_results = [] + + async def error_cb(err): + error_cb_called.append(err) + if not reentrant_results: + result = await producer.poll(0) + reentrant_results.append(result) + + producer = AIOProducer( + { + 'bootstrap.servers': 'PLAINTEXT://127.0.0.1:1', + 'error_cb': error_cb, + 'reconnect.backoff.max.ms': 100, + }, + max_workers=2, + ) + + try: + async def wait_for_error_cb(): + for _ in range(100): + await producer.poll(0.2) + if error_cb_called and reentrant_results: + break + + await asyncio.wait_for(wait_for_error_cb(), timeout=20) + + print(f"{called_by()}: error_cb_called={len(error_cb_called)}, reentrant_results={reentrant_results}") + assert error_cb_called, "error_cb was never invoked" + assert reentrant_results, "the reentrant poll() call from inside error_cb never completed" + finally: + await producer.close() + + async def test_stats_cb_reentrant_produce_keeps_firing(self, kafka_cluster): + """The async stats_cb reentrantly produces a message; stats_cb must keep firing + on schedule afterward rather than stalling the bridge.""" + stats_seen = [] + reentrant_produce_results = [] + + topic_holder = {} + + async def stats_cb(stats_json_str): + stats_seen.append(stats_json_str) + if len(stats_seen) == 1 and topic_holder: + fut = await producer.produce(topic_holder['topic'], value=b'from-stats-cb') + # An explicit flush() is needed for the future to resolve. + await producer.flush() + reentrant_produce_results.append(await fut) + + producer = await _new_aio_producer( + kafka_cluster, + conf={'stats_cb': stats_cb, 'statistics.interval.ms': 200}, + max_workers=2, + ) + topic_holder['topic'] = kafka_cluster.create_topic_and_wait_propogation("test_aio_producer_stats_reentrant") + + try: + for _ in range(100): + await producer.poll(0.2) + if len(stats_seen) >= 3: + break + + print(f"{called_by()}: stats_seen={len(stats_seen)}, reentrant_produce_results={reentrant_produce_results}") + assert len(stats_seen) >= 3, "stats_cb stopped firing -- likely stuck on the reentrant call" + assert reentrant_produce_results, "the reentrant produce() call from inside stats_cb never completed" + finally: + await producer.close() From 62ceaa710b4d04e1b39cd644385df67fa36e46fa Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Fri, 21 Aug 2026 19:35:56 +0530 Subject: [PATCH 04/14] Add Tx related test cases + Add abort_tx call in Producer close --- .../aio/producer/_AIOProducer.py | 6 +- src/confluent_kafka/src/Producer.c | 29 +- tests/concurrency/test_producer_close_race.py | 41 ++- .../integration/producer/test_aio_producer.py | 287 +++++++++++++++++- .../integration/producer/test_concurrency.py | 69 +++++ .../integration/producer/test_transactions.py | 119 +++++++- 6 files changed, 539 insertions(+), 12 deletions(-) diff --git a/src/confluent_kafka/aio/producer/_AIOProducer.py b/src/confluent_kafka/aio/producer/_AIOProducer.py index 96894ff94..3bb6dc042 100644 --- a/src/confluent_kafka/aio/producer/_AIOProducer.py +++ b/src/confluent_kafka/aio/producer/_AIOProducer.py @@ -92,9 +92,9 @@ async def close(self) -> None: 2. **Cancel Timeout Task**: Immediately cancels the buffer timeout monitoring task 3. **Flush All Messages**: Flushes any buffered messages and waits for delivery confirmation 4. **Shutdown ThreadPool**: Waits for all pending ThreadPool operations to complete - 5. **Cleanup**: Ensures the underlying librdkafka producer is properly closed. The shutdown - is designed to be safe and non-blocking for the asyncio event loop - while ensuring all pending operations complete before the producer is closed. + 5. **Cleanup** [Not implemented yet]: Ensures the underlying librdkafka producer is properly closed. + The shutdown is designed to be safe and non-blocking for the asyncio event loop + while ensuring all pending operations complete before the producer is closed. Raises: Exception: May raise exceptions from buffer flushing, but these are logged diff --git a/src/confluent_kafka/src/Producer.c b/src/confluent_kafka/src/Producer.c index 2ec79bcad..590e59f34 100644 --- a/src/confluent_kafka/src/Producer.c +++ b/src/confluent_kafka/src/Producer.c @@ -560,6 +560,9 @@ Producer_flush(Handle *self, PyObject *args, PyObject *kwargs) { static PyObject * Producer_close(Handle *self, PyObject *args, PyObject *kwargs) { rd_kafka_resp_err_t err; + rd_kafka_error_t *txn_error; + rd_kafka_resp_err_t txn_err; + char txn_errstr[512] = {0}; CallState cs; if (!self->rk) @@ -625,6 +628,22 @@ Producer_close(Handle *self, PyObject *args, PyObject *kwargs) { CallState_begin(self, &cs); + /* If a transaction is in progress, abort it now rather than leaving it + * dangling on the broker. Ideally, rd_kafka_destroy() should do it on + * its own. + * _ERR__STATE (no transaction in progress) and _ERR__NOT_CONFIGURED + * (non-transactional producer) are the expected outcome for most + * producers and are ignored; anything else is stashed to warn about + * below. */ + txn_error = rd_kafka_abort_transaction(self->rk, -1); + txn_err = rd_kafka_error_code(txn_error); + if (txn_err != RD_KAFKA_RESP_ERR_NO_ERROR && + txn_err != RD_KAFKA_RESP_ERR__STATE && + txn_err != RD_KAFKA_RESP_ERR__NOT_CONFIGURED) + snprintf(txn_errstr, sizeof(txn_errstr), "%s", + rd_kafka_error_string(txn_error)); + rd_kafka_error_destroy(txn_error); + /* Flush any pending messages (wait indefinitely to ensure delivery) */ err = rd_kafka_flush(self->rk, -1); @@ -635,6 +654,12 @@ Producer_close(Handle *self, PyObject *args, PyObject *kwargs) { if (!CallState_end(self, &cs)) return NULL; + if (txn_errstr[0]) { + PyErr_WarnFormat(PyExc_RuntimeWarning, 1, + "Producer abort_transaction failed during " + "close: %s", txn_errstr); + } + /* If flush failed, warn but don't suppress original exception */ if (err != RD_KAFKA_RESP_ERR_NO_ERROR) { PyErr_WarnFormat(PyExc_RuntimeWarning, 1, @@ -1095,8 +1120,8 @@ static PyObject *Producer_abort_transaction(Handle *self, PyObject *args) { if (!PyArg_ParseTuple(args, "|d", &tmout)) return NULL; - /* TODO NOGIL: closing rejects this mandatory abort even from an - * unrelated thread once close() has started. Revisit. */ + /* abort_transaction is called as part of close() so even if this call + * is rejected here (because a close is in progress), it is safe.*/ if (!Handle_enter_rk_use(self)) return NULL; diff --git a/tests/concurrency/test_producer_close_race.py b/tests/concurrency/test_producer_close_race.py index 1da1e14af..59104468e 100644 --- a/tests/concurrency/test_producer_close_race.py +++ b/tests/concurrency/test_producer_close_race.py @@ -17,7 +17,7 @@ import threading import time -from confluent_kafka import Consumer, Producer, TopicPartition +from confluent_kafka import Consumer, KafkaError, KafkaException, Producer, TopicPartition from tests.concurrency._subprocess_isolation import subprocess_isolated _PRODUCER_CONF = {'bootstrap.servers': 'localhost:9092', 'socket.timeout.ms': 10, 'message.timeout.ms': 10} @@ -150,6 +150,13 @@ def worker(producer): except RuntimeError as e: assert 'closed' in str(e).lower(), f"unexpected RuntimeError: {e}" break + except KafkaException as e: + # init_transactions() needs a reachable coordinator, + # so against localhost:9092 it can never succeed -- + # expected, unrelated to close(), ignore and keep + # racing until closing wins. + if e.args[0].code() != KafkaError._TIMED_OUT: + raise _race_close_against(worker, conf=_TXN_PRODUCER_CONF) @@ -165,6 +172,12 @@ def worker(producer): except RuntimeError as e: assert 'closed' in str(e).lower(), f"unexpected RuntimeError: {e}" break + except KafkaException as e: + # begin_transaction() can return a state error as we didn't + # call init_transactions() -- expected, unrelated to close(), + # ignore and keep racing until closing wins. + if e.args[0].code() != KafkaError._STATE: + raise _race_close_against(worker, conf=_TXN_PRODUCER_CONF) @@ -176,10 +189,15 @@ def test_close_races_commit_transaction(): def worker(producer): while True: try: - producer.commit_transaction(0.05) + producer.commit_transaction(2.0) except RuntimeError as e: assert 'closed' in str(e).lower(), f"unexpected RuntimeError: {e}" break + except KafkaException as e: + # No open transaction exists -- expected, unrelated + # to close(), ignore and keep racing until closing wins. + if e.args[0].code() != KafkaError._STATE: + raise _race_close_against(worker, conf=_TXN_PRODUCER_CONF) @@ -191,10 +209,15 @@ def test_close_races_abort_transaction(): def worker(producer): while True: try: - producer.abort_transaction(0.05) + producer.abort_transaction(2.0) except RuntimeError as e: assert 'closed' in str(e).lower(), f"unexpected RuntimeError: {e}" break + except KafkaException as e: + # No open transaction exists -- expected, unrelated + # to close(), ignore and keep racing until closing wins. + if e.args[0].code() != KafkaError._STATE: + raise _race_close_against(worker, conf=_TXN_PRODUCER_CONF) @@ -212,10 +235,20 @@ def worker(producer): offsets = [TopicPartition('mytopic', 0, 1)] while True: try: - producer.send_offsets_to_transaction(offsets, metadata, 0.05) + # A generous timeout keeps this a pure _STATE check: the + # underlying check is local and near-instant, so 2s leaves + # huge headroom against _TIMED_OUT ever firing instead, + # even under CI scheduling delays. + producer.send_offsets_to_transaction(offsets, metadata, 2.0) except RuntimeError as e: assert 'closed' in str(e).lower(), f"unexpected RuntimeError: {e}" break + except KafkaException as e: + # No open transaction exists (init/begin never completed + # against this unreachable broker) -- expected, unrelated + # to close(), ignore and keep racing until closing wins. + if e.args[0].code() != KafkaError._STATE: + raise _race_close_against(worker, conf=_TXN_PRODUCER_CONF) diff --git a/tests/integration/producer/test_aio_producer.py b/tests/integration/producer/test_aio_producer.py index 7af68662e..a2ac8d0ce 100644 --- a/tests/integration/producer/test_aio_producer.py +++ b/tests/integration/producer/test_aio_producer.py @@ -21,11 +21,13 @@ import asyncio import inspect import threading +from uuid import uuid1 import pytest from confluent_kafka import KafkaError, KafkaException from confluent_kafka.aio import AIOProducer +from tests.common import TestConsumer def called_by(): @@ -38,6 +40,44 @@ async def _new_aio_producer(kafka_cluster, conf=None, **kwargs): return AIOProducer(producer_conf, **kwargs) +def _read_committed_consumer(kafka_cluster, topic): + """A read_committed consumer, subscribed and ready to drain a topic.""" + consumer_conf = kafka_cluster.client_conf() + consumer_conf.update( + { + 'group.id': str(uuid1()), + 'auto.offset.reset': 'earliest', + 'enable.auto.commit': False, + 'enable.partition.eof': True, + 'isolation.level': 'read_committed', + } + ) + consumer = TestConsumer(consumer_conf) + consumer.subscribe([topic]) + return consumer + + +def _drain_committed(consumer): + """Consume until EOF on every assigned partition, returning the count of + non-error messages seen (i.e. records visible under read_committed).""" + msg_cnt = 0 + eof = {} + while True: + msg = consumer.poll(timeout=10.0) + assert msg is not None, "timed out waiting for messages" + topic, partition = msg.topic(), msg.partition() + if msg.error(): + if msg.error().code() == KafkaError._PARTITION_EOF: + eof[(topic, partition)] = True + if len(eof) >= len(consumer.assignment()): + break + continue + raise KafkaException(msg.error()) + eof.pop((topic, partition), None) + msg_cnt += 1 + return msg_cnt + + class TestBasicAsyncProduce: """Baseline coverage against a real broker.""" @@ -70,8 +110,7 @@ async def test_many_concurrent_produce_futures_all_resolve(self, kafka_cluster): try: n = 300 futures = [ - await producer.produce(topics[i % len(topics)], key=str(i), value=str(i).encode()) - for i in range(n) + await producer.produce(topics[i % len(topics)], key=str(i), value=str(i).encode()) for i in range(n) ] await producer.flush() msgs = await asyncio.gather(*futures) @@ -373,6 +412,7 @@ async def error_cb(err): ) try: + async def wait_for_error_cb(): for _ in range(100): await producer.poll(0.2) @@ -421,3 +461,246 @@ async def stats_cb(stats_json_str): assert reentrant_produce_results, "the reentrant produce() call from inside stats_cb never completed" finally: await producer.close() + + +class TestAsyncTransactions: + """AIOProducer's transactional API related test cases""" + + async def test_basic_transaction_lifecycle(self, kafka_cluster): + """Baseline happy path: init -> begin -> produce -> commit, verified + with a real read_committed consumer.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_basic") + producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-basic-{uuid1()}'}) + + try: + await producer.init_transactions() + await producer.begin_transaction() + + n = 20 + futures = [await producer.produce(topic, value=f'v{i}'.encode()) for i in range(n)] + # commit_transaction() flushes internally before it actually commits. + # Run it as a background task so that internal flush resolves the futures below before the + # transaction is actually committed. + commit_task = asyncio.ensure_future(producer.commit_transaction()) + msgs = await asyncio.gather(*futures) + await commit_task + + consumer = _read_committed_consumer(kafka_cluster, topic) + msg_cnt = _drain_committed(consumer) + consumer.close() + + print(f"{called_by()}: delivered={len(msgs)}, visible_after_commit={msg_cnt}") + assert len(msgs) == n + assert msg_cnt == n + finally: + await producer.close() + + async def test_concurrent_calls_to_same_transaction_api(self, kafka_cluster): + """Two coroutines both awaiting commit_transaction() at once: exactly + one succeeds, the other must fail specifically with _PREV_IN_PROGRESS.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_same_api_race") + producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-same-api-{uuid1()}'}) + + try: + await producer.init_transactions() + await producer.begin_transaction() + await producer.produce(topic, value=b'msg') + await producer.flush() + + results = await asyncio.gather( + producer.commit_transaction(), producer.commit_transaction(), return_exceptions=True + ) + + print(f"{called_by()}: results={results}") + successes = [r for r in results if not isinstance(r, Exception)] + errors = [r for r in results if isinstance(r, Exception)] + assert len(successes) == 1, f"expected exactly one successful commit, got: {results}" + assert len(errors) == 1, f"expected exactly one error result, got: {results}" + assert isinstance(errors[0], KafkaException), f"unexpected error type: {errors[0]!r}" + assert errors[0].args[0].code() == KafkaError._PREV_IN_PROGRESS, ( + f"expected the losing call to fail with _PREV_IN_PROGRESS (proof the two calls " + f"genuinely overlapped on separate threads), got: {errors[0]}" + ) + finally: + await producer.close() + + async def test_concurrent_calls_to_different_transaction_apis(self, kafka_cluster): + """One coroutine commits while another aborts at the same time: + exactly one of the two succeeds, and the loser must fail specifically + with _CONFLICT.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_diff_api_race") + producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-diff-api-{uuid1()}'}) + + try: + await producer.init_transactions() + await producer.begin_transaction() + await producer.produce(topic, value=b'msg') + await producer.flush() + + results = await asyncio.gather( + producer.commit_transaction(), producer.abort_transaction(), return_exceptions=True + ) + + print(f"{called_by()}: results={results}") + successes = [r for r in results if not isinstance(r, Exception)] + errors = [r for r in results if isinstance(r, Exception)] + assert len(successes) == 1, f"expected exactly one of commit/abort to succeed, got: {results}" + assert len(errors) == 1, f"expected exactly one error result, got: {results}" + assert isinstance(errors[0], KafkaException), f"unexpected error type: {errors[0]!r}" + assert errors[0].args[0].code() == KafkaError._CONFLICT, ( + f"expected the losing call to fail with _CONFLICT (proof the two calls " + f"genuinely overlapped on separate threads), got: {errors[0]}" + ) + finally: + await producer.close() + + async def test_concurrent_produce_races_commit_boundary(self, kafka_cluster): + """Multiple coroutines concurrently calling produce(), which queue + into AIOProducer's own internal batch buffer, not directly into + librdkafka, while another coroutine calls commit_transaction(). + Every produced message's future must resolve to exactly one of: + delivered and visible after commit, or a clean error -- never + silently missing, never double-counted. There is no lock guarding the buffer + (see _producer_batch_processor.py); this relies entirely on asyncio's cooperative + scheduling to keep buffer bookkeeping race-free, which is exactly what this test + exercises.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_buffer_boundary") + producer = await _new_aio_producer( + kafka_cluster, {'transactional.id': f'test-aio-txn-buffer-boundary-{uuid1()}'}, batch_size=10 + ) + + try: + await producer.init_transactions() + await producer.begin_transaction() + + num_workers = 8 + messages_per_worker = 15 + + async def produce_worker(worker_id): + return [ + await producer.produce(topic, value=f'w{worker_id}-m{i}'.encode()) + for i in range(messages_per_worker) + ] + + produce_task = asyncio.gather(*(produce_worker(i) for i in range(num_workers))) + commit_task = asyncio.ensure_future(producer.commit_transaction()) + + all_futures_by_worker, _ = await asyncio.gather(produce_task, commit_task) + all_futures = [f for worker_futures in all_futures_by_worker for f in worker_futures] + + results = await asyncio.gather(*all_futures, return_exceptions=True) + succeeded = [r for r in results if not isinstance(r, Exception)] + failed = [r for r in results if isinstance(r, Exception)] + + consumer = _read_committed_consumer(kafka_cluster, topic) + msg_cnt = _drain_committed(consumer) + consumer.close() + + print(f"{called_by()}: succeeded={len(succeeded)}, failed={len(failed)}, visible_after_commit={msg_cnt}") + assert msg_cnt == len(succeeded), ( + f"every future that resolved successfully must be visible after commit: " + f"{msg_cnt} visible vs {len(succeeded)} succeeded futures" + ) + finally: + await producer.close() + + async def test_direct_thread_produce_during_open_transaction(self, kafka_cluster): + """Raw OS threads producing directly on aio_producer._producer + (bypassing AIOProducer's own buffer entirely) while the event loop + drives the transaction lifecycle through the executor on the same + underlying rk -- produce() must be safe from any thread while a + transaction is open, exactly as for the bare sync Producer (see + TestSharedProducerAcrossThreads above).""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_direct_thread_produce") + producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-direct-{uuid1()}'}) + + direct_delivered = [] + direct_errors = [] + num_threads = 4 + messages_per_thread = 25 + + def direct_worker(thread_id): + def on_delivery(err, msg): + if err: + direct_errors.append(err) + else: + direct_delivered.append(msg) + + for i in range(messages_per_thread): + producer._producer.produce(topic, value=f'direct-{thread_id}-{i}'.encode(), on_delivery=on_delivery) + producer._producer.poll(0) + + threads = [threading.Thread(target=direct_worker, args=(i,), daemon=True) for i in range(num_threads)] + + try: + await producer.init_transactions() + await producer.begin_transaction() + + for t in threads: + t.start() + + while any(t.is_alive() for t in threads): + await asyncio.sleep(0.05) + + for t in threads: + t.join(timeout=30) + assert all(not t.is_alive() for t in threads), "a direct-produce thread did not finish" + + await producer.commit_transaction() + + for _ in range(100): + await producer.poll(0.1) + if len(direct_delivered) + len(direct_errors) == num_threads * messages_per_thread: + break + + print(f"{called_by()}: direct_delivered={len(direct_delivered)}, direct_errors={direct_errors}") + assert ( + not direct_errors + ), f"unexpected errors from direct produce() during open transaction: {direct_errors}" + assert len(direct_delivered) == num_threads * messages_per_thread + + consumer = _read_committed_consumer(kafka_cluster, topic) + msg_cnt = _drain_committed(consumer) + consumer.close() + + print(f"{called_by()}: visible_after_commit={msg_cnt}") + assert msg_cnt == num_threads * messages_per_thread + finally: + await producer.close() + + async def test_close_races_commit_transaction(self, kafka_cluster): + """close() concurrent with commit_transaction() via the executor. + Unlike the sync Producer, close() never calls the underlying Producer's + own close() -- so the only real interaction between the two here is contention + for the shared ThreadPoolExecutor. That means only two outcomes are legitimate: + either commit_transaction()'s work gets submitted before + executor.shutdown() takes effect and the commit genuinely + completes (verified below via a real read_committed consumer), or + it's submitted after and fails with the stdlib RuntimeError + ThreadPoolExecutor raises for exactly that case.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_close_races_commit") + producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-close-commit-{uuid1()}'}) + + await producer.init_transactions() + await producer.begin_transaction() + await producer.produce(topic, value=b'msg') + + commit_result, close_result = await asyncio.wait_for( + asyncio.gather(producer.commit_transaction(), producer.close(), return_exceptions=True), + timeout=30, + ) + + print(f"{called_by()}: commit_result={commit_result!r}, close_result={close_result!r}") + + assert not isinstance(close_result, Exception), f"close() unexpectedly raised: {close_result!r}" + + if isinstance(commit_result, Exception): + assert isinstance(commit_result, RuntimeError) and 'shutdown' in str(commit_result), ( + f"commit_transaction() failed with an unexpected error -- only the executor's " + f"post-shutdown RuntimeError is legitimate for this race, got: {commit_result!r}" + ) + else: + consumer = _read_committed_consumer(kafka_cluster, topic) + msg_cnt = _drain_committed(consumer) + consumer.close() + assert msg_cnt == 1, f"commit_transaction() reported success but the message isn't visible: {msg_cnt}" diff --git a/tests/integration/producer/test_concurrency.py b/tests/integration/producer/test_concurrency.py index a2b40fee7..02727f097 100644 --- a/tests/integration/producer/test_concurrency.py +++ b/tests/integration/producer/test_concurrency.py @@ -520,6 +520,75 @@ def call_abort(): successes = [k for k, v in results.items() if v is True] assert len(successes) == 1, f"expected exactly one of commit/abort to succeed, got: {results}" + def test_multiple_independent_transactional_producers_concurrent(self, kafka_cluster): + """Several producer instances, each with its own distinct + transactional.id, running a full init/begin/produce/commit + lifecycle concurrently on separate threads must not interfere with + each other -- every producer's transaction should complete and + commit independently, and none should block or corrupt another's.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_txn_multiple_independent_producers") + num_producers = 6 + messages_per_producer = 20 + errors = [] + + def worker(producer_id): + try: + producer = kafka_cluster.producer( + { + 'transactional.id': f'test-txn-independent-{producer_id}-{uuid1()}', + 'error_cb': prefixed_error_cb( + f'test_multiple_independent_transactional_producers_concurrent-{producer_id}' + ), + } + ) + producer.init_transactions() + producer.begin_transaction() + for i in range(messages_per_producer): + producer.produce(topic, value=f'producer-{producer_id}-msg-{i}'.encode()) + producer.commit_transaction() + producer.flush() + except Exception as e: # noqa: BLE001 - want to see any exception, not just crashes + errors.append((producer_id, e)) + + threads = [threading.Thread(target=worker, args=(i,)) for i in range(num_producers)] + for t in threads: + t.start() + for t in threads: + t.join(timeout=30) + + print(f"{called_by()}: {num_producers} independent producers finished, errors={errors}") + assert all(not t.is_alive() for t in threads), "a producer thread did not finish" + assert not errors, f"unexpected exceptions from independent transactional producers: {errors}" + + consumer_conf = kafka_cluster.client_conf() + consumer_conf.update( + { + 'group.id': str(uuid1()), + 'auto.offset.reset': 'earliest', + 'enable.auto.commit': False, + 'enable.partition.eof': True, + 'isolation.level': 'read_committed', + } + ) + consumer = TestConsumer(consumer_conf) + consumer.subscribe([topic]) + + msg_cnt = 0 + eof_reached = False + while not eof_reached: + msg = consumer.poll(timeout=10.0) + assert msg is not None, "timed out waiting for messages" + if msg.error(): + if msg.error().code() == KafkaError._PARTITION_EOF: + eof_reached = True + continue + raise KafkaException(msg.error()) + msg_cnt += 1 + consumer.close() + + print(f"{called_by()}: consumed msg_cnt={msg_cnt}") + assert msg_cnt == num_producers * messages_per_producer + class TestReentrantDeliveryCallback: """Delivery callbacks run synchronously inside poll()/flush() on diff --git a/tests/integration/producer/test_transactions.py b/tests/integration/producer/test_transactions.py index fe04c02e4..5bf603155 100644 --- a/tests/integration/producer/test_transactions.py +++ b/tests/integration/producer/test_transactions.py @@ -17,9 +17,10 @@ # import inspect import sys +import time from uuid import uuid1 -from confluent_kafka import KafkaError +from confluent_kafka import OFFSET_INVALID, KafkaError from tests.common import TestConsumer @@ -153,6 +154,122 @@ def test_send_offsets_committed_transaction(kafka_cluster): consumer.close() +def test_send_offsets_aborted_transaction(kafka_cluster): + """Offsets passed to send_offsets_to_transaction() must not be + committed if the transaction is aborted rather than committed.""" + input_topic = kafka_cluster.create_topic_and_wait_propogation("input_topic") + output_topic = kafka_cluster.create_topic_and_wait_propogation("output_topic") + error_cb = prefixed_error_cb('test_send_offsets_aborted_transaction') + producer = kafka_cluster.producer( + { + 'transactional.id': 'example_transactional_id', + 'error_cb': error_cb, + } + ) + + consumer_conf = { + 'group.id': str(uuid1()), + 'auto.offset.reset': 'earliest', + 'enable.auto.commit': False, + 'enable.partition.eof': True, + 'error_cb': error_cb, + } + consumer_conf.update(kafka_cluster.client_conf()) + consumer = TestConsumer(consumer_conf) + + kafka_cluster.seed_topic(input_topic) + consumer.subscribe([input_topic]) + + read_all_msgs(consumer) + + producer.init_transactions() + transactional_produce(producer, output_topic, 100) + + consumer_position = consumer.position(consumer.assignment()) + group_metadata = consumer.consumer_group_metadata() + print("=== Sending offsets {} to transaction (to be aborted) ===".format(consumer_position)) + producer.send_offsets_to_transaction(consumer_position, group_metadata) + producer.abort_transaction() + + committed_offsets = consumer.committed(consumer.assignment()) + print("=== Committed offsets after abort: {} ===".format(committed_offsets)) + assert all( + tp.offset == OFFSET_INVALID for tp in committed_offsets + ), f"expected no committed offsets after an aborted transaction, got: {committed_offsets}" + + # The produced messages must not be visible either. + assert consume_committed(kafka_cluster.client_conf(), output_topic) == 0 + + consumer.close() + + +def test_close_resolves_open_transaction_promptly(kafka_cluster): + """close() should actively abort an open transaction rather + than leave it dangling on the broker. A dangling transaction blocks its + partition's last-stable-offset (LSO) from advancing, so a read_committed + consumer can't see any later message on that partition until the transaction + resolves. Without an explicit abort, that only happens once transaction.timeout.ms + elapses; with one, it should happen almost immediately. + """ + output_topic = kafka_cluster.create_topic_and_wait_propogation("output_topic") + + txn_timeout_ms = 15000 + visibility_deadline_s = 7 + + producer1 = kafka_cluster.producer( + { + 'transactional.id': f'test_close_resolves_open_transaction_promptly-{uuid1()}', + 'transaction.timeout.ms': txn_timeout_ms, + 'error_cb': prefixed_error_cb('test_close_resolves_open_transaction_promptly-p1'), + } + ) + producer1.init_transactions() + producer1.begin_transaction() + producer1.produce(output_topic, value=b'from-open-txn') + producer1.flush() + + # Deliberately close() without calling abort_transaction() + assert producer1.close() is True + + # Now create a new non-transactional producer and produce one msg to the same topic + producer2 = kafka_cluster.producer( + {'error_cb': prefixed_error_cb('test_close_resolves_open_transaction_promptly-p2')} + ) + producer2.produce(output_topic, value=b'plain-message-after-close') + producer2.close() + + # Create a new consumer to try reading the msg produced by producer2 + consumer_conf = kafka_cluster.client_conf() + consumer_conf.update( + { + 'group.id': str(uuid1()), + 'auto.offset.reset': 'earliest', + 'enable.auto.commit': False, + 'isolation.level': 'read_committed', + 'error_cb': prefixed_error_cb('test_close_resolves_open_transaction_promptly-consumer'), + } + ) + consumer = TestConsumer(consumer_conf) + consumer.subscribe([output_topic]) + + deadline = time.monotonic() + visibility_deadline_s + msg = None + while time.monotonic() < deadline: + msg = consumer.poll(timeout=0.5) + if msg is not None and msg.error() is None: + break + msg = None + + consumer.close() + + assert msg is not None, ( + f"plain message produced after close() was not visible to a read_committed " + f"consumer within {visibility_deadline_s}s -- the transaction left open by " + f"close() is blocking the partition's last-stable-offset from advancing" + ) + assert msg.value() == b'plain-message-after-close' + + def transactional_produce(producer, topic, num_messages): print("=== Producing {} transactional messages to topic {}. ===".format(num_messages, topic)) From b2aa8b00497ac165c12d4bd51c6a788d283921fc Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Sun, 23 Aug 2026 18:39:57 +0530 Subject: [PATCH 05/14] Fix flaky AIO Producer test case --- .../integration/producer/test_aio_producer.py | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/integration/producer/test_aio_producer.py b/tests/integration/producer/test_aio_producer.py index a2ac8d0ce..7642180c0 100644 --- a/tests/integration/producer/test_aio_producer.py +++ b/tests/integration/producer/test_aio_producer.py @@ -554,16 +554,16 @@ async def test_concurrent_calls_to_different_transaction_apis(self, kafka_cluste finally: await producer.close() - async def test_concurrent_produce_races_commit_boundary(self, kafka_cluster): + async def test_concurrent_produce_into_shared_buffer_then_commit(self, kafka_cluster): """Multiple coroutines concurrently calling produce(), which queue into AIOProducer's own internal batch buffer, not directly into - librdkafka, while another coroutine calls commit_transaction(). - Every produced message's future must resolve to exactly one of: - delivered and visible after commit, or a clean error -- never - silently missing, never double-counted. There is no lock guarding the buffer - (see _producer_batch_processor.py); this relies entirely on asyncio's cooperative - scheduling to keep buffer bookkeeping race-free, which is exactly what this test - exercises.""" + librdkafka. Every produced message's future must resolve to exactly + one of: delivered and visible after commit, or a clean error -- never + silently missing, never double-counted. There is no lock guarding the + buffer (see _producer_batch_processor.py); this relies entirely on + asyncio's cooperative scheduling to keep buffer bookkeeping race-free, + which is exactly what the concurrent producers exercise. + """ topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_buffer_boundary") producer = await _new_aio_producer( kafka_cluster, {'transactional.id': f'test-aio-txn-buffer-boundary-{uuid1()}'}, batch_size=10 @@ -582,16 +582,16 @@ async def produce_worker(worker_id): for i in range(messages_per_worker) ] - produce_task = asyncio.gather(*(produce_worker(i) for i in range(num_workers))) - commit_task = asyncio.ensure_future(producer.commit_transaction()) - - all_futures_by_worker, _ = await asyncio.gather(produce_task, commit_task) + all_futures_by_worker = await asyncio.gather(*(produce_worker(i) for i in range(num_workers))) all_futures = [f for worker_futures in all_futures_by_worker for f in worker_futures] + await producer.flush() results = await asyncio.gather(*all_futures, return_exceptions=True) succeeded = [r for r in results if not isinstance(r, Exception)] failed = [r for r in results if isinstance(r, Exception)] + await producer.commit_transaction() + consumer = _read_committed_consumer(kafka_cluster, topic) msg_cnt = _drain_committed(consumer) consumer.close() From 84480fc713092edf7e6d09b2ec67cad7cab5598b Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Mon, 24 Aug 2026 13:32:24 +0530 Subject: [PATCH 06/14] Fix for serializing concurrent calls from a Async callback --- src/confluent_kafka/aio/_AIOConsumer.py | 16 +- src/confluent_kafka/aio/_common.py | 54 ++++-- ...t_aio_consumer_concurrent_serialization.py | 142 ++++++++++++++- tests/test_AIOConsumer.py | 162 +++++++++++++++--- 4 files changed, 330 insertions(+), 44 deletions(-) diff --git a/src/confluent_kafka/aio/_AIOConsumer.py b/src/confluent_kafka/aio/_AIOConsumer.py index 79bb5ccf5..a93251862 100644 --- a/src/confluent_kafka/aio/_AIOConsumer.py +++ b/src/confluent_kafka/aio/_AIOConsumer.py @@ -85,17 +85,25 @@ async def _call(self, blocking_task: Callable[..., Any], *args: Any, **kwargs: A raise RuntimeError("Consumer closed") # Resolved here, on the event-loop thread, so a re-entrant call reuses - # the enclosing call's identity -- see _common.ReentryIdentity. - identity = _common.ReentryIdentity.get_or_generate() + # the enclosing call's identity -- see _common.ReentryContext. + identity = _common.ReentryContext.get_or_generate_id() + + # Using the lock, the call gets serialized against any sibling in + # the same callback invocation dispatched concurrently. + # For any calls from outside a callback, this value stays None. + lock = _common.ReentryContext.current_lock() # Presented from inside wrapped_task so it is visible to the call it # guards, including any re-entrant callback (e.g. on_assign) that # blocking_task triggers synchronously before returning. def wrapped_task(*task_args: Any, **task_kwargs: Any) -> Any: - with _common.ReentryIdentity.active(identity): + with _common.ReentryContext.active(identity): return blocking_task(*task_args, **task_kwargs) - return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) + if lock is None: + return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) + async with lock: + return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) def _wrap_callback( self, diff --git a/src/confluent_kafka/aio/_common.py b/src/confluent_kafka/aio/_common.py index 12be94976..34572ffc7 100644 --- a/src/confluent_kafka/aio/_common.py +++ b/src/confluent_kafka/aio/_common.py @@ -15,6 +15,7 @@ import asyncio import concurrent.futures import contextlib +import contextvars import functools import itertools import logging @@ -25,9 +26,10 @@ T = TypeVar('T') -class ReentryIdentity: - """Internal use only. The identity AIOConsumer presents to the Consumer - reentrancy gate. +class ReentryContext: + """Internal use only. Per-call-chain context AIOConsumer carries through + a ContextVar: the identity presented to the Consumer reentrancy gate, and + the lock serializing concurrent dispatches within one callback invocation. The sync Consumer uses the calling thread's ID as its gate identity, but that does not work for AIOConsumer: a call and the re-entrant calls its @@ -38,7 +40,12 @@ class ReentryIdentity: -- see Handle_gate_enter() in Consumer.c. """ - _var = cimpl._reentry_identity_var + # The ContextVar the C gate itself reads, defined in confluent_kafka.c. + _id_var = cimpl._reentry_identity_var + + # Serializes concurrent/un-awaited calls dispatched from within the same + # callback invocation. Not used by C gate and only used by AIO Consumer. + _lock_var: contextvars.ContextVar = contextvars.ContextVar('reentry_lock_var', default=None) # Process-wide counter generating identities. _ctr = itertools.count(1) @@ -48,31 +55,41 @@ class ReentryIdentity: _MASK = 0xFFFFFFFF @classmethod - def get_or_generate(cls) -> int: + def get_or_generate_id(cls) -> int: """Return the identity for an AIOConsumer call: the current context's identity for a re-entrant call, or a fresh one for a top-level call. Must be called on the event-loop thread, before dispatching to the executor. """ - identity = cls.current() + identity = cls.current_id() if identity: return identity return (next(cls._ctr) & cls._MASK) or 1 @classmethod - def current(cls) -> int: + def current_id(cls) -> int: """Return the identity of the call currently in flight, or 0 if none. Called on a worker thread from inside a gated call, to capture the identity that the enclosing call set. """ - return cls._var.get() + return cls._id_var.get() + + @classmethod + def current_lock(cls) -> Optional[asyncio.Lock]: + """Return the lock serializing calls dispatched concurrently from + the current callback invocation, or None for a top-level call. + + Called on the event-loop thread, before dispatching to the executor. + """ + return cls._lock_var.get() @classmethod @contextlib.contextmanager - def active(cls, identity: int) -> Iterator[None]: - """Present `identity` to the gate for the duration of the block. + def active(cls, identity: int, lock: Optional[asyncio.Lock] = None) -> Iterator[None]: + """Present `identity` (and, for a callback invocation, `lock`) to + the gate for the duration of the block. The identity is set here, inside the worker thread (or callback task) that makes the call, rather than before dispatching to the executor: @@ -80,11 +97,13 @@ def active(cls, identity: int) -> Iterator[None]: thread's Context is first established, so a set() on the event-loop thread would be invisible to later calls reusing the same worker. """ - token = cls._var.set(identity) + active_id = cls._id_var.set(identity) + active_lock = cls._lock_var.set(lock) try: yield finally: - cls._var.reset(token) + cls._id_var.reset(active_id) + cls._lock_var.reset(active_lock) class AsyncLogger: @@ -112,13 +131,14 @@ def ret(*args: Any, **kwargs: Any) -> Any: # Set by the enclosing call's wrapped_task before this callback # trampoline fired -- see AIOConsumer._call(). - identity = ReentryIdentity.current() + identity = ReentryContext.current_id() async def _run_with_identity() -> Any: - # Tasks the callback spawns inherit this identity, so calls back into the - # Consumer must be awaited one at a time -- concurrent ones (gather, - # or an un-awaited create_task) would all be let through the gate. - with ReentryIdentity.active(identity): + # A fresh lock per invocation. Concurrent calls from the + # callback inherit the ID and lock via context propagation + # to the tasks asyncio creates for them, so only one is ever + # dispatched to the gate at a time. + with ReentryContext.active(identity, asyncio.Lock()): return await callback(*args, **kwargs) f = asyncio.run_coroutine_threadsafe(_run_with_identity(), loop) diff --git a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py index 96a6889e8..a5660f5a8 100644 --- a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py +++ b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py @@ -20,7 +20,10 @@ Out of multiple independent calls racing on the same underlying Consumer Handle, a colliding call waits for the current holder to release the gate, then proceeds -- it is not rejected. Only a genuinely re-entrant call (same -identity) is admitted immediately. +identity) is admitted immediately. Also covers same-identity concurrency: +concurrent or un-awaited calls a callback dispatches back into the Consumer +(gather(), or an un-awaited create_task()) all present the same identity, +so the gate alone can't tell them apart from a single sequential re-entrant call. """ import asyncio @@ -206,3 +209,140 @@ async def seed_after_collision(): ) await consumer.close() + + +async def test_gathered_reentrant_calls_from_callback_serialize(kafka_cluster): + """on_assign completes the required incremental_assign() first (fast), + then reentrantly fires two concurrent consume() calls via + asyncio.gather(). Both dispatches present the same identity, so the gate + alone would let them both through at once, the per-callback lock must + serialize them instead.""" + topic = kafka_cluster.create_topic_and_wait_propogation( + "test_gathered_reentrant_serialize", conf={'num_partitions': 4} + ) + + consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) + + elapsed = [] + + async def on_assign(consumer, partitions): + await consumer.incremental_assign(partitions) + t0 = time.time() + await asyncio.gather( + consumer.consume(num_messages=1, timeout=1.0), + consumer.consume(num_messages=1, timeout=1.0), + ) + elapsed.append(time.time() - t0) + + await consumer.subscribe([topic], on_assign=on_assign) + await consumer.poll(10) + + result = await consumer.assignment() + + print(f"elapsed={elapsed}, result={result}") + assert elapsed, "on_assign was never invoked" + assert elapsed[0] >= 2.0, ( + f"the two concurrent consume() calls completed in {elapsed[0]:.2f}s -- " + f"too fast to have been serialized (each blocks ~1.0s with nothing to consume, " + f"so a genuinely serialized pair must take >= 2.0s)" + ) + assert len(result) == 4, f"expected all 4 partitions assigned, got {result}" + + await consumer.close() + + +async def test_unawaited_create_task_from_callback_serializes(kafka_cluster): + """Same shape as test_gathered_reentrant_calls_from_callback_serialize, + but after completing the required incremental_assign(), on_assign fires one + consume() call via create_task() without immediately awaiting it, makes + its own reentrant consume() call directly, and only awaits the created + task afterward. Must still serialize.""" + topic = kafka_cluster.create_topic_and_wait_propogation( + "test_unawaited_task_reentrant_serialize", conf={'num_partitions': 4} + ) + + consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) + + elapsed = [] + + async def on_assign(consumer, partitions): + await consumer.incremental_assign(partitions) + t0 = time.time() + task = asyncio.create_task(consumer.consume(num_messages=1, timeout=1.0)) + await consumer.consume(num_messages=1, timeout=1.0) + await task + elapsed.append(time.time() - t0) + + await consumer.subscribe([topic], on_assign=on_assign) + await consumer.poll(10) + + result = await consumer.assignment() + + print(f"elapsed={elapsed}, result={result}") + assert elapsed, "on_assign was never invoked" + assert elapsed[0] >= 2.0, ( + f"the un-awaited create_task() call and the direct reentrant call completed in " + f"{elapsed[0]:.2f}s -- too fast to have been serialized (each blocks ~1.0s with " + f"nothing to consume, so a genuinely serialized pair must take >= 2.0s)" + ) + assert len(result) == 4, f"expected all 4 partitions assigned, got {result}" + + await consumer.close() + + +async def test_reentrant_gather_one_call_fails_lock_still_releases(kafka_cluster): + """on_commit fires two concurrent reentrant commit() calls via gather(): + one deliberately invalid and one valid. The invalid call's failure must + not leave the per-callback dispatch lock stuck -- the valid concurrent + call must still complete, and the consumer must remain fully usable afterward.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_reentrant_gather_failure_releases_lock") + kafka_cluster.seed_topic(topic, value_source=[b'hello']) + + commit_called = [] + reentrant_results = [] + consumer = None + msg = None + + async def on_commit(err, partitions): + commit_called.append((err, partitions)) + if len(commit_called) == 1: + results = await asyncio.gather( + consumer.commit(message=msg, offsets=[], asynchronous=False), # invalid: raises ValueError + consumer.commit(message=msg, asynchronous=False), # valid + return_exceptions=True, + ) + reentrant_results.append(results) + + consumer = await _new_aio_consumer(kafka_cluster, {'on_commit': on_commit}) + + async def on_assign(consumer, partitions): + await consumer.assign(partitions) + + await consumer.subscribe([topic], on_assign=on_assign) + + msg = await consumer.poll(10) + assert msg is not None + + await consumer.commit(message=msg, asynchronous=True) + for _ in range(50): + await consumer.poll(0.1) + if commit_called: + break + + print(f"commit_called={len(commit_called)}, reentrant_results={reentrant_results}") + assert commit_called, "on_commit was never invoked" + assert reentrant_results, "the concurrent reentrant commit() calls never completed" + results = reentrant_results[0] + errors = [r for r in results if isinstance(r, Exception)] + successes = [r for r in results if not isinstance(r, Exception)] + assert len(errors) == 1 and isinstance( + errors[0], ValueError + ), f"expected exactly one ValueError from the invalid concurrent call, got: {results}" + assert len(successes) == 1, f"expected the other concurrent commit() call to succeed, got: {results}" + + # The lock must have released despite the failure -- this plain, + # non-re-entrant commit() call afterward must succeed. + result = await consumer.commit(message=msg, asynchronous=False) + assert result is not None + + await consumer.close() diff --git a/tests/test_AIOConsumer.py b/tests/test_AIOConsumer.py index ec1bb0b8c..207427f3b 100644 --- a/tests/test_AIOConsumer.py +++ b/tests/test_AIOConsumer.py @@ -3,6 +3,8 @@ import asyncio import concurrent.futures import itertools +import threading +import time from unittest.mock import Mock, patch import pytest @@ -65,14 +67,14 @@ async def test_call_method_executor_usage(self, mock_consumer, mock_common, basi """Test that _call method properly uses ThreadPoolExecutor for async-to-sync bridging, setting the identity presented to the Consumer gate on the reentry ContextVar before invoking it.""" - mock_common.ReentryIdentity.get_or_generate.return_value = 42 + mock_common.ReentryContext.get_or_generate_id.return_value = 42 consumer = AIOConsumer(basic_config) mock_method = Mock(return_value="test_result") result = await consumer._call(mock_method, "arg1", kwarg1="value1") mock_method.assert_called_once_with("arg1", kwarg1="value1") - mock_common.ReentryIdentity.active.assert_called_once_with(42) + mock_common.ReentryContext.active.assert_called_once_with(42) assert result == "test_result" @pytest.mark.asyncio @@ -249,55 +251,171 @@ async def test_identity_does_not_leak_into_recycled_worker_thread(self, mock_con await consumer._call(lambda: None) # Submitted directly to the same single-worker executor, - # bypassing _call()/ReentryIdentity entirely, to force reuse of + # bypassing _call()/ReentryContext entirely, to force reuse of # the same OS thread _call() just used. leaked = await asyncio.get_event_loop().run_in_executor(executor, cimpl._reentry_identity_var.get) assert leaked == 0, f"identity leaked into the worker thread's persistent context: {leaked}" finally: executor.shutdown(wait=True) + @pytest.mark.asyncio + async def test_call_acquires_and_releases_context_bound_lock(self, mock_consumer, basic_config): + """_call() must acquire the lock bound in the current context (as + wrap_callback binds one per callback invocation) around the + executor dispatch, and release it once the dispatch completes.""" + consumer = AIOConsumer(basic_config, max_workers=2) + assert _common.ReentryContext.current_lock() is None + assert await consumer._call(lambda: "ok") == "ok" + + lock = asyncio.Lock() + entered = threading.Event() + release = threading.Event() + + def blocking_task(): + entered.set() + release.wait(timeout=5) + return "done" + + async def call_under_lock(): + with _common.ReentryContext.active(_common.ReentryContext.get_or_generate_id(), lock): + return await consumer._call(blocking_task) + + task = asyncio.create_task(call_under_lock()) + await asyncio.get_event_loop().run_in_executor(None, entered.wait, 5) + assert lock.locked(), "the context-bound lock must be held while the dispatch is in flight" + + release.set() + result = await task + + assert result == "done" + assert not lock.locked(), "the lock must be released once the dispatch completes" + + @pytest.mark.asyncio + async def test_concurrent_reentrant_calls_sharing_lock_serialize(self, mock_consumer, basic_config): + """Two reentrant calls sharing the same callback-bound lock -- as + gather()/create_task() from within a callback produce, since both + inherit the same context -- must never run their blocking_task + concurrently..""" + consumer = AIOConsumer(basic_config, max_workers=3) + lock = asyncio.Lock() + identity = _common.ReentryContext.get_or_generate_id() + + active_count = 0 + max_active = 0 + count_lock = threading.Lock() + + def blocking_task(): + nonlocal active_count, max_active + with count_lock: + active_count += 1 + max_active = max(max_active, active_count) + time.sleep(0.1) + with count_lock: + active_count -= 1 + return "ok" -class TestReentryIdentity: - """Unit tests for confluent_kafka.aio._common.ReentryIdentity: the + async def reentrant_call(): + return await consumer._call(blocking_task) + + with _common.ReentryContext.active(identity, lock): + results = await asyncio.gather(reentrant_call(), reentrant_call()) + + assert results == ["ok", "ok"] + assert ( + max_active == 1 + ), f"blocking_task ran concurrently (max_active={max_active}) -- the lock failed to serialize" + + @pytest.mark.asyncio + async def test_wrap_callback_binds_a_fresh_lock_per_invocation(self, mock_consumer, basic_config): + """wrap_callback's trampoline must bind a fresh asyncio.Lock per + invocation, visible to the wrapped callback via current_lock(). + Two separate invocations (e.g. two separate rebalances) must not share + a lock with each other.""" + consumer = AIOConsumer(basic_config, max_workers=2) + loop = asyncio.get_event_loop() + seen_locks = [] + + async def callback(*args, **kwargs): + seen_locks.append(_common.ReentryContext.current_lock()) + + wrapped = consumer._wrap_callback(loop, callback) + + await loop.run_in_executor(None, wrapped) + await loop.run_in_executor(None, wrapped) + + assert len(seen_locks) == 2 + assert all(isinstance(lock, asyncio.Lock) for lock in seen_locks) + assert seen_locks[0] is not seen_locks[1], "each callback invocation must get its own fresh lock" + + +class TestReentryContext: + """Unit tests for confluent_kafka.aio._common.ReentryContext: the identity AIOConsumer presents to the Consumer gate.""" - def test_get_or_generate_returns_nonzero_and_distinct_identities(self): + def test_get_or_generate_id_returns_nonzero_and_distinct_identities(self): """Two independent (non-nested) top-level calls must each get their own fresh, nonzero identity -- 0 means "not set" to the gate.""" - a = _common.ReentryIdentity.get_or_generate() - b = _common.ReentryIdentity.get_or_generate() + a = _common.ReentryContext.get_or_generate_id() + b = _common.ReentryContext.get_or_generate_id() assert a != 0 and b != 0 assert a != b - def test_active_sets_current_reuses_for_get_or_generate_then_resets_on_exit(self): + def test_active_sets_current_id_reuses_for_get_or_generate_id_then_resets_on_exit(self): """active() must, for the duration of its block: (1) make the - identity visible via current(), and (2) have get_or_generate() + identity visible via current_id(), and (2) have get_or_generate_id() reuse it rather than generating a fresh one -- this is what lets a re-entrant call present the same identity through the gate. Once the block exits, it must reset the ContextVar rather than just setting it.""" - assert _common.ReentryIdentity.current() == 0 - with _common.ReentryIdentity.active(4242): - assert _common.ReentryIdentity.current() == 4242 - assert _common.ReentryIdentity.get_or_generate() == 4242 - assert _common.ReentryIdentity.current() == 0 + assert _common.ReentryContext.current_id() == 0 + with _common.ReentryContext.active(4242): + assert _common.ReentryContext.current_id() == 4242 + assert _common.ReentryContext.get_or_generate_id() == 4242 + assert _common.ReentryContext.current_id() == 0 def test_active_nesting_restores_outer_identity(self): - with _common.ReentryIdentity.active(11): - with _common.ReentryIdentity.active(22): - assert _common.ReentryIdentity.current() == 22 - assert _common.ReentryIdentity.current() == 11 - assert _common.ReentryIdentity.current() == 0 + with _common.ReentryContext.active(11): + with _common.ReentryContext.active(22): + assert _common.ReentryContext.current_id() == 22 + assert _common.ReentryContext.current_id() == 11 + assert _common.ReentryContext.current_id() == 0 def test_generated_identity_stays_within_unsigned_long_mask(self, monkeypatch): """The gate stores an identity in a C unsigned long, 32-bit on Windows, so generated identities must always fit -- verified here by forcing the counter to the edge of that range and confirming it wraps instead of overflowing.""" - monkeypatch.setattr(_common.ReentryIdentity, '_ctr', itertools.count(0xFFFFFFFE)) - seen = [_common.ReentryIdentity.get_or_generate() for _ in range(5)] + monkeypatch.setattr(_common.ReentryContext, '_ctr', itertools.count(0xFFFFFFFE)) + seen = [_common.ReentryContext.get_or_generate_id() for _ in range(5)] assert all(0 < i <= 0xFFFFFFFF for i in seen), seen # 0xFFFFFFFF + 1 wraps to 0, remapped to 1 (0 means unset); the next # draw masks to 1 too (0x100000001 & 0xFFFFFFFF == 1), so 1 appears # twice at the wrap before the sequence continues from 2. assert seen == [0xFFFFFFFE, 0xFFFFFFFF, 1, 1, 2], seen + + def test_active_with_lock_binds_current_lock_then_resets_to_none(self): + lock = asyncio.Lock() + assert _common.ReentryContext.current_lock() is None + with _common.ReentryContext.active(1, lock): + assert _common.ReentryContext.current_lock() is lock + assert _common.ReentryContext.current_lock() is None + + def test_active_nesting_with_lock_restores_outer_lock(self): + outer_lock = asyncio.Lock() + inner_lock = asyncio.Lock() + with _common.ReentryContext.active(1, outer_lock): + with _common.ReentryContext.active(2, inner_lock): + assert _common.ReentryContext.current_lock() is inner_lock + assert _common.ReentryContext.current_lock() is outer_lock + assert _common.ReentryContext.current_lock() is None + + def test_active_without_lock_arg_clears_outer_lock_for_the_block(self): + """active() called without a lock argument does not preserve an + outer bound lock -- it explicitly clears it for the duration of + the block, then restores it on exit.""" + lock = asyncio.Lock() + with _common.ReentryContext.active(1, lock): + assert _common.ReentryContext.current_lock() is lock + with _common.ReentryContext.active(2): + assert _common.ReentryContext.current_lock() is None + assert _common.ReentryContext.current_lock() is lock From c50df1973978a1c92882b128c431ef05bf621009 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Mon, 24 Aug 2026 15:39:41 +0530 Subject: [PATCH 07/14] Minor improvements to tests --- ...t_aio_consumer_concurrent_serialization.py | 49 +++++++++++++++++-- .../integration/producer/test_aio_producer.py | 10 ++-- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py index a5660f5a8..2560107a4 100644 --- a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py +++ b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py @@ -251,14 +251,15 @@ async def on_assign(consumer, partitions): await consumer.close() -async def test_unawaited_create_task_from_callback_serializes(kafka_cluster): +async def test_joined_create_task_from_callback_serializes(kafka_cluster): """Same shape as test_gathered_reentrant_calls_from_callback_serialize, but after completing the required incremental_assign(), on_assign fires one consume() call via create_task() without immediately awaiting it, makes its own reentrant consume() call directly, and only awaits the created - task afterward. Must still serialize.""" + task afterward -- i.e. the task is created early but still joined before + the callback returns. Must still serialize.""" topic = kafka_cluster.create_topic_and_wait_propogation( - "test_unawaited_task_reentrant_serialize", conf={'num_partitions': 4} + "test_joined_task_reentrant_serialize", conf={'num_partitions': 4} ) consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) @@ -281,7 +282,7 @@ async def on_assign(consumer, partitions): print(f"elapsed={elapsed}, result={result}") assert elapsed, "on_assign was never invoked" assert elapsed[0] >= 2.0, ( - f"the un-awaited create_task() call and the direct reentrant call completed in " + f"the created-but-not-yet-awaited task and the direct reentrant call completed in " f"{elapsed[0]:.2f}s -- too fast to have been serialized (each blocks ~1.0s with " f"nothing to consume, so a genuinely serialized pair must take >= 2.0s)" ) @@ -290,6 +291,46 @@ async def on_assign(consumer, partitions): await consumer.close() +async def test_detached_create_task_from_callback_still_serializes_afterward(kafka_cluster): + """on_assign fires a consume() call via create_task() and returns + WITHOUT ever awaiting it. This lets the top-level poll() that invoked + on_assign fully return and release the gate while the detached call may + still be in flight (dispatched with on_assign's identity, on its own executor worker).""" + topic = kafka_cluster.create_topic_and_wait_propogation( + "test_detached_task_reentrant_serialize", conf={'num_partitions': 4} + ) + + consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) + + detached_tasks = [] + + async def on_assign(consumer, partitions): + await consumer.incremental_assign(partitions) + detached_tasks.append(asyncio.create_task(consumer.consume(num_messages=1, timeout=1.0))) + + await consumer.subscribe([topic], on_assign=on_assign) + await consumer.poll(10) + + assert detached_tasks, "on_assign was never invoked" + + t0 = time.time() + await consumer.consume(num_messages=1, timeout=1.0) + elapsed = time.time() - t0 + + result = await consumer.assignment() + await detached_tasks[0] # join it before close() so nothing is left dangling + + print(f"elapsed={elapsed:.2f}s, result={result}") + assert elapsed >= 1.0, ( + f"the unrelated call issued right after poll() returned completed in {elapsed:.2f}s -- " + f"too fast to have waited for on_assign's still-in-flight detached call, meaning the " + f"gate let them run concurrently" + ) + assert len(result) == 4, f"expected all 4 partitions assigned, got {result}" + + await consumer.close() + + async def test_reentrant_gather_one_call_fails_lock_still_releases(kafka_cluster): """on_commit fires two concurrent reentrant commit() calls via gather(): one deliberately invalid and one valid. The invalid call's failure must diff --git a/tests/integration/producer/test_aio_producer.py b/tests/integration/producer/test_aio_producer.py index 7642180c0..eefbf8892 100644 --- a/tests/integration/producer/test_aio_producer.py +++ b/tests/integration/producer/test_aio_producer.py @@ -681,9 +681,13 @@ async def test_close_races_commit_transaction(self, kafka_cluster): topic = kafka_cluster.create_topic_and_wait_propogation("test_aio_txn_close_races_commit") producer = await _new_aio_producer(kafka_cluster, {'transactional.id': f'test-aio-txn-close-commit-{uuid1()}'}) - await producer.init_transactions() - await producer.begin_transaction() - await producer.produce(topic, value=b'msg') + try: + await producer.init_transactions() + await producer.begin_transaction() + await producer.produce(topic, value=b'msg') + except Exception: + await producer.close() + raise commit_result, close_result = await asyncio.wait_for( asyncio.gather(producer.commit_transaction(), producer.close(), return_exceptions=True), From 503a4b26941d717c1c192693acf0397469c79068 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Mon, 24 Aug 2026 18:48:35 +0530 Subject: [PATCH 08/14] Fix styling --- tests/integration/consumer/test_aio_consumer_misc.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/integration/consumer/test_aio_consumer_misc.py b/tests/integration/consumer/test_aio_consumer_misc.py index f32147c09..9014c9939 100644 --- a/tests/integration/consumer/test_aio_consumer_misc.py +++ b/tests/integration/consumer/test_aio_consumer_misc.py @@ -152,6 +152,7 @@ async def test_call_after_close_raises(kafka_cluster): with pytest.raises(RuntimeError, match="Consumer closed"): await consumer.close() + async def test_async_context_manager_closes_on_exit(kafka_cluster): """The consumer must be usable inside the ctx manager block, and __aexit__ must actually close it -- confirmed by a subsequent call From 3b039de6f2f08c9d4f12dc5b28ecbe166b81a804 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Mon, 24 Aug 2026 22:23:40 +0530 Subject: [PATCH 09/14] Fix flaky test case --- tests/integration/producer/test_aio_producer.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/integration/producer/test_aio_producer.py b/tests/integration/producer/test_aio_producer.py index eefbf8892..4c6fc60f0 100644 --- a/tests/integration/producer/test_aio_producer.py +++ b/tests/integration/producer/test_aio_producer.py @@ -395,10 +395,13 @@ async def test_error_cb_reentrant_poll_completes_with_two_workers(self): kafka_cluster, this is purely about the executor/callback interaction.""" error_cb_called = [] reentrant_results = [] + reentrant_attempted = False async def error_cb(err): + nonlocal reentrant_attempted error_cb_called.append(err) - if not reentrant_results: + if not reentrant_attempted: + reentrant_attempted = True result = await producer.poll(0) reentrant_results.append(result) From f75dba3a1525df3c20fc7216ee00b31a6d9cf1b0 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Thu, 27 Aug 2026 23:43:40 +0530 Subject: [PATCH 10/14] Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant --- src/confluent_kafka/aio/_AIOConsumer.py | 83 ++++++++++++++++++++----- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/src/confluent_kafka/aio/_AIOConsumer.py b/src/confluent_kafka/aio/_AIOConsumer.py index a93251862..9c91617b9 100644 --- a/src/confluent_kafka/aio/_AIOConsumer.py +++ b/src/confluent_kafka/aio/_AIOConsumer.py @@ -45,6 +45,12 @@ class AIOConsumer: on_assign calling assign(), or on_commit calling commit()) is recognized as belonging to the same caller and is admitted immediately rather than waiting on itself. + + A call created inside a callback but not awaited there (e.g. via an + un-awaited asyncio.create_task()) may outlive the callback invocation + it was created in. Such a call is not re-entrant: it runs as a new + top-level call, waiting for the operation that fired the callback to + finish rather than being admitted alongside it. """ def __init__( @@ -84,26 +90,73 @@ async def _call(self, blocking_task: Callable[..., Any], *args: Any, **kwargs: A if self._closed: raise RuntimeError("Consumer closed") - # Resolved here, on the event-loop thread, so a re-entrant call reuses - # the enclosing call's identity -- see _common.ReentryContext. - identity = _common.ReentryContext.get_or_generate_id() - - # Using the lock, the call gets serialized against any sibling in - # the same callback invocation dispatched concurrently. - # For any calls from outside a callback, this value stays None. - lock = _common.ReentryContext.current_lock() + # Set when this call was made from within a callback invocation + # (e.g. on_assign), inherited via context propagation -- including + # into tasks created inside the callback. See _common.Invocation. + invocation = _common.ReentryContext.current_invocation() + + if invocation is not None: + # Sibling calls dispatched concurrently from the same callback + # invocation serialize on its lock, so only one presents the + # shared identity to the gate at a time. + async with invocation.lock: + if invocation.alive: + return await self._reentrant_call(invocation, blocking_task, *args, **kwargs) + # The callback has already returned (e.g. an un-awaited + # create_task() that outlived it): its identity is stale, and + # presenting it could run this call concurrently with the still + # in-flight call that fired the callback. Fall through and run + # as a fresh top-level call instead, outside the lock, which + # only exists to serialize the invocation's own calls. + + # Resolved here, on the event-loop thread, and presented from inside + # wrapped_task so it is visible to the call it guards, including any + # re-entrant callback (e.g. on_assign) that blocking_task triggers + # synchronously before returning. + identity = _common.ReentryContext.generate_id() - # Presented from inside wrapped_task so it is visible to the call it - # guards, including any re-entrant callback (e.g. on_assign) that - # blocking_task triggers synchronously before returning. def wrapped_task(*task_args: Any, **task_kwargs: Any) -> Any: with _common.ReentryContext.active(identity): return blocking_task(*task_args, **task_kwargs) - if lock is None: - return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) - async with lock: - return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) + return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) + + async def _reentrant_call( + self, invocation: _common.Invocation, blocking_task: Callable[..., Any], *args: Any, **kwargs: Any + ) -> Any: + """Dispatch a call made from within a live callback invocation, + presenting the enclosing call's identity so the gate admits it. + + The invocation must stay open until this dispatch has fully left + the gate, even if the task awaiting it is cancelled (e.g. by + asyncio.wait_for()): a worker thread cannot be interrupted, so the + blocking call keeps running after the await below is abandoned. + The done callback on the executor future -- which fires only once + wrapped_task has actually returned, or the submission was cancelled + before ever starting -- is therefore what balances the in-flight + count, never this coroutine's own await. + + Called with invocation.lock held. + """ + loop = asyncio.get_running_loop() + + def wrapped_task() -> Any: + with _common.ReentryContext.active(invocation.identity): + return blocking_task(*args, **kwargs) + + invocation.dispatch_started() + future = self.executor.submit(wrapped_task) + + def on_done(_: concurrent.futures.Future) -> None: + try: + loop.call_soon_threadsafe(invocation.dispatch_finished) + except RuntimeError: + # Event loop already closed (interpreter shutdown); nothing + # is waiting on the drain anymore. + pass + + future.add_done_callback(on_done) + return await asyncio.wrap_future(future) def _wrap_callback( self, From 42b40cce3e9de6248717c589bfa8e7daaede7c2b Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Thu, 27 Aug 2026 23:50:29 +0530 Subject: [PATCH 11/14] Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant --- src/confluent_kafka/aio/_common.py | 135 +++++-- ...t_aio_consumer_concurrent_serialization.py | 160 +++++++- tests/test_AIOConsumer.py | 350 ++++++++++++++---- 3 files changed, 542 insertions(+), 103 deletions(-) diff --git a/src/confluent_kafka/aio/_common.py b/src/confluent_kafka/aio/_common.py index 34572ffc7..0b726b3d6 100644 --- a/src/confluent_kafka/aio/_common.py +++ b/src/confluent_kafka/aio/_common.py @@ -26,10 +26,77 @@ T = TypeVar('T') +class Invocation: + """Internal use only. State for one callback invocation (e.g. one + on_assign firing): the identity it presents to the Consumer gate, the + lock serializing sibling calls dispatched from within it, whether the + callback has returned yet, and how many dispatches carrying its + identity are still in flight on executor workers. + + The record is shared by reference into every context copied from the + callback's context (the tasks gather()/create_task() create), so + closing it here is visible to all of them -- including a task that + outlives the callback and only runs later (see AIOConsumer._call()). + """ + + __slots__ = ('identity', 'lock', '_alive', '_inflight', '_idle') + + def __init__(self, identity: int) -> None: + self.identity = identity + self.lock = asyncio.Lock() + self._alive = True + self._inflight = 0 + self._idle = asyncio.Event() + self._idle.set() + + @property + def alive(self) -> bool: + """Whether the callback invocation is still open. Only a call made + while it is open may present its identity to the gate: that is + exactly when the gated call that fired the callback is guaranteed + to be parked, waiting for the callback to return.""" + return self._alive + + def dispatch_started(self) -> None: + """Record one gated dispatch carrying this invocation's identity. + Event-loop thread only, under self.lock, while alive.""" + self._inflight += 1 + self._idle.clear() + + def dispatch_finished(self) -> None: + """Counterpart to dispatch_started(), called once the dispatch has + fully left the gate (or was cancelled before it ever started). + Event-loop thread only -- marshal via call_soon_threadsafe from + other threads.""" + self._inflight -= 1 + if self._inflight == 0: + self._idle.set() + + async def close(self) -> None: + """Close the invocation and wait until no dispatch carrying its + identity is still inside the gate. + + The gated call that fired the callback resumes as soon as this + returns, so it must not return while a same-identity dispatch could + still be executing -- even if the surrounding task is cancelled. + Cancellation is therefore re-raised only after the drain completes. + """ + self._alive = False + cancelled = False + while self._inflight: + try: + await self._idle.wait() + except asyncio.CancelledError: + cancelled = True + if cancelled: + raise asyncio.CancelledError + + class ReentryContext: """Internal use only. Per-call-chain context AIOConsumer carries through - a ContextVar: the identity presented to the Consumer reentrancy gate, and - the lock serializing concurrent dispatches within one callback invocation. + ContextVars: the identity presented to the Consumer reentrancy gate, and + the Invocation record of the callback invocation the call chain belongs + to, if any. The sync Consumer uses the calling thread's ID as its gate identity, but that does not work for AIOConsumer: a call and the re-entrant calls its @@ -37,15 +104,17 @@ class ReentryContext: a rebalance callback dispatched to one worker, then a re-entrant call from within it scheduled on another). AIOConsumer therefore generates an identity per top-level call and carries it in a ContextVar the gate reads - -- see Handle_gate_enter() in Consumer.c. + -- see Handle_serialize_enter() in confluent_kafka.c. """ # The ContextVar the C gate itself reads, defined in confluent_kafka.c. _id_var = cimpl._reentry_identity_var - # Serializes concurrent/un-awaited calls dispatched from within the same - # callback invocation. Not used by C gate and only used by AIO Consumer. - _lock_var: contextvars.ContextVar = contextvars.ContextVar('reentry_lock_var', default=None) + # The Invocation of the callback invocation the current context belongs + # to, or None outside any callback. Not read by the C gate; used by + # AIOConsumer._call() to decide whether the inherited identity may still + # be presented. + _invocation_var: contextvars.ContextVar = contextvars.ContextVar('reentry_invocation_var', default=None) # Process-wide counter generating identities. _ctr = itertools.count(1) @@ -55,16 +124,12 @@ class ReentryContext: _MASK = 0xFFFFFFFF @classmethod - def get_or_generate_id(cls) -> int: - """Return the identity for an AIOConsumer call: the current context's - identity for a re-entrant call, or a fresh one for a top-level call. + def generate_id(cls) -> int: + """Return a fresh identity for a top-level AIOConsumer call. Must be called on the event-loop thread, before dispatching to the executor. """ - identity = cls.current_id() - if identity: - return identity return (next(cls._ctr) & cls._MASK) or 1 @classmethod @@ -77,19 +142,19 @@ def current_id(cls) -> int: return cls._id_var.get() @classmethod - def current_lock(cls) -> Optional[asyncio.Lock]: - """Return the lock serializing calls dispatched concurrently from - the current callback invocation, or None for a top-level call. + def current_invocation(cls) -> Optional[Invocation]: + """Return the Invocation of the callback invocation the current + context belongs to, or None for a top-level call. Called on the event-loop thread, before dispatching to the executor. """ - return cls._lock_var.get() + return cls._invocation_var.get() @classmethod @contextlib.contextmanager - def active(cls, identity: int, lock: Optional[asyncio.Lock] = None) -> Iterator[None]: - """Present `identity` (and, for a callback invocation, `lock`) to - the gate for the duration of the block. + def active(cls, identity: int, invocation: Optional[Invocation] = None) -> Iterator[None]: + """Present `identity` (and, for a callback invocation, its + Invocation record) for the duration of the block. The identity is set here, inside the worker thread (or callback task) that makes the call, rather than before dispatching to the executor: @@ -98,12 +163,12 @@ def active(cls, identity: int, lock: Optional[asyncio.Lock] = None) -> Iterator[ thread would be invisible to later calls reusing the same worker. """ active_id = cls._id_var.set(identity) - active_lock = cls._lock_var.set(lock) + active_invocation = cls._invocation_var.set(invocation) try: yield finally: cls._id_var.reset(active_id) - cls._lock_var.reset(active_lock) + cls._invocation_var.reset(active_invocation) class AsyncLogger: @@ -133,15 +198,25 @@ def ret(*args: Any, **kwargs: Any) -> Any: # trampoline fired -- see AIOConsumer._call(). identity = ReentryContext.current_id() - async def _run_with_identity() -> Any: - # A fresh lock per invocation. Concurrent calls from the - # callback inherit the ID and lock via context propagation - # to the tasks asyncio creates for them, so only one is ever - # dispatched to the gate at a time. - with ReentryContext.active(identity, asyncio.Lock()): - return await callback(*args, **kwargs) - - f = asyncio.run_coroutine_threadsafe(_run_with_identity(), loop) + async def _run_with_invocation() -> Any: + # A fresh Invocation per callback invocation. Calls made from + # the callback inherit it (and the identity) via context + # propagation to the tasks asyncio creates for them; its lock + # ensures only one is ever dispatched to the gate at a time. + invocation = Invocation(identity) + with ReentryContext.active(identity, invocation): + try: + return await callback(*args, **kwargs) + finally: + # Close before returning: once this coroutine finishes, + # the gated call that fired the callback resumes, and + # it must not run concurrently with a dispatch still + # carrying this invocation's identity. Calls that run + # after this point present a fresh identity instead -- + # see AIOConsumer._call(). + await invocation.close() + + f = asyncio.run_coroutine_threadsafe(_run_with_invocation(), loop) return f.result() return ret diff --git a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py index 2560107a4..9ff515459 100644 --- a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py +++ b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py @@ -20,10 +20,13 @@ Out of multiple independent calls racing on the same underlying Consumer Handle, a colliding call waits for the current holder to release the gate, then proceeds -- it is not rejected. Only a genuinely re-entrant call (same -identity) is admitted immediately. Also covers same-identity concurrency: -concurrent or un-awaited calls a callback dispatches back into the Consumer -(gather(), or an un-awaited create_task()) all present the same identity, -so the gate alone can't tell them apart from a single sequential re-entrant call. +identity) is admitted immediately. Also covers callback-spawned concurrency: +concurrent calls a callback dispatches back into the Consumer while it is +still running (gather(), create_task() joined before returning) inherit the +enclosing call's identity and are serialized by the per-invocation lock, +while a call that escapes its callback invocation (an un-awaited +create_task() that outlives the callback) runs as a fresh top-level call, +waiting for the enclosing operation to release the gate. """ import asyncio @@ -293,9 +296,10 @@ async def on_assign(consumer, partitions): async def test_detached_create_task_from_callback_still_serializes_afterward(kafka_cluster): """on_assign fires a consume() call via create_task() and returns - WITHOUT ever awaiting it. This lets the top-level poll() that invoked - on_assign fully return and release the gate while the detached call may - still be in flight (dispatched with on_assign's identity, on its own executor worker).""" + WITHOUT ever awaiting it. The detached call outlives its callback + invocation, so it runs as a fresh top-level call (own identity, own + executor worker) once the poll() that invoked on_assign releases the + gate -- and a subsequent unrelated call must serialize behind it.""" topic = kafka_cluster.create_topic_and_wait_propogation( "test_detached_task_reentrant_serialize", conf={'num_partitions': 4} ) @@ -331,6 +335,148 @@ async def on_assign(consumer, partitions): await consumer.close() +async def test_fire_and_forget_task_waits_for_enclosing_poll(kafka_cluster): + """on_assign detaches a FAST call (assignment()) via create_task() and + returns without awaiting it. The task outlives its callback invocation, + so it must not be admitted alongside the enclosing poll() that fired the + callback. It must stay pending until poll() returns and releases the gate, + then complete as a fresh top-level call.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_fire_and_forget_waits_for_poll") + + consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) + + assign_fired = asyncio.Event() + detached_tasks = [] + + async def on_assign(consumer, partitions): + await consumer.incremental_assign(partitions) + detached_tasks.append(asyncio.create_task(consumer.assignment())) + assign_fired.set() + + await consumer.subscribe([topic], on_assign=on_assign) + + # Nothing is seeded yet, so poll() keeps holding the gate for its full + # timeout after the rebalance fires inside it. + poll_task = asyncio.create_task(consumer.poll(10)) + await asyncio.wait_for(assign_fired.wait(), 30) + + # assignment() is a local, broker-free call: if the detached task were + # (wrongly) admitted while poll() still holds the gate, it would finish + # within milliseconds. Give it ample time to prove it is really waiting. + await asyncio.sleep(1.0) + assert not detached_tasks[0].done(), ( + "the detached call completed while the enclosing poll() still held the " + "gate -- an escaped call must wait for the gate, not run alongside its " + "enclosing operation" + ) + + # Unblock poll() early instead of waiting out its full timeout. + kafka_cluster.seed_topic(topic, value_source=[b'hello']) + msg = await poll_task + assert msg is not None and msg.value() == b'hello' + + result = await asyncio.wait_for(detached_tasks[0], 10) + assert result, "the detached assignment() call must succeed once the gate frees up" + + await consumer.close() + + +async def test_fire_and_forget_subscribe_from_on_assign(kafka_cluster): + """on_assign fires subscribe() via create_task() and returns without + awaiting it. The resubscribe must wait for the enclosing poll() rather + than racing it inside the gate, complete cleanly, and leave the consumer + fully usable through the rebalance the resubscribe itself triggers.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_fire_and_forget_subscribe") + kafka_cluster.seed_topic(topic, value_source=[b'hello']) + + consumer = await _new_aio_consumer(kafka_cluster) + + resubscribe_tasks = [] + + async def on_assign(consumer, partitions): + if not resubscribe_tasks: + resubscribe_tasks.append(asyncio.create_task(consumer.subscribe([topic]))) + + await consumer.subscribe([topic], on_assign=on_assign) + + msg = await consumer.poll(10) + assert msg is not None and msg.value() == b'hello' + assert resubscribe_tasks, "on_assign was never invoked" + + await asyncio.wait_for(resubscribe_tasks[0], 10) + + # The resubscribe triggers a group rejoin; with no committed offsets the + # consumer restarts from earliest, so drain until the newly seeded + # message arrives to prove the consumer survived the whole sequence. + kafka_cluster.seed_topic(topic, value_source=[b'world']) + seen = [] + for _ in range(100): + msg = await consumer.poll(0.2) + if msg is not None: + seen.append(msg.value()) + if b'world' in seen: + break + + assert b'world' in seen, f"consumer never delivered the post-resubscribe message, saw: {seen}" + + await consumer.close() + + +async def test_cancelled_reentrant_call_drains_before_callback_returns(kafka_cluster): + """asyncio.wait_for() cancels a re-entrant consume() shortly after it + starts, but the executor worker running it cannot be interrupted: the + consume keeps blocking until its own timeout. The callback invocation + must stay open -- keeping the enclosing poll() parked inside the + rebalance callback -- until that worker actually exits, so the two + never run inside the gate concurrently.""" + topic = kafka_cluster.create_topic_and_wait_propogation("test_cancelled_reentrant_drains") + + consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) + + timings = {} + + async def on_assign(consumer, partitions): + await consumer.incremental_assign(partitions) + if 'cancelled_at' not in timings: + try: + # Nothing is seeded, so the worker blocks for the full 1.5s; + # wait_for() abandons the await at ~0.2s. + await asyncio.wait_for(consumer.consume(num_messages=1, timeout=1.5), timeout=0.2) + except asyncio.TimeoutError: + timings['cancelled_at'] = time.time() + + await consumer.subscribe([topic], on_assign=on_assign) + + for _ in range(60): + await consumer.poll(0.5) + if 'cancelled_at' in timings: + break + assert 'cancelled_at' in timings, "on_assign's wait_for() never timed out" + + # The poll() that fired on_assign could only return once the abandoned + # consume()'s worker exited (~1.3s after the cancellation), because the + # callback invocation drains in-flight dispatches before closing. If the + # cancellation had been allowed to reopen the gate immediately, poll() + # would have resumed within its own 0.5s timeout instead. + resumed_after = time.time() - timings['cancelled_at'] + assert resumed_after >= 1.0, ( + f"the enclosing poll() resumed {resumed_after:.2f}s after the re-entrant " + f"consume() was cancelled -- too fast: the cancelled dispatch was still " + f"running inside the gate for ~1.3s more" + ) + + # The consumer must remain fully usable afterward. + kafka_cluster.seed_topic(topic, value_source=[b'hello']) + msg = None + for _ in range(100): + msg = await consumer.poll(0.2) + if msg is not None: + break + assert msg is not None and msg.value() == b'hello' + + await consumer.close() + + async def test_reentrant_gather_one_call_fails_lock_still_releases(kafka_cluster): """on_commit fires two concurrent reentrant commit() calls via gather(): one deliberately invalid and one valid. The invalid call's failure must diff --git a/tests/test_AIOConsumer.py b/tests/test_AIOConsumer.py index 207427f3b..20322a6e7 100644 --- a/tests/test_AIOConsumer.py +++ b/tests/test_AIOConsumer.py @@ -32,6 +32,9 @@ async def mock_async_call(executor, blocking_task, *args, **kwargs): return blocking_task(*args, **kwargs) mock.async_call.side_effect = mock_async_call + # Outside a callback invocation there is no Invocation record; + # _call() must take the fresh top-level path. + mock.ReentryContext.current_invocation.return_value = None yield mock @pytest.fixture @@ -67,7 +70,7 @@ async def test_call_method_executor_usage(self, mock_consumer, mock_common, basi """Test that _call method properly uses ThreadPoolExecutor for async-to-sync bridging, setting the identity presented to the Consumer gate on the reentry ContextVar before invoking it.""" - mock_common.ReentryContext.get_or_generate_id.return_value = 42 + mock_common.ReentryContext.generate_id.return_value = 42 consumer = AIOConsumer(basic_config) mock_method = Mock(return_value="test_result") @@ -259,15 +262,15 @@ async def test_identity_does_not_leak_into_recycled_worker_thread(self, mock_con executor.shutdown(wait=True) @pytest.mark.asyncio - async def test_call_acquires_and_releases_context_bound_lock(self, mock_consumer, basic_config): - """_call() must acquire the lock bound in the current context (as - wrap_callback binds one per callback invocation) around the - executor dispatch, and release it once the dispatch completes.""" + async def test_call_acquires_and_releases_invocation_lock(self, mock_consumer, basic_config): + """_call() must hold the current invocation's lock (as wrap_callback + binds one Invocation per callback invocation) around the executor + dispatch, and release it once the dispatch completes.""" consumer = AIOConsumer(basic_config, max_workers=2) - assert _common.ReentryContext.current_lock() is None + assert _common.ReentryContext.current_invocation() is None assert await consumer._call(lambda: "ok") == "ok" - lock = asyncio.Lock() + invocation = _common.Invocation(_common.ReentryContext.generate_id()) entered = threading.Event() release = threading.Event() @@ -276,29 +279,28 @@ def blocking_task(): release.wait(timeout=5) return "done" - async def call_under_lock(): - with _common.ReentryContext.active(_common.ReentryContext.get_or_generate_id(), lock): + async def call_under_invocation(): + with _common.ReentryContext.active(invocation.identity, invocation): return await consumer._call(blocking_task) - task = asyncio.create_task(call_under_lock()) + task = asyncio.create_task(call_under_invocation()) await asyncio.get_event_loop().run_in_executor(None, entered.wait, 5) - assert lock.locked(), "the context-bound lock must be held while the dispatch is in flight" + assert invocation.lock.locked(), "the invocation's lock must be held while the dispatch is in flight" release.set() result = await task assert result == "done" - assert not lock.locked(), "the lock must be released once the dispatch completes" + assert not invocation.lock.locked(), "the lock must be released once the dispatch completes" @pytest.mark.asyncio - async def test_concurrent_reentrant_calls_sharing_lock_serialize(self, mock_consumer, basic_config): - """Two reentrant calls sharing the same callback-bound lock -- as - gather()/create_task() from within a callback produce, since both + async def test_concurrent_reentrant_calls_sharing_invocation_serialize(self, mock_consumer, basic_config): + """Two reentrant calls belonging to the same callback invocation -- + as gather()/create_task() from within a callback produce, since both inherit the same context -- must never run their blocking_task - concurrently..""" + concurrently.""" consumer = AIOConsumer(basic_config, max_workers=3) - lock = asyncio.Lock() - identity = _common.ReentryContext.get_or_generate_id() + invocation = _common.Invocation(_common.ReentryContext.generate_id()) active_count = 0 max_active = 0 @@ -317,7 +319,7 @@ def blocking_task(): async def reentrant_call(): return await consumer._call(blocking_task) - with _common.ReentryContext.active(identity, lock): + with _common.ReentryContext.active(invocation.identity, invocation): results = await asyncio.gather(reentrant_call(), reentrant_call()) assert results == ["ok", "ok"] @@ -326,51 +328,267 @@ async def reentrant_call(): ), f"blocking_task ran concurrently (max_active={max_active}) -- the lock failed to serialize" @pytest.mark.asyncio - async def test_wrap_callback_binds_a_fresh_lock_per_invocation(self, mock_consumer, basic_config): - """wrap_callback's trampoline must bind a fresh asyncio.Lock per - invocation, visible to the wrapped callback via current_lock(). - Two separate invocations (e.g. two separate rebalances) must not share - a lock with each other.""" + async def test_wrap_callback_binds_a_fresh_invocation_per_invocation(self, mock_consumer, basic_config): + """wrap_callback's trampoline must bind a fresh Invocation per + callback invocation, visible to the wrapped callback via + current_invocation(). Two separate invocations (e.g. two separate + rebalances) must not share one, and each must be closed once its + callback has returned.""" consumer = AIOConsumer(basic_config, max_workers=2) loop = asyncio.get_event_loop() - seen_locks = [] + seen = [] async def callback(*args, **kwargs): - seen_locks.append(_common.ReentryContext.current_lock()) + invocation = _common.ReentryContext.current_invocation() + seen.append(invocation) + assert invocation.alive, "the invocation must be open while its callback is running" wrapped = consumer._wrap_callback(loop, callback) await loop.run_in_executor(None, wrapped) await loop.run_in_executor(None, wrapped) - assert len(seen_locks) == 2 - assert all(isinstance(lock, asyncio.Lock) for lock in seen_locks) - assert seen_locks[0] is not seen_locks[1], "each callback invocation must get its own fresh lock" + assert len(seen) == 2 + assert all(isinstance(invocation, _common.Invocation) for invocation in seen) + assert seen[0] is not seen[1], "each callback invocation must get its own fresh Invocation" + assert all( + not invocation.alive for invocation in seen + ), "invocations must be closed once their callback has returned" + + # The tests below cover calls that escape their callback invocation + # (un-awaited create_task) and cancellation of re-entrant calls. + + @pytest.mark.asyncio + async def test_escaped_task_gets_fresh_identity_after_callback_returns(self, mock_consumer, basic_config): + """A call created inside a callback with create_task() but not + awaited there outlives the callback invocation. When it eventually + runs it must present a fresh identity, not the enclosing call's -- + presenting the inherited one would admit it into the gate alongside + the still-running enclosing call.""" + consumer = AIOConsumer(basic_config, max_workers=4) + seen = {} + escaped = [] + + async def on_assign(c, partitions): + seen['callback'] = cimpl._reentry_identity_var.get() + escaped.append( + asyncio.create_task( + consumer._call(lambda: seen.setdefault('escaped', cimpl._reentry_identity_var.get())) + ) + ) + # Returns without awaiting the task: it runs only after this + # callback invocation has been closed. + + loop = asyncio.get_event_loop() + wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) + + def outer_blocking_task(): + seen['outer'] = cimpl._reentry_identity_var.get() + # Simulate librdkafka invoking the rebalance callback + # synchronously from inside the blocking call. + wrapped(None, []) + + await consumer._call(outer_blocking_task) + await escaped[0] + + assert seen['callback'] == seen['outer'] != 0 + assert seen['escaped'] != 0 + assert ( + seen['escaped'] != seen['outer'] + ), "an escaped call must not present the identity of a callback invocation that already ended" + + @pytest.mark.asyncio + async def test_task_awaited_inside_callback_inherits_identity(self, mock_consumer, basic_config): + """A create_task() call awaited within the callback runs while the + invocation is still open, so it must inherit the enclosing identity + -- a fresh one would deadlock: the enclosing call holds the gate + until the callback returns.""" + consumer = AIOConsumer(basic_config, max_workers=4) + seen = {} + + async def on_assign(c, partitions): + seen['callback'] = cimpl._reentry_identity_var.get() + task = asyncio.create_task( + consumer._call(lambda: seen.setdefault('awaited', cimpl._reentry_identity_var.get())) + ) + await task + + loop = asyncio.get_event_loop() + wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) + + def outer_blocking_task(): + seen['outer'] = cimpl._reentry_identity_var.get() + wrapped(None, []) + + await consumer._call(outer_blocking_task) + + assert seen['callback'] == seen['outer'] != 0 + assert ( + seen['awaited'] == seen['outer'] + ), "a task awaited inside the callback must reuse the enclosing call's identity" + + @pytest.mark.asyncio + async def test_cancelled_reentrant_call_holds_callback_open_until_worker_exits(self, mock_consumer, basic_config): + """asyncio.wait_for() cancels the awaiting task on timeout, but an + executor worker cannot be interrupted: the blocking call keeps + running. The callback invocation must stay open -- keeping the + enclosing gated call parked -- until that worker actually finishes, + otherwise the two would run inside the gate concurrently.""" + consumer = AIOConsumer(basic_config, max_workers=4) + slow_started = threading.Event() + release_slow = threading.Event() + order = [] + + def slow_blocking(): + slow_started.set() + release_slow.wait(timeout=5) + order.append('worker_exited') + + async def on_assign(c, partitions): + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(consumer._call(slow_blocking), timeout=0.05) + order.append('callback_body_done') + + loop = asyncio.get_event_loop() + wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) + + def outer_blocking_task(): + wrapped(None, []) + order.append('enclosing_call_resumed') + + outer = asyncio.create_task(consumer._call(outer_blocking_task)) + + await loop.run_in_executor(None, slow_started.wait, 5) + # Let wait_for() time out and the callback body finish; the + # trampoline must still be parked, draining the cancelled-but-still- + # running dispatch. + while 'callback_body_done' not in order: + await asyncio.sleep(0.01) + await asyncio.sleep(0.05) + assert not outer.done(), "the enclosing call resumed while the cancelled dispatch was still running" + assert 'enclosing_call_resumed' not in order + + release_slow.set() + await outer + + assert order.index('worker_exited') < order.index('enclosing_call_resumed'), order + + @pytest.mark.asyncio + async def test_reentrant_dispatch_cancelled_before_start_unwinds_inflight(self, mock_consumer, basic_config): + """A dispatch cancelled while still queued behind a busy worker + never runs, so its in-flight accounting must be unwound by the + executor future's done callback -- otherwise Invocation.close() + would wait forever for a dispatch that will never finish.""" + executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + try: + consumer = AIOConsumer(basic_config, executor=executor) + release_worker = threading.Event() + worker_busy = threading.Event() + + def occupy_worker(): + worker_busy.set() + release_worker.wait(timeout=5) + + executor.submit(occupy_worker) + await asyncio.get_event_loop().run_in_executor(None, worker_busy.wait, 5) + + invocation = _common.Invocation(_common.ReentryContext.generate_id()) + ran = threading.Event() + + async def reentrant_call(): + with _common.ReentryContext.active(invocation.identity, invocation): + return await consumer._call(ran.set) + + task = asyncio.create_task(reentrant_call()) + # Once the lock is observed held, the task has already submitted + # its dispatch (everything up to its await is one synchronous + # step on the event loop). + while not invocation.lock.locked(): + await asyncio.sleep(0.01) + + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + # close() must return promptly: the queued dispatch was + # cancelled before it ever started. + await asyncio.wait_for(invocation.close(), timeout=5) + assert not ran.is_set(), "the cancelled-before-start dispatch must never run" + finally: + release_worker.set() + executor.shutdown(wait=True) + + +class TestInvocation: + """Unit tests for confluent_kafka.aio._common.Invocation: the record of + one callback invocation and the drain that keeps the enclosing gated + call parked until every dispatch carrying its identity has finished.""" + + @pytest.mark.asyncio + async def test_close_marks_dead_and_returns_immediately_when_idle(self): + invocation = _common.Invocation(7) + assert invocation.alive + await asyncio.wait_for(invocation.close(), timeout=1) + assert not invocation.alive + + @pytest.mark.asyncio + async def test_close_waits_for_all_inflight_dispatches(self): + invocation = _common.Invocation(7) + invocation.dispatch_started() + invocation.dispatch_started() + + closer = asyncio.create_task(invocation.close()) + await asyncio.sleep(0.05) + assert not closer.done(), "close() must wait for in-flight dispatches" + assert not invocation.alive, "close() must mark the invocation dead before draining" + + invocation.dispatch_finished() + await asyncio.sleep(0.05) + assert not closer.done(), "close() must wait for ALL in-flight dispatches" + + invocation.dispatch_finished() + await asyncio.wait_for(closer, timeout=1) + + @pytest.mark.asyncio + async def test_close_survives_cancellation_and_reraises_after_drain(self): + """The gated call that fired the callback resumes when close() + returns, so close() must keep draining even when its task is + cancelled, and only re-raise the cancellation once the drain is + complete.""" + invocation = _common.Invocation(7) + invocation.dispatch_started() + + closer = asyncio.create_task(invocation.close()) + await asyncio.sleep(0) # let close() block on the drain + closer.cancel() + await asyncio.sleep(0.05) + assert not closer.done(), "cancellation must not abandon the drain" + + invocation.dispatch_finished() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(closer, timeout=1) class TestReentryContext: """Unit tests for confluent_kafka.aio._common.ReentryContext: the identity AIOConsumer presents to the Consumer gate.""" - def test_get_or_generate_id_returns_nonzero_and_distinct_identities(self): + def test_generate_id_returns_nonzero_and_distinct_identities(self): """Two independent (non-nested) top-level calls must each get their own fresh, nonzero identity -- 0 means "not set" to the gate.""" - a = _common.ReentryContext.get_or_generate_id() - b = _common.ReentryContext.get_or_generate_id() + a = _common.ReentryContext.generate_id() + b = _common.ReentryContext.generate_id() assert a != 0 and b != 0 assert a != b - def test_active_sets_current_id_reuses_for_get_or_generate_id_then_resets_on_exit(self): - """active() must, for the duration of its block: (1) make the - identity visible via current_id(), and (2) have get_or_generate_id() - reuse it rather than generating a fresh one -- this is what lets a - re-entrant call present the same identity through the gate. Once - the block exits, it must reset the ContextVar rather than just - setting it.""" + def test_active_sets_current_id_then_resets_on_exit(self): + """active() must make the identity visible via current_id() for the + duration of its block -- this is what a re-entrant callback + captures and presents through the gate. Once the block exits, it + must reset the ContextVar rather than just setting it.""" assert _common.ReentryContext.current_id() == 0 with _common.ReentryContext.active(4242): assert _common.ReentryContext.current_id() == 4242 - assert _common.ReentryContext.get_or_generate_id() == 4242 assert _common.ReentryContext.current_id() == 0 def test_active_nesting_restores_outer_identity(self): @@ -386,36 +604,36 @@ def test_generated_identity_stays_within_unsigned_long_mask(self, monkeypatch): by forcing the counter to the edge of that range and confirming it wraps instead of overflowing.""" monkeypatch.setattr(_common.ReentryContext, '_ctr', itertools.count(0xFFFFFFFE)) - seen = [_common.ReentryContext.get_or_generate_id() for _ in range(5)] + seen = [_common.ReentryContext.generate_id() for _ in range(5)] assert all(0 < i <= 0xFFFFFFFF for i in seen), seen # 0xFFFFFFFF + 1 wraps to 0, remapped to 1 (0 means unset); the next # draw masks to 1 too (0x100000001 & 0xFFFFFFFF == 1), so 1 appears # twice at the wrap before the sequence continues from 2. assert seen == [0xFFFFFFFE, 0xFFFFFFFF, 1, 1, 2], seen - def test_active_with_lock_binds_current_lock_then_resets_to_none(self): - lock = asyncio.Lock() - assert _common.ReentryContext.current_lock() is None - with _common.ReentryContext.active(1, lock): - assert _common.ReentryContext.current_lock() is lock - assert _common.ReentryContext.current_lock() is None - - def test_active_nesting_with_lock_restores_outer_lock(self): - outer_lock = asyncio.Lock() - inner_lock = asyncio.Lock() - with _common.ReentryContext.active(1, outer_lock): - with _common.ReentryContext.active(2, inner_lock): - assert _common.ReentryContext.current_lock() is inner_lock - assert _common.ReentryContext.current_lock() is outer_lock - assert _common.ReentryContext.current_lock() is None - - def test_active_without_lock_arg_clears_outer_lock_for_the_block(self): - """active() called without a lock argument does not preserve an - outer bound lock -- it explicitly clears it for the duration of - the block, then restores it on exit.""" - lock = asyncio.Lock() - with _common.ReentryContext.active(1, lock): - assert _common.ReentryContext.current_lock() is lock + def test_active_with_invocation_binds_current_invocation_then_resets_to_none(self): + invocation = _common.Invocation(1) + assert _common.ReentryContext.current_invocation() is None + with _common.ReentryContext.active(1, invocation): + assert _common.ReentryContext.current_invocation() is invocation + assert _common.ReentryContext.current_invocation() is None + + def test_active_nesting_with_invocation_restores_outer_invocation(self): + outer_invocation = _common.Invocation(1) + inner_invocation = _common.Invocation(2) + with _common.ReentryContext.active(1, outer_invocation): + with _common.ReentryContext.active(2, inner_invocation): + assert _common.ReentryContext.current_invocation() is inner_invocation + assert _common.ReentryContext.current_invocation() is outer_invocation + assert _common.ReentryContext.current_invocation() is None + + def test_active_without_invocation_arg_clears_outer_invocation_for_the_block(self): + """active() called without an invocation argument does not preserve + an outer bound Invocation -- it explicitly clears it for the + duration of the block, then restores it on exit.""" + invocation = _common.Invocation(1) + with _common.ReentryContext.active(1, invocation): + assert _common.ReentryContext.current_invocation() is invocation with _common.ReentryContext.active(2): - assert _common.ReentryContext.current_lock() is None - assert _common.ReentryContext.current_lock() is lock + assert _common.ReentryContext.current_invocation() is None + assert _common.ReentryContext.current_invocation() is invocation From 79fe726b5bc67d7d66bbee29eb0acf4cfa6bee30 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Fri, 28 Aug 2026 17:16:13 +0530 Subject: [PATCH 12/14] Revert "Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant" This reverts commit 42b40cce3e9de6248717c589bfa8e7daaede7c2b. --- src/confluent_kafka/aio/_common.py | 135 ++----- ...t_aio_consumer_concurrent_serialization.py | 160 +------- tests/test_AIOConsumer.py | 350 ++++-------------- 3 files changed, 103 insertions(+), 542 deletions(-) diff --git a/src/confluent_kafka/aio/_common.py b/src/confluent_kafka/aio/_common.py index 0b726b3d6..34572ffc7 100644 --- a/src/confluent_kafka/aio/_common.py +++ b/src/confluent_kafka/aio/_common.py @@ -26,77 +26,10 @@ T = TypeVar('T') -class Invocation: - """Internal use only. State for one callback invocation (e.g. one - on_assign firing): the identity it presents to the Consumer gate, the - lock serializing sibling calls dispatched from within it, whether the - callback has returned yet, and how many dispatches carrying its - identity are still in flight on executor workers. - - The record is shared by reference into every context copied from the - callback's context (the tasks gather()/create_task() create), so - closing it here is visible to all of them -- including a task that - outlives the callback and only runs later (see AIOConsumer._call()). - """ - - __slots__ = ('identity', 'lock', '_alive', '_inflight', '_idle') - - def __init__(self, identity: int) -> None: - self.identity = identity - self.lock = asyncio.Lock() - self._alive = True - self._inflight = 0 - self._idle = asyncio.Event() - self._idle.set() - - @property - def alive(self) -> bool: - """Whether the callback invocation is still open. Only a call made - while it is open may present its identity to the gate: that is - exactly when the gated call that fired the callback is guaranteed - to be parked, waiting for the callback to return.""" - return self._alive - - def dispatch_started(self) -> None: - """Record one gated dispatch carrying this invocation's identity. - Event-loop thread only, under self.lock, while alive.""" - self._inflight += 1 - self._idle.clear() - - def dispatch_finished(self) -> None: - """Counterpart to dispatch_started(), called once the dispatch has - fully left the gate (or was cancelled before it ever started). - Event-loop thread only -- marshal via call_soon_threadsafe from - other threads.""" - self._inflight -= 1 - if self._inflight == 0: - self._idle.set() - - async def close(self) -> None: - """Close the invocation and wait until no dispatch carrying its - identity is still inside the gate. - - The gated call that fired the callback resumes as soon as this - returns, so it must not return while a same-identity dispatch could - still be executing -- even if the surrounding task is cancelled. - Cancellation is therefore re-raised only after the drain completes. - """ - self._alive = False - cancelled = False - while self._inflight: - try: - await self._idle.wait() - except asyncio.CancelledError: - cancelled = True - if cancelled: - raise asyncio.CancelledError - - class ReentryContext: """Internal use only. Per-call-chain context AIOConsumer carries through - ContextVars: the identity presented to the Consumer reentrancy gate, and - the Invocation record of the callback invocation the call chain belongs - to, if any. + a ContextVar: the identity presented to the Consumer reentrancy gate, and + the lock serializing concurrent dispatches within one callback invocation. The sync Consumer uses the calling thread's ID as its gate identity, but that does not work for AIOConsumer: a call and the re-entrant calls its @@ -104,17 +37,15 @@ class ReentryContext: a rebalance callback dispatched to one worker, then a re-entrant call from within it scheduled on another). AIOConsumer therefore generates an identity per top-level call and carries it in a ContextVar the gate reads - -- see Handle_serialize_enter() in confluent_kafka.c. + -- see Handle_gate_enter() in Consumer.c. """ # The ContextVar the C gate itself reads, defined in confluent_kafka.c. _id_var = cimpl._reentry_identity_var - # The Invocation of the callback invocation the current context belongs - # to, or None outside any callback. Not read by the C gate; used by - # AIOConsumer._call() to decide whether the inherited identity may still - # be presented. - _invocation_var: contextvars.ContextVar = contextvars.ContextVar('reentry_invocation_var', default=None) + # Serializes concurrent/un-awaited calls dispatched from within the same + # callback invocation. Not used by C gate and only used by AIO Consumer. + _lock_var: contextvars.ContextVar = contextvars.ContextVar('reentry_lock_var', default=None) # Process-wide counter generating identities. _ctr = itertools.count(1) @@ -124,12 +55,16 @@ class ReentryContext: _MASK = 0xFFFFFFFF @classmethod - def generate_id(cls) -> int: - """Return a fresh identity for a top-level AIOConsumer call. + def get_or_generate_id(cls) -> int: + """Return the identity for an AIOConsumer call: the current context's + identity for a re-entrant call, or a fresh one for a top-level call. Must be called on the event-loop thread, before dispatching to the executor. """ + identity = cls.current_id() + if identity: + return identity return (next(cls._ctr) & cls._MASK) or 1 @classmethod @@ -142,19 +77,19 @@ def current_id(cls) -> int: return cls._id_var.get() @classmethod - def current_invocation(cls) -> Optional[Invocation]: - """Return the Invocation of the callback invocation the current - context belongs to, or None for a top-level call. + def current_lock(cls) -> Optional[asyncio.Lock]: + """Return the lock serializing calls dispatched concurrently from + the current callback invocation, or None for a top-level call. Called on the event-loop thread, before dispatching to the executor. """ - return cls._invocation_var.get() + return cls._lock_var.get() @classmethod @contextlib.contextmanager - def active(cls, identity: int, invocation: Optional[Invocation] = None) -> Iterator[None]: - """Present `identity` (and, for a callback invocation, its - Invocation record) for the duration of the block. + def active(cls, identity: int, lock: Optional[asyncio.Lock] = None) -> Iterator[None]: + """Present `identity` (and, for a callback invocation, `lock`) to + the gate for the duration of the block. The identity is set here, inside the worker thread (or callback task) that makes the call, rather than before dispatching to the executor: @@ -163,12 +98,12 @@ def active(cls, identity: int, invocation: Optional[Invocation] = None) -> Itera thread would be invisible to later calls reusing the same worker. """ active_id = cls._id_var.set(identity) - active_invocation = cls._invocation_var.set(invocation) + active_lock = cls._lock_var.set(lock) try: yield finally: cls._id_var.reset(active_id) - cls._invocation_var.reset(active_invocation) + cls._lock_var.reset(active_lock) class AsyncLogger: @@ -198,25 +133,15 @@ def ret(*args: Any, **kwargs: Any) -> Any: # trampoline fired -- see AIOConsumer._call(). identity = ReentryContext.current_id() - async def _run_with_invocation() -> Any: - # A fresh Invocation per callback invocation. Calls made from - # the callback inherit it (and the identity) via context - # propagation to the tasks asyncio creates for them; its lock - # ensures only one is ever dispatched to the gate at a time. - invocation = Invocation(identity) - with ReentryContext.active(identity, invocation): - try: - return await callback(*args, **kwargs) - finally: - # Close before returning: once this coroutine finishes, - # the gated call that fired the callback resumes, and - # it must not run concurrently with a dispatch still - # carrying this invocation's identity. Calls that run - # after this point present a fresh identity instead -- - # see AIOConsumer._call(). - await invocation.close() - - f = asyncio.run_coroutine_threadsafe(_run_with_invocation(), loop) + async def _run_with_identity() -> Any: + # A fresh lock per invocation. Concurrent calls from the + # callback inherit the ID and lock via context propagation + # to the tasks asyncio creates for them, so only one is ever + # dispatched to the gate at a time. + with ReentryContext.active(identity, asyncio.Lock()): + return await callback(*args, **kwargs) + + f = asyncio.run_coroutine_threadsafe(_run_with_identity(), loop) return f.result() return ret diff --git a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py index 9ff515459..2560107a4 100644 --- a/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py +++ b/tests/integration/consumer/test_aio_consumer_concurrent_serialization.py @@ -20,13 +20,10 @@ Out of multiple independent calls racing on the same underlying Consumer Handle, a colliding call waits for the current holder to release the gate, then proceeds -- it is not rejected. Only a genuinely re-entrant call (same -identity) is admitted immediately. Also covers callback-spawned concurrency: -concurrent calls a callback dispatches back into the Consumer while it is -still running (gather(), create_task() joined before returning) inherit the -enclosing call's identity and are serialized by the per-invocation lock, -while a call that escapes its callback invocation (an un-awaited -create_task() that outlives the callback) runs as a fresh top-level call, -waiting for the enclosing operation to release the gate. +identity) is admitted immediately. Also covers same-identity concurrency: +concurrent or un-awaited calls a callback dispatches back into the Consumer +(gather(), or an un-awaited create_task()) all present the same identity, +so the gate alone can't tell them apart from a single sequential re-entrant call. """ import asyncio @@ -296,10 +293,9 @@ async def on_assign(consumer, partitions): async def test_detached_create_task_from_callback_still_serializes_afterward(kafka_cluster): """on_assign fires a consume() call via create_task() and returns - WITHOUT ever awaiting it. The detached call outlives its callback - invocation, so it runs as a fresh top-level call (own identity, own - executor worker) once the poll() that invoked on_assign releases the - gate -- and a subsequent unrelated call must serialize behind it.""" + WITHOUT ever awaiting it. This lets the top-level poll() that invoked + on_assign fully return and release the gate while the detached call may + still be in flight (dispatched with on_assign's identity, on its own executor worker).""" topic = kafka_cluster.create_topic_and_wait_propogation( "test_detached_task_reentrant_serialize", conf={'num_partitions': 4} ) @@ -335,148 +331,6 @@ async def on_assign(consumer, partitions): await consumer.close() -async def test_fire_and_forget_task_waits_for_enclosing_poll(kafka_cluster): - """on_assign detaches a FAST call (assignment()) via create_task() and - returns without awaiting it. The task outlives its callback invocation, - so it must not be admitted alongside the enclosing poll() that fired the - callback. It must stay pending until poll() returns and releases the gate, - then complete as a fresh top-level call.""" - topic = kafka_cluster.create_topic_and_wait_propogation("test_fire_and_forget_waits_for_poll") - - consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) - - assign_fired = asyncio.Event() - detached_tasks = [] - - async def on_assign(consumer, partitions): - await consumer.incremental_assign(partitions) - detached_tasks.append(asyncio.create_task(consumer.assignment())) - assign_fired.set() - - await consumer.subscribe([topic], on_assign=on_assign) - - # Nothing is seeded yet, so poll() keeps holding the gate for its full - # timeout after the rebalance fires inside it. - poll_task = asyncio.create_task(consumer.poll(10)) - await asyncio.wait_for(assign_fired.wait(), 30) - - # assignment() is a local, broker-free call: if the detached task were - # (wrongly) admitted while poll() still holds the gate, it would finish - # within milliseconds. Give it ample time to prove it is really waiting. - await asyncio.sleep(1.0) - assert not detached_tasks[0].done(), ( - "the detached call completed while the enclosing poll() still held the " - "gate -- an escaped call must wait for the gate, not run alongside its " - "enclosing operation" - ) - - # Unblock poll() early instead of waiting out its full timeout. - kafka_cluster.seed_topic(topic, value_source=[b'hello']) - msg = await poll_task - assert msg is not None and msg.value() == b'hello' - - result = await asyncio.wait_for(detached_tasks[0], 10) - assert result, "the detached assignment() call must succeed once the gate frees up" - - await consumer.close() - - -async def test_fire_and_forget_subscribe_from_on_assign(kafka_cluster): - """on_assign fires subscribe() via create_task() and returns without - awaiting it. The resubscribe must wait for the enclosing poll() rather - than racing it inside the gate, complete cleanly, and leave the consumer - fully usable through the rebalance the resubscribe itself triggers.""" - topic = kafka_cluster.create_topic_and_wait_propogation("test_fire_and_forget_subscribe") - kafka_cluster.seed_topic(topic, value_source=[b'hello']) - - consumer = await _new_aio_consumer(kafka_cluster) - - resubscribe_tasks = [] - - async def on_assign(consumer, partitions): - if not resubscribe_tasks: - resubscribe_tasks.append(asyncio.create_task(consumer.subscribe([topic]))) - - await consumer.subscribe([topic], on_assign=on_assign) - - msg = await consumer.poll(10) - assert msg is not None and msg.value() == b'hello' - assert resubscribe_tasks, "on_assign was never invoked" - - await asyncio.wait_for(resubscribe_tasks[0], 10) - - # The resubscribe triggers a group rejoin; with no committed offsets the - # consumer restarts from earliest, so drain until the newly seeded - # message arrives to prove the consumer survived the whole sequence. - kafka_cluster.seed_topic(topic, value_source=[b'world']) - seen = [] - for _ in range(100): - msg = await consumer.poll(0.2) - if msg is not None: - seen.append(msg.value()) - if b'world' in seen: - break - - assert b'world' in seen, f"consumer never delivered the post-resubscribe message, saw: {seen}" - - await consumer.close() - - -async def test_cancelled_reentrant_call_drains_before_callback_returns(kafka_cluster): - """asyncio.wait_for() cancels a re-entrant consume() shortly after it - starts, but the executor worker running it cannot be interrupted: the - consume keeps blocking until its own timeout. The callback invocation - must stay open -- keeping the enclosing poll() parked inside the - rebalance callback -- until that worker actually exits, so the two - never run inside the gate concurrently.""" - topic = kafka_cluster.create_topic_and_wait_propogation("test_cancelled_reentrant_drains") - - consumer = await _new_aio_consumer(kafka_cluster, {'partition.assignment.strategy': 'cooperative-sticky'}) - - timings = {} - - async def on_assign(consumer, partitions): - await consumer.incremental_assign(partitions) - if 'cancelled_at' not in timings: - try: - # Nothing is seeded, so the worker blocks for the full 1.5s; - # wait_for() abandons the await at ~0.2s. - await asyncio.wait_for(consumer.consume(num_messages=1, timeout=1.5), timeout=0.2) - except asyncio.TimeoutError: - timings['cancelled_at'] = time.time() - - await consumer.subscribe([topic], on_assign=on_assign) - - for _ in range(60): - await consumer.poll(0.5) - if 'cancelled_at' in timings: - break - assert 'cancelled_at' in timings, "on_assign's wait_for() never timed out" - - # The poll() that fired on_assign could only return once the abandoned - # consume()'s worker exited (~1.3s after the cancellation), because the - # callback invocation drains in-flight dispatches before closing. If the - # cancellation had been allowed to reopen the gate immediately, poll() - # would have resumed within its own 0.5s timeout instead. - resumed_after = time.time() - timings['cancelled_at'] - assert resumed_after >= 1.0, ( - f"the enclosing poll() resumed {resumed_after:.2f}s after the re-entrant " - f"consume() was cancelled -- too fast: the cancelled dispatch was still " - f"running inside the gate for ~1.3s more" - ) - - # The consumer must remain fully usable afterward. - kafka_cluster.seed_topic(topic, value_source=[b'hello']) - msg = None - for _ in range(100): - msg = await consumer.poll(0.2) - if msg is not None: - break - assert msg is not None and msg.value() == b'hello' - - await consumer.close() - - async def test_reentrant_gather_one_call_fails_lock_still_releases(kafka_cluster): """on_commit fires two concurrent reentrant commit() calls via gather(): one deliberately invalid and one valid. The invalid call's failure must diff --git a/tests/test_AIOConsumer.py b/tests/test_AIOConsumer.py index 20322a6e7..207427f3b 100644 --- a/tests/test_AIOConsumer.py +++ b/tests/test_AIOConsumer.py @@ -32,9 +32,6 @@ async def mock_async_call(executor, blocking_task, *args, **kwargs): return blocking_task(*args, **kwargs) mock.async_call.side_effect = mock_async_call - # Outside a callback invocation there is no Invocation record; - # _call() must take the fresh top-level path. - mock.ReentryContext.current_invocation.return_value = None yield mock @pytest.fixture @@ -70,7 +67,7 @@ async def test_call_method_executor_usage(self, mock_consumer, mock_common, basi """Test that _call method properly uses ThreadPoolExecutor for async-to-sync bridging, setting the identity presented to the Consumer gate on the reentry ContextVar before invoking it.""" - mock_common.ReentryContext.generate_id.return_value = 42 + mock_common.ReentryContext.get_or_generate_id.return_value = 42 consumer = AIOConsumer(basic_config) mock_method = Mock(return_value="test_result") @@ -262,15 +259,15 @@ async def test_identity_does_not_leak_into_recycled_worker_thread(self, mock_con executor.shutdown(wait=True) @pytest.mark.asyncio - async def test_call_acquires_and_releases_invocation_lock(self, mock_consumer, basic_config): - """_call() must hold the current invocation's lock (as wrap_callback - binds one Invocation per callback invocation) around the executor - dispatch, and release it once the dispatch completes.""" + async def test_call_acquires_and_releases_context_bound_lock(self, mock_consumer, basic_config): + """_call() must acquire the lock bound in the current context (as + wrap_callback binds one per callback invocation) around the + executor dispatch, and release it once the dispatch completes.""" consumer = AIOConsumer(basic_config, max_workers=2) - assert _common.ReentryContext.current_invocation() is None + assert _common.ReentryContext.current_lock() is None assert await consumer._call(lambda: "ok") == "ok" - invocation = _common.Invocation(_common.ReentryContext.generate_id()) + lock = asyncio.Lock() entered = threading.Event() release = threading.Event() @@ -279,28 +276,29 @@ def blocking_task(): release.wait(timeout=5) return "done" - async def call_under_invocation(): - with _common.ReentryContext.active(invocation.identity, invocation): + async def call_under_lock(): + with _common.ReentryContext.active(_common.ReentryContext.get_or_generate_id(), lock): return await consumer._call(blocking_task) - task = asyncio.create_task(call_under_invocation()) + task = asyncio.create_task(call_under_lock()) await asyncio.get_event_loop().run_in_executor(None, entered.wait, 5) - assert invocation.lock.locked(), "the invocation's lock must be held while the dispatch is in flight" + assert lock.locked(), "the context-bound lock must be held while the dispatch is in flight" release.set() result = await task assert result == "done" - assert not invocation.lock.locked(), "the lock must be released once the dispatch completes" + assert not lock.locked(), "the lock must be released once the dispatch completes" @pytest.mark.asyncio - async def test_concurrent_reentrant_calls_sharing_invocation_serialize(self, mock_consumer, basic_config): - """Two reentrant calls belonging to the same callback invocation -- - as gather()/create_task() from within a callback produce, since both + async def test_concurrent_reentrant_calls_sharing_lock_serialize(self, mock_consumer, basic_config): + """Two reentrant calls sharing the same callback-bound lock -- as + gather()/create_task() from within a callback produce, since both inherit the same context -- must never run their blocking_task - concurrently.""" + concurrently..""" consumer = AIOConsumer(basic_config, max_workers=3) - invocation = _common.Invocation(_common.ReentryContext.generate_id()) + lock = asyncio.Lock() + identity = _common.ReentryContext.get_or_generate_id() active_count = 0 max_active = 0 @@ -319,7 +317,7 @@ def blocking_task(): async def reentrant_call(): return await consumer._call(blocking_task) - with _common.ReentryContext.active(invocation.identity, invocation): + with _common.ReentryContext.active(identity, lock): results = await asyncio.gather(reentrant_call(), reentrant_call()) assert results == ["ok", "ok"] @@ -328,267 +326,51 @@ async def reentrant_call(): ), f"blocking_task ran concurrently (max_active={max_active}) -- the lock failed to serialize" @pytest.mark.asyncio - async def test_wrap_callback_binds_a_fresh_invocation_per_invocation(self, mock_consumer, basic_config): - """wrap_callback's trampoline must bind a fresh Invocation per - callback invocation, visible to the wrapped callback via - current_invocation(). Two separate invocations (e.g. two separate - rebalances) must not share one, and each must be closed once its - callback has returned.""" + async def test_wrap_callback_binds_a_fresh_lock_per_invocation(self, mock_consumer, basic_config): + """wrap_callback's trampoline must bind a fresh asyncio.Lock per + invocation, visible to the wrapped callback via current_lock(). + Two separate invocations (e.g. two separate rebalances) must not share + a lock with each other.""" consumer = AIOConsumer(basic_config, max_workers=2) loop = asyncio.get_event_loop() - seen = [] + seen_locks = [] async def callback(*args, **kwargs): - invocation = _common.ReentryContext.current_invocation() - seen.append(invocation) - assert invocation.alive, "the invocation must be open while its callback is running" + seen_locks.append(_common.ReentryContext.current_lock()) wrapped = consumer._wrap_callback(loop, callback) await loop.run_in_executor(None, wrapped) await loop.run_in_executor(None, wrapped) - assert len(seen) == 2 - assert all(isinstance(invocation, _common.Invocation) for invocation in seen) - assert seen[0] is not seen[1], "each callback invocation must get its own fresh Invocation" - assert all( - not invocation.alive for invocation in seen - ), "invocations must be closed once their callback has returned" - - # The tests below cover calls that escape their callback invocation - # (un-awaited create_task) and cancellation of re-entrant calls. - - @pytest.mark.asyncio - async def test_escaped_task_gets_fresh_identity_after_callback_returns(self, mock_consumer, basic_config): - """A call created inside a callback with create_task() but not - awaited there outlives the callback invocation. When it eventually - runs it must present a fresh identity, not the enclosing call's -- - presenting the inherited one would admit it into the gate alongside - the still-running enclosing call.""" - consumer = AIOConsumer(basic_config, max_workers=4) - seen = {} - escaped = [] - - async def on_assign(c, partitions): - seen['callback'] = cimpl._reentry_identity_var.get() - escaped.append( - asyncio.create_task( - consumer._call(lambda: seen.setdefault('escaped', cimpl._reentry_identity_var.get())) - ) - ) - # Returns without awaiting the task: it runs only after this - # callback invocation has been closed. - - loop = asyncio.get_event_loop() - wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) - - def outer_blocking_task(): - seen['outer'] = cimpl._reentry_identity_var.get() - # Simulate librdkafka invoking the rebalance callback - # synchronously from inside the blocking call. - wrapped(None, []) - - await consumer._call(outer_blocking_task) - await escaped[0] - - assert seen['callback'] == seen['outer'] != 0 - assert seen['escaped'] != 0 - assert ( - seen['escaped'] != seen['outer'] - ), "an escaped call must not present the identity of a callback invocation that already ended" - - @pytest.mark.asyncio - async def test_task_awaited_inside_callback_inherits_identity(self, mock_consumer, basic_config): - """A create_task() call awaited within the callback runs while the - invocation is still open, so it must inherit the enclosing identity - -- a fresh one would deadlock: the enclosing call holds the gate - until the callback returns.""" - consumer = AIOConsumer(basic_config, max_workers=4) - seen = {} - - async def on_assign(c, partitions): - seen['callback'] = cimpl._reentry_identity_var.get() - task = asyncio.create_task( - consumer._call(lambda: seen.setdefault('awaited', cimpl._reentry_identity_var.get())) - ) - await task - - loop = asyncio.get_event_loop() - wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) - - def outer_blocking_task(): - seen['outer'] = cimpl._reentry_identity_var.get() - wrapped(None, []) - - await consumer._call(outer_blocking_task) - - assert seen['callback'] == seen['outer'] != 0 - assert ( - seen['awaited'] == seen['outer'] - ), "a task awaited inside the callback must reuse the enclosing call's identity" - - @pytest.mark.asyncio - async def test_cancelled_reentrant_call_holds_callback_open_until_worker_exits(self, mock_consumer, basic_config): - """asyncio.wait_for() cancels the awaiting task on timeout, but an - executor worker cannot be interrupted: the blocking call keeps - running. The callback invocation must stay open -- keeping the - enclosing gated call parked -- until that worker actually finishes, - otherwise the two would run inside the gate concurrently.""" - consumer = AIOConsumer(basic_config, max_workers=4) - slow_started = threading.Event() - release_slow = threading.Event() - order = [] - - def slow_blocking(): - slow_started.set() - release_slow.wait(timeout=5) - order.append('worker_exited') - - async def on_assign(c, partitions): - with pytest.raises(asyncio.TimeoutError): - await asyncio.wait_for(consumer._call(slow_blocking), timeout=0.05) - order.append('callback_body_done') - - loop = asyncio.get_event_loop() - wrapped = consumer._wrap_callback(loop, on_assign, consumer._edit_rebalance_callbacks_args) - - def outer_blocking_task(): - wrapped(None, []) - order.append('enclosing_call_resumed') - - outer = asyncio.create_task(consumer._call(outer_blocking_task)) - - await loop.run_in_executor(None, slow_started.wait, 5) - # Let wait_for() time out and the callback body finish; the - # trampoline must still be parked, draining the cancelled-but-still- - # running dispatch. - while 'callback_body_done' not in order: - await asyncio.sleep(0.01) - await asyncio.sleep(0.05) - assert not outer.done(), "the enclosing call resumed while the cancelled dispatch was still running" - assert 'enclosing_call_resumed' not in order - - release_slow.set() - await outer - - assert order.index('worker_exited') < order.index('enclosing_call_resumed'), order - - @pytest.mark.asyncio - async def test_reentrant_dispatch_cancelled_before_start_unwinds_inflight(self, mock_consumer, basic_config): - """A dispatch cancelled while still queued behind a busy worker - never runs, so its in-flight accounting must be unwound by the - executor future's done callback -- otherwise Invocation.close() - would wait forever for a dispatch that will never finish.""" - executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) - try: - consumer = AIOConsumer(basic_config, executor=executor) - release_worker = threading.Event() - worker_busy = threading.Event() - - def occupy_worker(): - worker_busy.set() - release_worker.wait(timeout=5) - - executor.submit(occupy_worker) - await asyncio.get_event_loop().run_in_executor(None, worker_busy.wait, 5) - - invocation = _common.Invocation(_common.ReentryContext.generate_id()) - ran = threading.Event() - - async def reentrant_call(): - with _common.ReentryContext.active(invocation.identity, invocation): - return await consumer._call(ran.set) - - task = asyncio.create_task(reentrant_call()) - # Once the lock is observed held, the task has already submitted - # its dispatch (everything up to its await is one synchronous - # step on the event loop). - while not invocation.lock.locked(): - await asyncio.sleep(0.01) - - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task - - # close() must return promptly: the queued dispatch was - # cancelled before it ever started. - await asyncio.wait_for(invocation.close(), timeout=5) - assert not ran.is_set(), "the cancelled-before-start dispatch must never run" - finally: - release_worker.set() - executor.shutdown(wait=True) - - -class TestInvocation: - """Unit tests for confluent_kafka.aio._common.Invocation: the record of - one callback invocation and the drain that keeps the enclosing gated - call parked until every dispatch carrying its identity has finished.""" - - @pytest.mark.asyncio - async def test_close_marks_dead_and_returns_immediately_when_idle(self): - invocation = _common.Invocation(7) - assert invocation.alive - await asyncio.wait_for(invocation.close(), timeout=1) - assert not invocation.alive - - @pytest.mark.asyncio - async def test_close_waits_for_all_inflight_dispatches(self): - invocation = _common.Invocation(7) - invocation.dispatch_started() - invocation.dispatch_started() - - closer = asyncio.create_task(invocation.close()) - await asyncio.sleep(0.05) - assert not closer.done(), "close() must wait for in-flight dispatches" - assert not invocation.alive, "close() must mark the invocation dead before draining" - - invocation.dispatch_finished() - await asyncio.sleep(0.05) - assert not closer.done(), "close() must wait for ALL in-flight dispatches" - - invocation.dispatch_finished() - await asyncio.wait_for(closer, timeout=1) - - @pytest.mark.asyncio - async def test_close_survives_cancellation_and_reraises_after_drain(self): - """The gated call that fired the callback resumes when close() - returns, so close() must keep draining even when its task is - cancelled, and only re-raise the cancellation once the drain is - complete.""" - invocation = _common.Invocation(7) - invocation.dispatch_started() - - closer = asyncio.create_task(invocation.close()) - await asyncio.sleep(0) # let close() block on the drain - closer.cancel() - await asyncio.sleep(0.05) - assert not closer.done(), "cancellation must not abandon the drain" - - invocation.dispatch_finished() - with pytest.raises(asyncio.CancelledError): - await asyncio.wait_for(closer, timeout=1) + assert len(seen_locks) == 2 + assert all(isinstance(lock, asyncio.Lock) for lock in seen_locks) + assert seen_locks[0] is not seen_locks[1], "each callback invocation must get its own fresh lock" class TestReentryContext: """Unit tests for confluent_kafka.aio._common.ReentryContext: the identity AIOConsumer presents to the Consumer gate.""" - def test_generate_id_returns_nonzero_and_distinct_identities(self): + def test_get_or_generate_id_returns_nonzero_and_distinct_identities(self): """Two independent (non-nested) top-level calls must each get their own fresh, nonzero identity -- 0 means "not set" to the gate.""" - a = _common.ReentryContext.generate_id() - b = _common.ReentryContext.generate_id() + a = _common.ReentryContext.get_or_generate_id() + b = _common.ReentryContext.get_or_generate_id() assert a != 0 and b != 0 assert a != b - def test_active_sets_current_id_then_resets_on_exit(self): - """active() must make the identity visible via current_id() for the - duration of its block -- this is what a re-entrant callback - captures and presents through the gate. Once the block exits, it - must reset the ContextVar rather than just setting it.""" + def test_active_sets_current_id_reuses_for_get_or_generate_id_then_resets_on_exit(self): + """active() must, for the duration of its block: (1) make the + identity visible via current_id(), and (2) have get_or_generate_id() + reuse it rather than generating a fresh one -- this is what lets a + re-entrant call present the same identity through the gate. Once + the block exits, it must reset the ContextVar rather than just + setting it.""" assert _common.ReentryContext.current_id() == 0 with _common.ReentryContext.active(4242): assert _common.ReentryContext.current_id() == 4242 + assert _common.ReentryContext.get_or_generate_id() == 4242 assert _common.ReentryContext.current_id() == 0 def test_active_nesting_restores_outer_identity(self): @@ -604,36 +386,36 @@ def test_generated_identity_stays_within_unsigned_long_mask(self, monkeypatch): by forcing the counter to the edge of that range and confirming it wraps instead of overflowing.""" monkeypatch.setattr(_common.ReentryContext, '_ctr', itertools.count(0xFFFFFFFE)) - seen = [_common.ReentryContext.generate_id() for _ in range(5)] + seen = [_common.ReentryContext.get_or_generate_id() for _ in range(5)] assert all(0 < i <= 0xFFFFFFFF for i in seen), seen # 0xFFFFFFFF + 1 wraps to 0, remapped to 1 (0 means unset); the next # draw masks to 1 too (0x100000001 & 0xFFFFFFFF == 1), so 1 appears # twice at the wrap before the sequence continues from 2. assert seen == [0xFFFFFFFE, 0xFFFFFFFF, 1, 1, 2], seen - def test_active_with_invocation_binds_current_invocation_then_resets_to_none(self): - invocation = _common.Invocation(1) - assert _common.ReentryContext.current_invocation() is None - with _common.ReentryContext.active(1, invocation): - assert _common.ReentryContext.current_invocation() is invocation - assert _common.ReentryContext.current_invocation() is None - - def test_active_nesting_with_invocation_restores_outer_invocation(self): - outer_invocation = _common.Invocation(1) - inner_invocation = _common.Invocation(2) - with _common.ReentryContext.active(1, outer_invocation): - with _common.ReentryContext.active(2, inner_invocation): - assert _common.ReentryContext.current_invocation() is inner_invocation - assert _common.ReentryContext.current_invocation() is outer_invocation - assert _common.ReentryContext.current_invocation() is None - - def test_active_without_invocation_arg_clears_outer_invocation_for_the_block(self): - """active() called without an invocation argument does not preserve - an outer bound Invocation -- it explicitly clears it for the - duration of the block, then restores it on exit.""" - invocation = _common.Invocation(1) - with _common.ReentryContext.active(1, invocation): - assert _common.ReentryContext.current_invocation() is invocation + def test_active_with_lock_binds_current_lock_then_resets_to_none(self): + lock = asyncio.Lock() + assert _common.ReentryContext.current_lock() is None + with _common.ReentryContext.active(1, lock): + assert _common.ReentryContext.current_lock() is lock + assert _common.ReentryContext.current_lock() is None + + def test_active_nesting_with_lock_restores_outer_lock(self): + outer_lock = asyncio.Lock() + inner_lock = asyncio.Lock() + with _common.ReentryContext.active(1, outer_lock): + with _common.ReentryContext.active(2, inner_lock): + assert _common.ReentryContext.current_lock() is inner_lock + assert _common.ReentryContext.current_lock() is outer_lock + assert _common.ReentryContext.current_lock() is None + + def test_active_without_lock_arg_clears_outer_lock_for_the_block(self): + """active() called without a lock argument does not preserve an + outer bound lock -- it explicitly clears it for the duration of + the block, then restores it on exit.""" + lock = asyncio.Lock() + with _common.ReentryContext.active(1, lock): + assert _common.ReentryContext.current_lock() is lock with _common.ReentryContext.active(2): - assert _common.ReentryContext.current_invocation() is None - assert _common.ReentryContext.current_invocation() is invocation + assert _common.ReentryContext.current_lock() is None + assert _common.ReentryContext.current_lock() is lock From f0ed844861c4dfaaae0a82dcd5742781413faed1 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Fri, 28 Aug 2026 17:16:25 +0530 Subject: [PATCH 13/14] Revert "Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant" This reverts commit f75dba3a1525df3c20fc7216ee00b31a6d9cf1b0. --- src/confluent_kafka/aio/_AIOConsumer.py | 83 +++++-------------------- 1 file changed, 15 insertions(+), 68 deletions(-) diff --git a/src/confluent_kafka/aio/_AIOConsumer.py b/src/confluent_kafka/aio/_AIOConsumer.py index 9c91617b9..a93251862 100644 --- a/src/confluent_kafka/aio/_AIOConsumer.py +++ b/src/confluent_kafka/aio/_AIOConsumer.py @@ -45,12 +45,6 @@ class AIOConsumer: on_assign calling assign(), or on_commit calling commit()) is recognized as belonging to the same caller and is admitted immediately rather than waiting on itself. - - A call created inside a callback but not awaited there (e.g. via an - un-awaited asyncio.create_task()) may outlive the callback invocation - it was created in. Such a call is not re-entrant: it runs as a new - top-level call, waiting for the operation that fired the callback to - finish rather than being admitted alongside it. """ def __init__( @@ -90,73 +84,26 @@ async def _call(self, blocking_task: Callable[..., Any], *args: Any, **kwargs: A if self._closed: raise RuntimeError("Consumer closed") - # Set when this call was made from within a callback invocation - # (e.g. on_assign), inherited via context propagation -- including - # into tasks created inside the callback. See _common.Invocation. - invocation = _common.ReentryContext.current_invocation() - - if invocation is not None: - # Sibling calls dispatched concurrently from the same callback - # invocation serialize on its lock, so only one presents the - # shared identity to the gate at a time. - async with invocation.lock: - if invocation.alive: - return await self._reentrant_call(invocation, blocking_task, *args, **kwargs) - # The callback has already returned (e.g. an un-awaited - # create_task() that outlived it): its identity is stale, and - # presenting it could run this call concurrently with the still - # in-flight call that fired the callback. Fall through and run - # as a fresh top-level call instead, outside the lock, which - # only exists to serialize the invocation's own calls. - - # Resolved here, on the event-loop thread, and presented from inside - # wrapped_task so it is visible to the call it guards, including any - # re-entrant callback (e.g. on_assign) that blocking_task triggers - # synchronously before returning. - identity = _common.ReentryContext.generate_id() + # Resolved here, on the event-loop thread, so a re-entrant call reuses + # the enclosing call's identity -- see _common.ReentryContext. + identity = _common.ReentryContext.get_or_generate_id() + + # Using the lock, the call gets serialized against any sibling in + # the same callback invocation dispatched concurrently. + # For any calls from outside a callback, this value stays None. + lock = _common.ReentryContext.current_lock() + # Presented from inside wrapped_task so it is visible to the call it + # guards, including any re-entrant callback (e.g. on_assign) that + # blocking_task triggers synchronously before returning. def wrapped_task(*task_args: Any, **task_kwargs: Any) -> Any: with _common.ReentryContext.active(identity): return blocking_task(*task_args, **task_kwargs) - return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) - - async def _reentrant_call( - self, invocation: _common.Invocation, blocking_task: Callable[..., Any], *args: Any, **kwargs: Any - ) -> Any: - """Dispatch a call made from within a live callback invocation, - presenting the enclosing call's identity so the gate admits it. - - The invocation must stay open until this dispatch has fully left - the gate, even if the task awaiting it is cancelled (e.g. by - asyncio.wait_for()): a worker thread cannot be interrupted, so the - blocking call keeps running after the await below is abandoned. - The done callback on the executor future -- which fires only once - wrapped_task has actually returned, or the submission was cancelled - before ever starting -- is therefore what balances the in-flight - count, never this coroutine's own await. - - Called with invocation.lock held. - """ - loop = asyncio.get_running_loop() - - def wrapped_task() -> Any: - with _common.ReentryContext.active(invocation.identity): - return blocking_task(*args, **kwargs) - - invocation.dispatch_started() - future = self.executor.submit(wrapped_task) - - def on_done(_: concurrent.futures.Future) -> None: - try: - loop.call_soon_threadsafe(invocation.dispatch_finished) - except RuntimeError: - # Event loop already closed (interpreter shutdown); nothing - # is waiting on the drain anymore. - pass - - future.add_done_callback(on_done) - return await asyncio.wrap_future(future) + if lock is None: + return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) + async with lock: + return await _common.async_call(self.executor, wrapped_task, *args, **kwargs) def _wrap_callback( self, From ff95c4ea8c1505fc2af7fe672cce850e77d96365 Mon Sep 17 00:00:00 2001 From: Ojasva Jain Date: Fri, 28 Aug 2026 17:28:22 +0530 Subject: [PATCH 14/14] Add TODO --- src/confluent_kafka/aio/_common.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/confluent_kafka/aio/_common.py b/src/confluent_kafka/aio/_common.py index 34572ffc7..fba6d4c5d 100644 --- a/src/confluent_kafka/aio/_common.py +++ b/src/confluent_kafka/aio/_common.py @@ -26,6 +26,8 @@ T = TypeVar('T') +# TODO NOGIL: Fix for fire and forget tasks created inside callbacks. +# We don't want such tasks to escape serialization and run concurrently. class ReentryContext: """Internal use only. Per-call-chain context AIOConsumer carries through a ContextVar: the identity presented to the Consumer reentrancy gate, and