Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/confluent_kafka/aio/_AIOConsumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
57 changes: 39 additions & 18 deletions src/confluent_kafka/aio/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import asyncio
import concurrent.futures
import contextlib
import contextvars
import functools
import itertools
import logging
Expand All @@ -25,9 +26,12 @@
T = TypeVar('T')


class ReentryIdentity:
"""Internal use only. The identity AIOConsumer presents to the Consumer
reentrancy gate.
# TODO NOGIL: Fix for fire and forget tasks created inside callbacks.

Check warning on line 29 in src/confluent_kafka/aio/_common.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Complete the task associated to this "TODO" comment.

[S1135] Track uses of "TODO" tags See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=5b6ef106-1bec-4e56-8ade-4183fdb02ddb&open=5b6ef106-1bec-4e56-8ade-4183fdb02ddb
# We don't want such tasks to escape serialization and run concurrently.
class ReentryContext:

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.

Two concurrent subscribe(), which double-frees callback references will be fixed by this fix but remains is the mutating call racing the application poll that is still running, still needs to be fixed?

eg.

async def on_assign(consumer, partitions):
    asyncio.create_task(consumer.subscribe(...),)   
await consumer.subscribe(["topic"], on_assign=on_assign)
await consumer.poll(10)   

Application workflow

  1. poll() runs on executor worker W1, holding the client handle rk.
  2. librdkafka fires on_assign from inside that poll. W1 is now parked waiting for the callback to finish but its C-level poll is suspended mid-execution, still holding rk.
  3. The callback starts consumer.subscribe(). Because asyncio copies the callback's context into the child task, the child also presents same identity.
    4.. W2 runs Consumer_subscribe which runs/mutates on rk handle.
  4. W1's suspended poll resumes and touches the mutated rk and crashs.

Can we check if this workflow should be fixed?

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 this will break because task is outliving the callback. This can also happen in sync consumers if user starts some threads from within the callback. We should document that starting threads/tasks from within a callback is not recommended. I am not saying this can't be fixed but it can be taken as a future goal to fix maybe, if a requirement comes. In the current version of python client as well, the issue persists because there is no serialization at all so we are not breaking something that was supported. It's just that we are not supporting the serialization of consumer calls in all the cases, which should be fine.

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.
Lets verify this is issue with GIL mode also. If no, we might need to fix this in upcoming PRs.

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.

I pushed a fix for this. I have now introduced a new field called Invocation that will be set in context and instead of its value, its reference will be passed on to the child tasks. So when a callback is complete, it can update this object and then while executing the child tasks (who will also have the value updated), we can check if we want to treat it as a re-entrant call or a separate top-level call.

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.

Have reverted the fix based on Emanuele's suggestion. It will be part of a separate PR later.

"""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
Expand All @@ -38,7 +42,12 @@
-- 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)
Expand All @@ -48,43 +57,55 @@
_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:
contextvars only propagate into a ThreadPoolExecutor worker when that
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:
Expand Down Expand Up @@ -112,14 +133,14 @@

# 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.
# TODO NOGIL: Add support for concurrent and un-awaited calls
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)
Expand Down
6 changes: 3 additions & 3 deletions src/confluent_kafka/aio/producer/_AIOProducer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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.

Should we call Producer.close() in AIOProducer.close()?

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. It is a pre-existing bug that I am not planning to fix in this PR as it will require more testing.

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.

