Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
## Unreleased

### Fixes
- Fix crashes in `Producer.produce(headers=...)` and `Producer.produce_batch()` when Python
code they run while converting the headers or the messages, such as a header key's
`__str__()`, changed the list or dict being converted. Like the other methods that take
a list, such as `Consumer.subscribe()` and the ones taking `TopicPartition` lists, they
now convert a copy of it with the GIL too, not only on free-threaded Python.
`ShareConsumer.subscribe()` now converts a copy on both.
- Fix `AvroDeserializer` rejecting messages of 5 bytes or fewer when the schema GUID is
sent in a header (`header_schema_id_serializer`), for example `int` keys or short
strings. The length check now runs where the schema id framing is parsed, so it
Expand Down
6 changes: 0 additions & 6 deletions src/confluent_kafka/src/Consumer.c
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ Consumer_subscribe(Handle *self, PyObject *args, PyObject *kwargs) {
PyObject *result = NULL;
Py_ssize_t pos = 0;
rd_kafka_resp_err_t err;
#ifdef Py_GIL_DISABLED
PyObject *owned_tlist = NULL;
#endif

if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOO", kws, &tlist,
&on_assign, &on_revoke, &on_lost))
Expand Down Expand Up @@ -151,12 +149,10 @@ Consumer_subscribe(Handle *self, PyObject *args, PyObject *kwargs) {
goto done;
}

#ifdef Py_GIL_DISABLED
owned_tlist = PyList_GetSlice(tlist, 0, PY_SSIZE_T_MAX);
if (!owned_tlist)
goto done;
tlist = owned_tlist;
#endif

