Skip to content

[NOGIL] Fix borrowed-reference/stale-count races - #2334

Merged
Ojasva Jain (ojasvajain) merged 35 commits into
dev_thread_free_support_previewfrom
dev_mem_ref_fixes_no_gil
Sep 2, 2026
Merged

Ojasva Jain (ojasvajain) merged 35 commits into
dev_thread_free_support_previewfrom
dev_mem_ref_fixes_no_gil

Conversation

@ojasvajain

@ojasvajain Ojasva Jain (ojasvajain) commented Aug 27, 2026 •

Copy link
Copy Markdown
Member
  1. Fixes Free-threaded (no-GIL) use-after-free in Admin_create_topics: borrowed NewTopic from PyList_GET_ITEM dereferenced as a C struct against a stale count #2319 and related issues across Producer/Consumer/Admin clients.
  2. Adds unit and integration test cases to validate the fixes.

What

Checklist

  • Contains customer facing changes? Including API/behavior changes
  • Did you add sufficient unit test and/or integration test coverage for this PR?
    • If not, please explain why it is not required

References

JIRA:

Test & Review

Open questions / Follow-ups

@confluent-cla-assistant

Copy link
Copy Markdown

🎉 All Contributor License Agreements have been signed. Ready to merge.
Please push an empty commit if you would like to re-run the checks to verify CLA status for all contributors.

@ojasvajain

Copy link
Copy Markdown
Member Author

Junhyung Lee (@espressolee) Feel free to run your harness against 980398c

@espressolee

Copy link
Copy Markdown

Tested exact head 980398c04e2c97bc471585fb0e92b475db31139c against exact base 5ccf0ab2bf16f990525f8bb286b995b04b5ba9ae.

Environment: macOS/arm64, CPython 3.14.0rc1t, sys._is_gil_enabled() == False, C extension built from each exact tree, Homebrew librdkafka 2.15.0. The fake broker is unreachable; the reported parse path is synchronous and does not require a broker.

arm result
base, constant-length topics[i] replacement 10/10 SIGSEGV
base, shrink/regrow stale-count race 10/10 SIGSEGV
base, same replacement with runtime GIL enabled 0/5 faults
candidate, constant-length replacement 0/20 faults
candidate, shrink/regrow 0/20 faults
candidate, no mutator 0/5 faults
candidate, decoy-list mutation 0/5 faults
candidate, runtime GIL enabled 0/5 faults

There were no timeouts or other nonzero exits in the matrix. The constant-length arm isolates the borrowed-element lifetime window independently of the captured count; the shrink/regrow arm isolates the stale-count window.

I also ran the new broker-free memory-safety file on the candidate:

PYTHON_GIL=0 python -m pytest -q tests/concurrency/test_memory_safety.py -vv
21 passed in 120.44s

Bounded conclusion: on this measured host, exact head 980398c closes both #2319 mechanisms. I did not test other platforms or allocators, and I did not run the broker-backed integration tests. Semaphore CI is green; the current SonarQube failure is the separate new-code coverage gate.

@ojasvajain

Copy link
Copy Markdown
Member Author

Thanks.

base, constant-length topics[i] replacement 10/10 SIGSEGV
base, shrink/regrow stale-count race 10/10 SIGSEGV

Did you observe failures again or am I interpreting the results incorrectly?

@espressolee

Copy link
Copy Markdown

No new failures were observed on the candidate — those two 10/10 SIGSEGV rows are the exact base (5ccf0ab2bf16f990525f8bb286b995b04b5ba9ae) positive controls, included to confirm that the harness still reproduces the original bugs.

For exact candidate 980398c04e2c97bc471585fb0e92b475db31139c:

  • constant-length replacement: 0/20 faults
  • shrink/regrow: 0/20 faults
  • candidate memory-safety test file: 21/21 passed

So on this host: base fails; candidate passes both arms. I could have made that split more prominent in the table.

@espressolee

Copy link
Copy Markdown

Refreshed the focused validation after the bot-updated PR head.

Exact pair now checked: base 74860f00ac2ca9b63cf814099032fd179609452f, head 7db086ee8abfdc521737ffb3244dd1dc37b614c7.

The four changed C source files and tests/concurrency/test_memory_safety.py relevant to #2319 are blob-identical between the previously tested 980398c and current 7db086e; the previous/current base C blobs are likewise identical. I nevertheless rebuilt the extension from exact 7db086e and reran the two candidate arms on the same macOS/arm64 CPython 3.14.0rc1t host with the GIL disabled and librdkafka 2.15.0:

  • constant-length replacement: 20/20 clean
  • shrink/regrow: 20/20 clean
  • signals, timeouts, other nonzero exits: 0
  • PYTHON_GIL=0 python -m pytest -q tests/concurrency/test_memory_safety.py -vv: 21 passed, 1 warning in 119.97s

No new candidate failure was observed on this host. I did not rerun the base positive controls because the relevant base C blobs are byte-identical to the previously reproduced base. The current Semaphore check is failing, and its external job log is not available to me, so this focused result does not claim overall CI or merge readiness.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact PR head ca340b81627f23ad5a4c3deebbb854677a630f2d
against exact base 143a219bf69cb0c310db7c0d37190e654da71515.

I rebuilt both trees independently on macOS/arm64 with CPython 3.14.6t,
sys._is_gil_enabled() == False, and librdkafka 2.15.0.

Focused #2319 matrix:

  • base, constant-length topics[i] replacement: 5/5 SIGSEGV
  • base, shrink/regrow stale-count race: 5/5 SIGSEGV
  • base, same replacement with the GIL enabled: 5/5 clean
  • head, constant-length replacement: 10/10 clean
  • head, shrink/regrow: 10/10 clean
  • head, no-mutator / decoy-list / GIL controls: 5/5 clean each