Since rk is leaking after application is closed, seems like it will be one time leak so severity is low. We should check in future PRs if this can be fixed and free threading is compatible for fix.

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
Expand Down
29 changes: 27 additions & 2 deletions src/confluent_kafka/src/Producer.c
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@
if (total_timeout_ms >= 0 && total_timeout_ms < CHUNK_TIMEOUT_MS) {
r = rd_kafka_poll(self->rk, total_timeout_ms);
} else {
while (1) {

Check warning on line 387 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Reduce the number of nested "break" statements from 3 to 1 authorized.

[S924] Loops should not have more than one "break" or "goto" statement See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=4732328f-b45f-49fa-8e91-e6d6db4b630f&open=4732328f-b45f-49fa-8e91-e6d6db4b630f
/* Calculate timeout for this chunk */
chunk_timeout_ms = calculate_chunk_timeout(
total_timeout_ms, chunk_count, CHUNK_TIMEOUT_MS);
Expand Down Expand Up @@ -502,7 +502,7 @@
* means all messages that were queued at that point have been
* delivered. Note: Messages produced after flush() starts are
* not included in the current flush. */
while (1) {

Check warning on line 505 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Reduce the number of nested "break" and "goto" statements from 5 to 1 authorized.

[S924] Loops should not have more than one "break" or "goto" statement See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=956107c8-27d8-459c-8f39-24b14917b17b&open=956107c8-27d8-459c-8f39-24b14917b17b
/* Calculate timeout for this chunk */
chunk_timeout_ms = calculate_chunk_timeout(
total_timeout_ms, chunk_count, CHUNK_TIMEOUT_MS);
Expand Down Expand Up @@ -560,15 +560,18 @@
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)
Py_RETURN_TRUE;

/* Calling close() reentrantly from within a callback
* is not supported and will deadlock here.
* TODO NOGIL: Update documentation to highlight this.
*/

Check warning on line 574 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Complete the task associated to this "TODO" comment.

[S1135] Track uses of "TODO" tags See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=cfa40e51-402c-4816-9b04-8a963549338b&open=cfa40e51-402c-4816-9b04-8a963549338b

/* If there are concurrent calls to close(), only one of them can
* destroy rk, the rest wait here for the winner to finish
Expand All @@ -580,7 +583,7 @@
#ifdef _WIN32
Sleep(100);
#else
usleep(100000);

Check warning on line 586 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Remove use of this obsolete "usleep" function. Replace it by a call to "nanosleep" or "setitimer".

[S1911] Obsolete POSIX functions should not be used See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=fa126f39-8c76-4156-9adc-313d922e2b2d&open=fa126f39-8c76-4156-9adc-313d922e2b2d
#endif
if (!CallState_end(self, &cs))
return NULL;
Expand All @@ -604,14 +607,14 @@
/* Signal in-flight calls to stop, and wait for them to finish
* using self->rk before destroying it -- see Handle_enter_rk_use().
* New calls will see `closing` and fail with ERR_MSG_PRODUCER_CLOSED. */
/* TODO NOGIL: replace this poll loop with a mutex/condvar wait so
* close() unblocks immediately instead of up to 100ms late. */

Check warning on line 611 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Complete the task associated to this "TODO" comment.

[S1135] Track uses of "TODO" tags See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=2a37e6ab-24a9-46dc-9039-17b7ad57a1bf&open=2a37e6ab-24a9-46dc-9039-17b7ad57a1bf
while (atomic_int_get(&self->active_calls) > 0) {
CallState_begin(self, &cs);
#ifdef _WIN32
Sleep(100);
#else
usleep(100000);

Check warning on line 617 in src/confluent_kafka/src/Producer.c

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Remove use of this obsolete "usleep" function. Replace it by a call to "nanosleep" or "setitimer".

[S1911] Obsolete POSIX functions should not be used See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=e54c6b0a-ae96-403d-a61f-588a5e5da3de&open=e54c6b0a-ae96-403d-a61f-588a5e5da3de
#endif
if (!CallState_end(self, &cs)) {
/* Abort the attempt: rk was never touched, so
Expand All @@ -625,6 +628,22 @@

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);

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.

-1 means an infinite deadline. librdkafka's abort ends with an EndTxn round-trip to the coordinator, which waits on that infinite deadline which blocks forever. Should we add resonable timeout?

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.

In Java, when we call producer.close() without timeout, it blocks indefinitely on aborting the tx (if broker is not reachable), which is the what above change also does. But Java does provide an option to set timeout for close (which librdkafka does not support). Do you think setting 60s of timeout would be fine?

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.

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.

On Emaneule's suggestion, I double checked the Java behaviour - the abort_tx call inside close waits indefinitely if broker is not reachable. So it should be fine to keep -1 as timeout here.

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);

Expand All @@ -635,6 +654,12 @@
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,
Expand Down Expand Up @@ -1095,8 +1120,8 @@
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;

Expand Down
49 changes: 37 additions & 12 deletions tests/concurrency/test_producer_close_race.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -48,9 +48,9 @@
def run_worker():
try:
start_barrier.wait()
worker(producer)

Check warning on line 51 in tests/concurrency/test_producer_close_race.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Add a parameter to function "run_worker" and use variable "producer" as its default value;The value of "producer" might change at the next loop iteration.

[S1515] Functions and lambdas should not reference variables defined in enclosing loops See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=2dce8415-3730-45ff-addf-cdcae5f1e6c7&open=2dce8415-3730-45ff-addf-cdcae5f1e6c7
except Exception as e: # noqa: BLE001 - want to see any exception, not just crashes

Check warning on line 52 in tests/concurrency/test_producer_close_race.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Fix the syntax of this issue suppression comment.

[S7632] Issue suppression comment should have the correct format See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=e8227bc4-7e44-4dc7-a572-4c5d1e9fabc7&open=e8227bc4-7e44-4dc7-a572-4c5d1e9fabc7
errors.append((i, e))

Check warning on line 53 in tests/concurrency/test_producer_close_race.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Add a parameter to function "run_worker" and use variable "i" as its default value;The value of "i" might change at the next loop iteration.

[S1515] Functions and lambdas should not reference variables defined in enclosing loops See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=e8f056ae-2058-442a-895b-6eb9b7388bd6&open=e8f056ae-2058-442a-895b-6eb9b7388bd6

threads = [threading.Thread(target=run_worker, daemon=True) for _ in range(num_workers)]
for t in threads:
Expand Down Expand Up @@ -145,15 +145,18 @@

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:
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)

Expand All @@ -169,6 +172,12 @@
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)

Expand All @@ -180,10 +189,15 @@
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)

Expand All @@ -194,15 +208,16 @@

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)
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)

Expand All @@ -220,10 +235,20 @@
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)

Expand Down Expand Up @@ -256,7 +281,7 @@
start_barrier = threading.Barrier(num_workers + 1)

def worker():
start_barrier.wait()

Check warning on line 284 in tests/concurrency/test_producer_close_race.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Add a parameter to function "worker" and use variable "start_barrier" as its default value;The value of "start_barrier" might change at the next loop iteration.

[S1515] Functions and lambdas should not reference variables defined in enclosing loops See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=9c43299f-66d0-46bc-9194-d8c3ea91a57d&open=9c43299f-66d0-46bc-9194-d8c3ea91a57d
all_results.append(producer.close())

# Daemon: if close() itself ever hangs (e.g. a deadlock), the
Expand Down Expand Up @@ -312,7 +337,7 @@

t.join(timeout=10)
assert not t.is_alive(), "poll() thread did not finish after close()"
assert poll_finished_at is not None, "poll() never finished"

Check failure on line 340 in tests/concurrency/test_producer_close_race.py

View check run for this annotation

SonarQube-Confluent / SonarQube Code Analysis

Remove this identity check; it will always be False.

[S5727] Comparison to None should not be constant See more on https://sonarqube.confluent.io/project/issues?id=confluent-kafka-python&pullRequest=2329&issues=cecf8900-bf2b-4310-896c-aac9f93e139b&open=cecf8900-bf2b-4310-896c-aac9f93e139b
assert close_duration < 0.5, (
f"close() took {close_duration:.2f}s to complete while poll(-1) was "
f"in progress -- expected it to finish within 0.5s"
Expand Down
Loading
Loading