topics = rd_kafka_topic_partition_list_new((int)PyList_Size(tlist));
for (pos = 0; pos < PyList_Size(tlist); pos++) {
Expand Down Expand Up @@ -219,9 +215,7 @@ Consumer_subscribe(Handle *self, PyObject *args, PyObject *kwargs) {
result = Py_None;

done:
#ifdef Py_GIL_DISABLED
Py_XDECREF(owned_tlist);
#endif
Handle_serialize_exit(self);
return result;
}
Expand Down
8 changes: 1 addition & 7 deletions src/confluent_kafka/src/Producer.c
Original file line number Diff line number Diff line change
Expand Up @@ -896,9 +896,7 @@ Producer_produce_batch(Handle *self, PyObject *args, PyObject *kwargs) {
int message_cnt = 0;
int good = 0;
rd_kafka_topic_t *rkt = NULL;
#ifdef Py_GIL_DISABLED
PyObject *owned_messages = NULL;
#endif
PyObject *owned_messages = NULL;

static char *kws[] = {"topic", "messages", "partition",
"callback", "on_delivery", NULL};
Expand Down Expand Up @@ -929,15 +927,13 @@ Producer_produce_batch(Handle *self, PyObject *args, PyObject *kwargs) {
if (!Producer_rk_use_begin(self))
return NULL;

#ifdef Py_GIL_DISABLED
owned_messages = PyList_GetSlice(messages_list, 0, PY_SSIZE_T_MAX);
if (!owned_messages)
goto cleanup;
messages_list = owned_messages;
message_cnt = (int)PyList_Size(messages_list);
if (message_cnt == 0)
goto cleanup;
#endif

/* Allocate arrays for librdkafka messages and msgstates */
rkmessages = calloc(message_cnt, sizeof(*rkmessages));
Expand Down Expand Up @@ -977,9 +973,7 @@ Producer_produce_batch(Handle *self, PyObject *args, PyObject *kwargs) {
if (msgstates)
free(msgstates);

#ifdef Py_GIL_DISABLED
Py_XDECREF(owned_messages);
#endif

if (PyErr_Occurred())
return NULL;
Expand Down
11 changes: 10 additions & 1 deletion src/confluent_kafka/src/ShareConsumer.c
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ static void ShareConsumer_PyErr_from_error_destroy(rd_kafka_error_t *error) {
static PyObject *ShareConsumer_subscribe(ShareConsumerHandle *self,
PyObject *args,
PyObject *kwargs) {
PyObject *tlist;
PyObject *tlist, *owned_tlist;
static char *kws[] = {"topics", NULL};
rd_kafka_topic_partition_list_t *c_topics;
rd_kafka_resp_err_t err;
Expand All @@ -216,6 +216,13 @@ static PyObject *ShareConsumer_subscribe(ShareConsumerHandle *self,
return NULL;
}

/* Iterate a snapshot of the list, as Consumer.subscribe() does:
* str() of an item can run Python code that changes the list, and
* so can another thread. */
if (!(owned_tlist = PyList_GetSlice(tlist, 0, PY_SSIZE_T_MAX)))
return NULL;
tlist = owned_tlist;

/* Build partition list from topic name strings */
c_topics = rd_kafka_topic_partition_list_new((int)PyList_Size(tlist));
for (i = 0; i < PyList_Size(tlist); i++) {
Expand All @@ -225,6 +232,7 @@ static PyObject *ShareConsumer_subscribe(ShareConsumerHandle *self,
PyErr_SetString(PyExc_TypeError,
"expected list of unicode strings");
rd_kafka_topic_partition_list_destroy(c_topics);
Py_DECREF(owned_tlist);
return NULL;
}
/* TODO KIP-932: cfl_PyUnistr_AsUTF8 can return NULL; passing
Expand All @@ -237,6 +245,7 @@ static PyObject *ShareConsumer_subscribe(ShareConsumerHandle *self,
Py_XDECREF(uo8);
Py_DECREF(uo);
}
Py_DECREF(owned_tlist);

err = rd_kafka_share_subscribe(self->rkshare, c_topics);

Expand Down
30 changes: 1 addition & 29 deletions src/confluent_kafka/src/confluent_kafka.c
Original file line number Diff line number Diff line change
Expand Up @@ -1935,22 +1935,18 @@ PyObject *c_share_partition_offsets_list_to_py_dict(
rd_kafka_topic_partition_list_t *py_to_c_parts(PyObject *plist) {
rd_kafka_topic_partition_list_t *c_parts;
size_t i;
#ifdef Py_GIL_DISABLED
PyObject *owned_plist = NULL;
#endif

if (!PyList_Check(plist)) {
PyErr_SetString(PyExc_TypeError,
"requires list of TopicPartition");
return NULL;
}

#ifdef Py_GIL_DISABLED
owned_plist = PyList_GetSlice(plist, 0, PY_SSIZE_T_MAX);
if (!owned_plist)
return NULL;
plist = owned_plist;
#endif

c_parts = rd_kafka_topic_partition_list_new((int)PyList_Size(plist));

Expand All @@ -1963,9 +1959,7 @@ rd_kafka_topic_partition_list_t *py_to_c_parts(PyObject *plist) {
PyErr_Format(PyExc_TypeError, "expected %s",
TopicPartitionType.tp_name);
rd_kafka_topic_partition_list_destroy(c_parts);
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_plist);
#endif
return NULL;
}

Expand All @@ -1983,9 +1977,7 @@ rd_kafka_topic_partition_list_t *py_to_c_parts(PyObject *plist) {
}
}

#ifdef Py_GIL_DISABLED
Py_DECREF(owned_plist);
#endif
return c_parts;
}

Expand Down Expand Up @@ -2111,12 +2103,10 @@ py_header_to_c(rd_kafka_headers_t *rd_headers, PyObject *key, PyObject *value) {
static rd_kafka_headers_t *py_headers_list_to_c(PyObject *hdrs) {
int i, len;
rd_kafka_headers_t *rd_headers = NULL;
#ifdef Py_GIL_DISABLED
PyObject *owned_hdrs = PyList_GetSlice(hdrs, 0, PY_SSIZE_T_MAX);
if (!owned_hdrs)
return NULL;
hdrs = owned_hdrs;
#endif

len = (int)PyList_Size(hdrs);
rd_headers = rd_kafka_headers_new(len);
Expand All @@ -2129,24 +2119,18 @@ static rd_kafka_headers_t *py_headers_list_to_c(PyObject *hdrs) {
PyErr_SetString(PyExc_TypeError,
"Headers are expected to be a "
"list of (key, value) tuples");
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_hdrs);
#endif
return NULL;
}

if (!py_header_to_c(rd_headers, PyTuple_GET_ITEM(tuple, 0),
PyTuple_GET_ITEM(tuple, 1))) {
rd_kafka_headers_destroy(rd_headers);
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_hdrs);
#endif
return NULL;
}
}
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_hdrs);
#endif
return rd_headers;
}

Expand All @@ -2159,12 +2143,10 @@ static rd_kafka_headers_t *py_headers_dict_to_c(PyObject *hdrs) {
Py_ssize_t pos = 0;
rd_kafka_headers_t *rd_headers = NULL;
PyObject *ko, *vo;
#ifdef Py_GIL_DISABLED
PyObject *owned_hdrs = PyDict_Copy(hdrs);
if (!owned_hdrs)
return NULL;
hdrs = owned_hdrs;
#endif

len = (int)PyDict_Size(hdrs);
rd_headers = rd_kafka_headers_new(len);
Expand All @@ -2173,16 +2155,12 @@ static rd_kafka_headers_t *py_headers_dict_to_c(PyObject *hdrs) {

if (!py_header_to_c(rd_headers, ko, vo)) {
rd_kafka_headers_destroy(rd_headers);
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_hdrs);
#endif
return NULL;
}
}

#ifdef Py_GIL_DISABLED
Py_DECREF(owned_hdrs);
#endif
return rd_headers;
}

Expand Down Expand Up @@ -2709,33 +2687,27 @@ oauth_cb(rd_kafka_t *rk, const char *oauthbearer_config, void *opaque) {
}

if (extensions) {
#ifdef Py_GIL_DISABLED
PyObject *owned_extensions = PyDict_Copy(extensions);
if (!owned_extensions) {
Py_DECREF(result);
goto err;
}
extensions = owned_extensions;
#endif
extensions = owned_extensions;
int len = (int)PyDict_Size(extensions);
rd_extensions = (char **)malloc(2 * len * sizeof(char *));
Py_ssize_t pos = 0;
PyObject *ko, *vo;
while (PyDict_Next(extensions, &pos, &ko, &vo)) {
if (!py_extensions_to_c(rd_extensions,
rd_extensions_size, ko, vo)) {
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_extensions);
#endif
Py_DECREF(result);
free(rd_extensions);
goto err;
}
rd_extensions_size = rd_extensions_size + 2;
}
#ifdef Py_GIL_DISABLED
Py_DECREF(owned_extensions);
#endif
}

err_code = rd_kafka_oauthbearer_set_token(
Expand Down
66 changes: 66 additions & 0 deletions tests/concurrency/test_memory_safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,72 @@ def test_produce_headers_list_races_mutation():
_race(lambda s: producer.produce('memref', value=b'value', headers=s), _headers(), _churn(_headers))


# The parse loops can also run Python code that changes the list or dict while
# it is being converted, with or without the GIL: below, the first such call
# clears it. Iterating the caller's container then went on with a stale count
# and borrowed items, and segfaulted on GIL builds.


@subprocess_isolated
def test_produce_headers_list_cleared_by_key_str():
"""py_headers_list_to_c() calls str() on each header key."""
headers = []

class ClearListOnStr:
def __str__(self):
headers.clear()
return 'k0'

headers.extend([(ClearListOnStr(), b'v0')] + [('k%d' % i, b'v%d' % i) for i in range(1, 8)])
Producer(_CONF).produce('memref', value=b'value', headers=headers)
assert not headers


@subprocess_isolated
def test_produce_headers_dict_cleared_by_key_str():
"""py_headers_dict_to_c() calls str() on each header key: the value of that
header must stay alive while the dict is cleared."""
events = []
headers = {}

class Value(bytes):
def __del__(self):
events.append('value released')

class ClearDictOnStr:
def __str__(self):
headers.clear()
events.append('dict cleared')
return 'k1'

headers[ClearDictOnStr()] = Value(b'v1')
headers['k2'] = b'v2'
Producer(_CONF).produce('memref', value=b'value', headers=headers)
assert events == ['dict cleared', 'value released']


@subprocess_isolated
def test_produce_batch_list_cleared_by_message_key_eq():
"""Producer_validate_and_parse_batch() looks up the fields of each message
dict, which calls __eq__ of a key with the same hash as the field name."""
messages = []

class ClearListOnEq:
def __hash__(self):
return hash('value')

def __eq__(self, other):
messages.clear()
return False

first = {ClearListOnEq(): None}
first['value'] = b'v0'
messages.extend([first] + [{'value': b'v%d' % i} for i in range(1, 8)])
del first
Producer(_CONF).produce_batch('memref', messages)
assert not messages


###############################################################################
# AdminClient
###############################################################################
Expand Down
15 changes: 15 additions & 0 deletions tests/test_ShareConsumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ def test_subscribe_multiple_topics(share_consumer):
assert sorted(share_consumer.subscription()) == ['topic-a', 'topic-b', 'topic-c']


def test_subscribe_list_cleared_by_topic_str(share_consumer):
"""subscribe() subscribes to the list as it was passed, even when str() of a
topic runs Python code that changes the list."""
topics = []

class ClearListOnStr:
def __str__(self):
topics.clear()
return 'topic-a'

topics.extend([ClearListOnStr(), 'topic-b', 'topic-c'])
share_consumer.subscribe(topics)
assert sorted(share_consumer.subscription()) == ['topic-a', 'topic-b', 'topic-c']


def test_subscribe_idempotent_and_incremental(share_consumer):
"""Re-subscribing to the same set is idempotent, growing the topic list
grows the subscription, and a repeated unsubscribe() is a harmless no-op.
Expand Down