Repository navigation
[NOGIL] Improve Test Coverage for Producer + Some Edge Case Fixes #2329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
3e4e603
b601bce
4fcd01d
62ceaa7
b2aa8b0
84480fc
c50df19
503a4b2
3b039de
f75dba3
42b40cc
79fe726
f0ed844
ff95c4e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we call Producer.close() in AIOProducer.close()?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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
|
||
| /* Calculate timeout for this chunk */ | ||
| chunk_timeout_ms = calculate_chunk_timeout( | ||
| total_timeout_ms, chunk_count, CHUNK_TIMEOUT_MS); | ||
|
|
@@ -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
|
||
| /* Calculate timeout for this chunk */ | ||
| chunk_timeout_ms = calculate_chunk_timeout( | ||
| total_timeout_ms, chunk_count, CHUNK_TIMEOUT_MS); | ||
|
|
@@ -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
|
||
|
|
||
| /* If there are concurrent calls to close(), only one of them can | ||
| * destroy rk, the rest wait here for the winner to finish | ||
|
|
@@ -580,7 +583,7 @@ | |
| #ifdef _WIN32 | ||
| Sleep(100); | ||
| #else | ||
| usleep(100000); | ||
|
Check warning on line 586 in src/confluent_kafka/src/Producer.c
|
||
| #endif | ||
| if (!CallState_end(self, &cs)) | ||
| return NULL; | ||
|
|
@@ -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
|
||
| 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
|
||
| #endif | ||
| if (!CallState_end(self, &cs)) { | ||
| /* Abort the attempt: rk was never touched, so | ||
|
|
@@ -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); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To check with Emanuele Sabellico (@emasab)
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
|
|
||
|
|
@@ -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, | ||
|
|
@@ -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; | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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.
Application workflow
4.. W2 runs Consumer_subscribe which runs/mutates on rk handle.
Can we check if this workflow should be fixed?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.