Repository navigation
[NOGIL] Restrict sharing of Consumer instances across threads - #2322
Conversation
|
🎉 All Contributor License Agreements have been signed. Ready to merge. |
015da26 to
4c750a2
Compare
3cd1566 to
da12753
Compare
| @@ -186,6 +190,10 @@ def worker(producer, stop_event): | |||
| def test_close_races_abort_transaction(): | |||
| """close() concurrent with abort_transaction() on another thread.""" | |||
|
|
|||
| # 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. | |||
There was a problem hiding this comment.
Will revisit this in a separate PR that I plan to raise for Transactional Producer related audit.
c822dd7 to
dd5d705
Compare
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.
d15855d to
d5eb86d
Compare
Kaushik Raina (k-raina)
left a comment
There was a problem hiding this comment.
Thanks for PR!
Provided couple of correctness comments on gating logic.
| -- see Handle_gate_enter() in Consumer.c. | ||
| """ | ||
|
|
||
| _var = cimpl._reentry_identity_var |
There was a problem hiding this comment.
The gate identifies callers with a contextvar asyncio copies a task's context into every child task it spawns (gather, create_task), so any task launched from inside a callback inherits the same identity as the callback.
- When an application writes callbacks like:
async def on_assign(consumer, partitions):
await asyncio.gather(*(consumer.seek(tp) for tp in partitions))
def on_commit(err, partitions):
asyncio.create_task(consumer.commit())
- the spawned tasks inherit the callback's identity, so the owner == identity check in the gate is true for each of them and the gate admits them concurrently instead of serializing them.
- when poll() is running and its rebalance callback fires. The callback does gather(consumer.seek(a), consumer.seek(b)) two child tasks, both carrying the callback's copied identity are dispatched onto two executor worker threads.
- Task A enters Handle_gate_enter. Gate is free, so A takes it. A is now inside the C code, using self->rk
- Task B enters Handle_gate_enter. It sees gate_owner == identity (same copied badge), assumes it's a nested re-entrant call, does gate_depth++, and returns "admitted" immediately.
- Now A and B are both inside the gated code at once, both touching self->rk.
Since running on two threads at once, those updates can collide with each other. When both threads increment and decrement the same object's reference count without synchronization, one of the updates can be lost, and the recorded count drops below the number of references that actually exist. The object is then freed while it is still in use, and the next thread to reach for it dereferences memory that has already been released . The use after free that can crash the process.
Can we check if this can cause any issue?
There was a problem hiding this comment.
Yes I have documented it as a gap here(line 120). We can use python level lock to serialize the access. I will address this in a separate PR.
There was a problem hiding this comment.
Added a TODO at the same place
There was a problem hiding this comment.
Thanks Ojasva Jain (@ojasvajain) ,
As this has potential to crash, not sure if we should prioritise this fix. Feel free to ping me , i will review second PR ASAP.
| #ifdef _WIN32 | ||
| Sleep(1); | ||
| #else | ||
| usleep(1000); |
There was a problem hiding this comment.
Lets take an minimal example :
async def on_assign(c, partitions):
await c.assign(partitions)
await consumer.subscribe([topic], on_assign=on_assign)
await asyncio.gather(
consumer.poll(10),
consumer.commit(),
)
AIOConsumer runs every call on a fixed thread pool (default 2 workers). A poll() takes worker 1 and the gate, then blocks waiting for its rebalance callback to return. A concurrent commit() (different thread) takes worker 2 and busy-spins at the gate instead of releasing its worker. The callback now makes a re-entrant call (assign/pause) that needs a worker but both are taken.
Application impact : For applications doing manual offset management (seek/commit from a rebalance callback) while any background task also calls the consumer will be stuck in Deadlock.
Could we check this?
There was a problem hiding this comment.
Yes this is possible if number of workers are less. But we can't have multiple tasks/threads touching the consumer handle at the same time and given AIO consumer schedules callbacks on different thread, we will need to accept this caveat. We will document this behaviour and recommend users to have enough workers in their thread pool.
Since this change will be part of a minor version upgrade, we decided to serialize the calls rather than returning ConcurrentModificationException to the users, as this will not be backward compatible. In the next major version upgrade, we can replace the waiting behaviour with throwing the exception which will avoid such deadlocks and change them to exceptions.
There was a problem hiding this comment.
Since we are documenting that "consumer should not be called from multiple user threads", should we mention that it would deadlock in document, so its not a surprise if some one faces it?
Also as you mentioned above, AIOConsumer hits it because the concurrency is created by the library, not the user. The user writes ordinary single-event-loop async code, but AIOConsumer runs every call on its internal ThreadPoolExecutor (default 2 workers). Should we plan to update default threads?
There was a problem hiding this comment.
should we mention that it would deadlock in document, so its not a surprise if some one faces it?
We will mention - ensure there are adequate number of workers in the pool otherwise it can cause deadlocks.
Should we plan to update default threads?
Yes that's what Emanuele Sabellico (@emasab) suggested today. Will think of what can be the new default value.
There was a problem hiding this comment.
Bumped it to 100
| #ifdef _WIN32 | ||
| Sleep(1); | ||
| #else | ||
| usleep(1000); |
There was a problem hiding this comment.
For code snippet:
async def consume_loop():
while running:
msg = await consumer.poll(-1) # block until the next message
if msg:
await process(msg)
async def shutdown_on_signal():
await consumer.close() # ← must wait behind poll(-1) at the gate
await asyncio.gather(consume_loop(), shutdown_on_signal())
- consume_loop's poll(-1) calls Handle_gate_enter and takes the gate, then enters a chunk loop. With timeout = -1, poll forever until a message arrives. The gate is held the entire time.
- shutdown's close() calls Handle_gate_enter, sees the gate owned by poll (different identity), and spins in the wait loop (usleep) waiting for poll to release it.
Application impact
For applications with Idle topic → no message → poll(-1) never returns → the gate is never released → close spins forever. The consumer is stuck.
Can we check this?
There was a problem hiding this comment.
Yes. This will expected. And this is the cost of serializing the calls, rather then returning the exception but that will not be backward compatible.
In the latest version of the python client, calling close() in parallel with poll(-1) is unsafe and causes hangs or segfault. So this is not a supported pattern anyway.
In Java client, close() will get a ConcurrentModificationException.
There was a problem hiding this comment.
In the latest version of the python client, calling close() in parallel with poll(-1) is unsafe and causes hangs or segfault. So this is not a supported pattern anyway.
This behavior might be working for current latest version of python client, as it doesn't support free threading. However with free threading, will above consumer stuck issue might be commonly encounted?
If we are documenting that consumer will not free threading, that will work for Sync Consumer, however will consumer stuck still be case for AIOConsumer running in NOGIL package?
There was a problem hiding this comment.
This behavior might be working for current latest version of python client, as it doesn't support free threading.
As mentioned earlier, in current version, calling close() in parallel with any other conusmer call causes hangs or segfault because at librdkafka layer, these APIs are not thread safe with each other. By serializing the calls, we want to prioritize correctness of the consumer's behaviour. So with these changes, there will be no segfault or hang, but there will be indefinite wait because we are serializing the calls.
However with free threading, will above consumer stuck issue might be commonly encountered?
Since it does not work in the current version, we can assume that nobody uses this pattern.
If we are documenting that consumer will not free threading, that will work for Sync Consumer, however will consumer stuck still be case for AIOConsumer running in NOGIL package?
We will document that consumer is not thread safe and the statement will be applicable for both Sync and Async consumers. If worker thread 1 is calling poll() and after that, worker thread 2 calls close(), then worker thread 2 will wait for poll() to complete. During this time, worker 2 will be blocked and any new call will need a new worker.
Kaushik Raina (k-raina)
left a comment
There was a problem hiding this comment.
Comments on AIOConsumer mainly
| -- see Handle_gate_enter() in Consumer.c. | ||
| """ | ||
|
|
||
| _var = cimpl._reentry_identity_var |
There was a problem hiding this comment.
Thanks Ojasva Jain (@ojasvajain) ,
As this has potential to crash, not sure if we should prioritise this fix. Feel free to ping me , i will review second PR ASAP.
| #ifdef _WIN32 | ||
| Sleep(1); | ||
| #else | ||
| usleep(1000); |
There was a problem hiding this comment.
Since we are documenting that "consumer should not be called from multiple user threads", should we mention that it would deadlock in document, so its not a surprise if some one faces it?
Also as you mentioned above, AIOConsumer hits it because the concurrency is created by the library, not the user. The user writes ordinary single-event-loop async code, but AIOConsumer runs every call on its internal ThreadPoolExecutor (default 2 workers). Should we plan to update default threads?
| #ifdef _WIN32 | ||
| Sleep(1); | ||
| #else | ||
| usleep(1000); |
There was a problem hiding this comment.
In the latest version of the python client, calling close() in parallel with poll(-1) is unsafe and causes hangs or segfault. So this is not a supported pattern anyway.
This behavior might be working for current latest version of python client, as it doesn't support free threading. However with free threading, will above consumer stuck issue might be commonly encounted?
If we are documenting that consumer will not free threading, that will work for Sync Consumer, however will consumer stuck still be case for AIOConsumer running in NOGIL package?
| ) | ||
| if conf: | ||
| consumer_conf.update(conf) | ||
| return TestAIOConsumer(consumer_conf, max_workers=3) |
There was a problem hiding this comment.
Should we be using more workers to future proof tests, considering we have limitation regarding low count threads mentioned in comment https://github.com/confluentinc/confluent-kafka-python/pull/2322/changes#r3813055437?
There was a problem hiding this comment.
Yes, we will increase the max workers default value (I am still thinking of what should be the right value). Once we do that, we don't need to set max workers here.
There was a problem hiding this comment.
Removed explicit setting of max_workers here as default value is increased
| commit_result, BaseException | ||
| ), f"expected the independent top-level commit() call to wait and then succeed, got: {commit_result}" | ||
|
|
||
| result = await consumer.assignment() |
There was a problem hiding this comment.
Should we verify, if commit actually persisted to broker? Maybe Like
partitions = await consumer.assignment()
assert partitions
positions = await consumer.position(partitions)
committed = await consumer.committed(partitions, timeout=10)
There was a problem hiding this comment.
Ack, will check.
Kaushik Raina (k-raina)
left a comment
There was a problem hiding this comment.
Added few comments on code quality and tests
| self, | ||
| consumer_conf: Dict[str, Any], | ||
| max_workers: int = 2, | ||
| max_workers: int = 100, |
There was a problem hiding this comment.
Considering that we are spawning high number of threads, threads (and memory) pile up until the process is exhausted. Should we shut them down in close call?
There was a problem hiding this comment.
Checked this. Currently in AIO Consumer close, we simply call the Consumer_close from C bindings and do nothing else. The threads in the pool will be idle and alive until they get garbage collected so they will remain alive for an indeterministic time. As an improvement we can shutdown the executor (and its threads) immediately after close. We will do this only when the executor is not user-supplied. I am pushing a change for this.
| struct commit_return commit_return; | ||
| PyThreadState *thread_state; | ||
|
|
||
| if (!Handle_gate_enter(self)) { |
There was a problem hiding this comment.
Can we use goto syntax to make this function consistent with others?
There was a problem hiding this comment.
I modified 10-12 functions into having goto so that they only have one exit path. But for Consumer_commit() and Consumer_consume(), I found these function to be complex and modifying them to having goto may require good amount of testing to avoid introducing any regression. That's why I decided to skip them.
| @@ -1114,38 +1367,47 @@ static PyObject * | |||
| Consumer_consume(Handle *self, PyObject *args, PyObject *kwargs) { | |||
There was a problem hiding this comment.
Can we use goto syntax to make this function consistent with others?
There was a problem hiding this comment.
Same as above.
| */ | ||
| static void Handle_gate_exit(Handle *h) { | ||
| int depth = atomic_int_dec(&h->u.Consumer.gate_depth); | ||
| assert(depth >= 0); |
There was a problem hiding this comment.
Will this asset be functional in production?
There was a problem hiding this comment.
No. This is only applicable for debug builds, not production builds.
| #ifdef _WIN32 | ||
| Sleep(1); | ||
| #else | ||
| usleep(1000); |
There was a problem hiding this comment.
Does it makes sense to define these magic numbers as constants?
There was a problem hiding this comment.
I am thinking of creating a function which takes the duration as param and calls Sleep / usleep. I will do that refactoring as part of the admin PR because I need to add sleep for Admin as well. Once I move it in a function, we can store the duration in constant.
There was a problem hiding this comment.
Added a TODO for this.
| from . import _common as _common | ||
|
|
||
|
|
||
| class AIOConsumer: |
There was a problem hiding this comment.
Considering this class will be bit complex now, with NOGIL, should we add detailed class docstring?
There was a problem hiding this comment.
I have added a docstring.
| 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 | ||
| consumer = AIOConsumer(basic_config, max_workers=2) |
There was a problem hiding this comment.
Any reason why we are using max_workers=2 in tests? Can we use default i.e 100 ?
There was a problem hiding this comment.
Yes, we can remove it.
There was a problem hiding this comment.
Removed from this and other UTs in this file where setting max workers is not relevant.
|
a15c8ad
into
dev_thread_free_support
* 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. * Style fixes * Fix flaky tests * Add TODO for handling concurrent calls inside callback * Addressed comments * Trigger CLA check * Address comments * Return consistent error when consumer is closed * Fix one test case * Fix styling
* 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. * Style fixes * Fix flaky tests * Add TODO for handling concurrent calls inside callback * Addressed comments * Trigger CLA check * Address comments * Return consistent error when consumer is closed * Fix one test case * Fix styling
* 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. * Style fixes * Fix flaky tests * Add TODO for handling concurrent calls inside callback * Addressed comments * Trigger CLA check * Address comments * Return consistent error when consumer is closed * Fix one test case * Fix styling
* 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. * Style fixes * Fix flaky tests * Add TODO for handling concurrent calls inside callback * Addressed comments * Trigger CLA check * Address comments * Return consistent error when consumer is closed * Fix one test case * Fix styling
* [NOGIL] Add CI verification jobs for free-threaded Python 3.14t (#2304) * Add CI verification jobs for free-threaded Python 3.14t - Add a Semaphore block running source package verification and integration tests on CPython 3.14t (classic and consumer group protocols). cimpl does not declare free-threading support yet, so importing it re-enables the GIL: these jobs validate the 3.14t toolchain and packaging until that declaration ships. - Skip the CI-only orjson install on free-threaded interpreters: no free-threaded orjson wheels exist and the source build would fail; the stdlib JSON fallback path stays covered. - Add a module-scoped autouse fixture (defined on free-threaded builds only) that warns when the GIL is re-enabled around a test module. Hard asserts are staged behind TODO FTS markers, to be enabled in the same PR that declares Py_MOD_GIL_NOT_USED. Interpreter detection follows the free-threading HOWTO: https://docs.python.org/3/howto/free-threading-python.html * Handle deps without free-threaded wheels in test setup On free-threaded (no-GIL) builds, the rules and json-fast extras' compiled deps (tink, google-re2, grpcio; orjson) ship no free-threaded wheels and fail to build from source, so: - Add requirements-tests-install-nogil.txt, a variant of requirements-tests-install.txt without those extras, and install it from source-package-verification.sh when the interpreter is free-threaded (detected via Py_GIL_DISABLED). - Exclude the schema_registry test modules that import tink/celpy/orjson at the top of the file from collection on free-threaded builds only; on regular builds a missing dep stays a loud collection error rather than a silent skip. Plain serdes coverage recovery is marked as a TODO NOGIL follow-up. * Style fixes * [NOGIL] Split schema_registry tests to narrow free-threaded test exclusions (#2309) * [NOGIL] Split schema_registry tests to narrow free-threaded test exclusions Each of test_avro_serdes.py, test_config.py, test_json_serdes.py, and test_proto_serdes.py is split into a plain file (no rules/encryption dependency) and a _rules file (CEL/encryption/JSONata-dependent tests). This lets the plain tests run on free-threaded (3.14t) builds, where tink/celpy/orjson have no free-threaded wheels, while only the _rules files stay excluded via conftest.py's collect_ignore. * Fix isort/black formatting in split schema_registry tests * [NOGIL] Fix post-rebase gap: exclude azure/tink-dependent schema_registry tests from free-threaded collection test_azure_aead.py, test_azure_client.py, test_azure_driver.py, and test_encrypt_executor.py import azure/tink unconditionally at module level but were missing from conftest.py's free-threaded collect_ignore list, causing collection errors on 3.14t CI. These tests were added to master after the original NOGIL schema_registry exclusion list (#2309) landed, so they weren't accounted for; rebasing onto master surfaced the gap. * [NOGIL] Fix post-rebase gap: update schema_registry free-threaded exclusions test_json.py's orjson import became pytest.importorskip upstream, so it no longer needs excluding. test_dlq_serdes.py is new post-rebase and hard- imports celpy, so it needs excluding. * [NOGIL] Exclude test_dlq.py from free-threaded schema_registry integration test collection * [NOGIL] Fix Producer.close() races with concurrent calls and with itself (#2313) * Fix Producer.close() races with concurrent calls and with itself Producer.close() previously raced with concurrent produce()/poll()/ flush()/produce_batch()/transaction calls and with itself when called from multiple threads, both leading to use-after-free/double-free on the underlying rd_kafka_t handle. Adds an active_calls/closing guard (Handle_enter_rk_use/Handle_exit_rk_use) so every method that touches self->rk registers itself before use, and close() drains in-flight calls before tearing down; a CAS on `closing` ensures only one concurrent close() call performs the actual teardown, with losing callers waiting for it to finish rather than racing it. Adds tests/parallel/test_producer_close_race.py covering each affected method racing close(), close() racing itself, and close()'s blocking behavior. Uses pytest-forked (POSIX only) so a regression segfault fails only that test. Integration tests against a real broker are still pending. * Replace pytest-forked with subprocess-based test isolation * Fix subprocess_isolated import and flaky close() timing assertion * Rename tests/parallel to tests/concurrency and add integration tests for Producer close()/transaction races * Clarified comment * Make Producer.close() non-blocking for concurrent callers, add reentrancy tests Concurrent close() calls now return False immediately with a warning instead of waiting for the CAS winner, since waiting could deadlock a caller that already holds an active_calls slot (e.g. a callback invoked from its own poll()/flush()). poll()/flush() now also exit early once closing is set instead of blocking the drain-wait. Fixes an ordering bug in produce_batch() where the topic handle was destroyed after releasing the active_calls slot. Adds integration tests for reentrant callbacks and close()'s internal flush delivering all messages, and documents close()-from-callback as unsupported. * Fix close() losers to wait for winner instead of returning False early * Fix CI flakiness in test_close_races_close_losers_wait_for_slow_winner * Move signal/slow-winner close() race tests to integration suite * Allow reentrant Producer calls from close()'s own delivery callback * Update docstring of test case * Harden race checks * [NOGIL] Restrict sharing of Consumer instances across threads (#2322) * 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. * Style fixes * Fix flaky tests * Add TODO for handling concurrent calls inside callback * Addressed comments * Trigger CLA check * Address comments * Return consistent error when consumer is closed * Fix one test case * Fix styling * [NOGIL] Exclude Avro tests from running on free threaded python builds (#2335) * Exclude Avro tests from running on free threaded python builds * Exclude only fastavro * temoporarily install fastavro for docs * [NOGIL] Declare thread free support * [NOGIL] Improve Test Coverage for Producer + Some Edge Case Fixes (#2329) * 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. * Trigger CLA check * Add Integration test coverage for AIO Producer * Add Tx related test cases + Add abort_tx call in Producer close * Fix flaky AIO Producer test case * Fix for serializing concurrent calls from a Async callback * Minor improvements to tests * Fix styling * Fix flaky test case * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Revert "Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant" This reverts commit 42b40cc. * Revert "Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant" This reverts commit f75dba3. * Add TODO * [NOGIL] Fix post-rebase gap: move rules test from test_proto_serdes.py to test_proto_serdes_rules.py * [NOGIL] Fix post-rebase gap: Fix misplaced CEL test and missing free-threaded collect_ignore entries * [NOGIL] Fix post-rebase gap: Initialize queue and add exit call in Consumer_consume * [NOGIL] Guard AdminClient against concurrent close() vs method-call races (#2317) (#2346) * 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. * Trigger CLA check * Add Integration test coverage for AIO Producer * Add Tx related test cases + Add abort_tx call in Producer close * Fix styling * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Trigger CLA check * Trigger CLA check * 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. * Style fixes * Addressed comments * Trigger CLA check * Address comments * Add Tx related test cases + Add abort_tx call in Producer close * Fix for serializing concurrent calls from a Async callback * Fix one test case * Fix styling * [NOGIL] Guard AdminClient against concurrent close()-vs-method-call races * Add handle check in common APIs and refactor overall handle logic * Remove conflict marker * Remove another conflict marker * Rename handle functions * Add more tests * Fix flaky test * Address comments * Fix corrupted _common.py * Fix other corrupted files * Fix flaky test case * [NOGIL] Fix borrowed-reference/stale-count races (#2334) (#2348) * 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. * Trigger CLA check * Add Integration test coverage for AIO Producer * Add Tx related test cases + Add abort_tx call in Producer close * Fix styling * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Serialize AIOConsumer calls that outlive their callback invocation instead of admitting them as re-entrant * Trigger CLA check * Trigger CLA check * 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. * Style fixes * Addressed comments * Trigger CLA check * Address comments * Add Tx related test cases + Add abort_tx call in Producer close * Fix for serializing concurrent calls from a Async callback * Fix one test case * Fix styling * [NOGIL] Guard AdminClient against concurrent close()-vs-method-call races * Add handle check in common APIs and refactor overall handle logic * Remove conflict marker * Remove another conflict marker * Rename handle functions * Add more tests * Fix flaky test * Address comments * Fix corrupted _common.py * Fix other corrupted files * Fix flaky test case * [NOGIL] Fix borrowed-reference/stale-count races in Admin/Producer/Consumer parse loop * Fix list mutation in Admin API and a flaky test case * Fix data race on Handle.rk in close()/__exit__()/__len__() by making liveness checks atomic * Fix flaky test * Address comments * [NOGIL] Make Message class methods thread safe (#2350) * Make Message class methods thread safe * Add thread safety for eq and len functions, ref counting test cases * Use getters instead of direct access in Consumer methods * Fix mem leak * Use a single object-level lock for Message, snapshot via Message_copy, and fix __eq__ field comparison (treat unset/None alike, no crash)


Introduces a reentrancy gate for the sync Consumer and AIOConsumer that serializes concurrent access to a single Consumer instance from a different caller — a colliding call waits for the current caller to finish rather than interleaving or racing directly against librdkafka's own consumer, which isn't thread-safe — while still allowing legitimate re-entrant calls to proceed immediately — e.g. a rebalance or commit callback calling back into the Consumer/AIOConsumer that triggered it (on_assign calling assign(), on_commit calling commit(), etc.).
A unified gate_owner/gate_depth mechanism (Handle_gate_enter()/Handle_gate_exit() in Consumer.c) is shared between both sync and async consumer types, and every gated method resolves its own caller identity internally. For the sync consumer, calling thread ID serves as the identity, while for the async consumer an ID is generated before dispatching each call and carried over through the task chain using context variables. For async consumers this is required, as callbacks may get scheduled on a different worker thread, so a thread ID can not be used as an identity.