The PR's broker-free memory-safety file passed twice on the exact head:
21/21 in 119.62 s and 21/21 in 120.39 s. tests/test_Admin.py
passed 33/33 and tests/test_Consumer.py passed 21/21 with the GIL disabled.

I also checked the current diff and cleanup paths for the shallow snapshots
covering the #2319 list-count and borrowed-element lifetime windows. I found no
blocking issue in that measured scope.

Limits: I did not run broker-backed integration tests, other platforms or
allocators, or the full project suite. The free-threaded snapshot allocation
cost is unmeasured. Current SonarQube and Semaphore statuses are still failing,
so this review does not claim overall CI or merge readiness.

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.
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.
@airlock-confluentinc
airlock-confluentinc Bot force-pushed the dev_mem_ref_fixes_no_gil branch from ca340b8 to a9994be Compare August 29, 2026 17:14
@espressolee

Copy link
Copy Markdown

Retested exact head 00d97b063b7f2ee9ff0ced5cf4e513414a135f16 against exact base 2dd1397525fef9c02ec4bffabed503b5c5b024e3 on macOS arm64 / CPython 3.14.0rc1t / librdkafka 2.15.0.

Issue #2319 matrix:

revision constant-length replacement shrink/regrow stale count
base 2dd1397 9/10 SIGSEGV, 1 clean 10/10 SIGSEGV
candidate 00d97b0 10/10 clean 10/10 clean

Controls were clean: base GIL-on 5/5; candidate no-mutator 5/5, decoy-list mutation 5/5, and GIL-on 5/5. There were no timeouts or unclassified non-signal exits.

I also exercised the changes added after the previously tested a9994be head:

  • incremental-config mutation: 10/10 clean with the GIL disabled and 10/10 with it enabled;
  • Producer/Admin close-versus-len() stress: 250 total close transactions with eight readers, all clean;
  • upstream suites: memory-safety 21/21, Admin 33/33, Consumer 21/21, Producer 49/49, and the two close-race files 22/22.

The installed extension kept the GIL disabled, and the exact worktree was clean with git diff --check passing. I did not find a new blocker in the a9994be..00d97b0 delta.

This is scoped local evidence for the named list-lifetime, incremental-config, and Producer/Admin close/len paths. It does not supersede the separate SonarQube gate, which remains at 12.0% new-code coverage versus the required 80%, and it is not a broker-backed or cross-platform claim.

Base automatically changed from dev_admin_no_gil to dev_thread_free_support_preview September 1, 2026 07:27

@k-raina Kaushik Raina (k-raina) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for PR Ojasva Jain (@ojasvajain) . Thanks Junhyung Lee (@espressolee) for validations
Couple of minor comments on memory leak and test hardening.

rd_kafka_AclBinding_destroy_array(c_objs, i);
free(c_objs);
}
#ifdef Py_GIL_DISABLED

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cleanup is added to error path but missed in success path. This might cause memory leak.

Application Impact:
A long-running service on a free-threaded build that manages ACLs in a loop e.g. a multi-tenant platform granting/revoking topic permissions as tenants come and go, or a reconciliation loop that periodically re-applies desired ACLs.

Process's memory grows without bound, over days it gets OOM-killed

@ojasvajain Ojasva Jain (ojasvajain) Sep 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed here and in delete_acl as well.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added some ref counting test cases for this

@subprocess_isolated
def test_create_acls_races_list_mutation():
"""AdminClient.create_acls() -- borrows each AclBinding (Admin.c:1463)."""
_admin_list_crash(lambda a, s: a.create_acls(s), _acl_bindings)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In these tests we are checking "did the process die?". Maybe we should be checking ""did it clean up"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By "did it clean up", do you mean that checking if ref counts are balanced? If yes, I have added some tests for the create and delete acls. We can add it for the rest of the methods as well but it is a big list so I have added a TODO for it and add them in a later PR.

Comment thread tests/test_Consumer.py Outdated
# Test error_cb callback
with pytest.raises(RuntimeError) as exc_info:
consumer1.consume(timeout=0.1)
consumer1.consume(timeout=0.5)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Timeout based assertion might be flaky, should we poll for the "callback fired" flag in a bounded loop instead of sleeping a fixed time?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, fixed it.

@sonarqube-confluent

Copy link
Copy Markdown

Quality Gate failed Quality Gate failed

Failed conditions
11.9% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube

@k-raina Kaushik Raina (k-raina) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Overall, with one comment on improving code quality

const char *err_count_desc) {
int pi;
int ret = 0;
#ifdef Py_GIL_DISABLED

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are 80+ calls to "def Py_GIL_DISABLED" . Could we use macros to reduce this or any better way to clean up?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason they are added is that we want to create a copy only on GIL free builds because there is no GIL to serialize. We could remove all ifdefs but that would mean that GIL based builds will also create a copy of the list, which is not wrong in any way, but it is an extra thing that GIL based builds will do even though they don't need to. Since most of changes are in Admin clients, I don't think performance might not be a factor so I can discuss this with Emanuele and reach a conclusion.

@ojasvajain
Ojasva Jain (ojasvajain) merged commit d564253 into dev_thread_free_support_preview Sep 2, 2026
3 of 4 checks passed
@ojasvajain
Ojasva Jain (ojasvajain) deleted the dev_mem_ref_fixes_no_gil branch September 2, 2026 12:19
Ojasva Jain (ojasvajain) added a commit that referenced this pull request Sep 7, 2026
* 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
airlock-confluentinc Bot pushed a commit that referenced this pull request Sep 8, 2026
* 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
airlock-confluentinc Bot pushed a commit that referenced this pull request Sep 18, 2026
* 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
Ojasva Jain (ojasvajain) added a commit that referenced this pull request Sep 21, 2026
* [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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants