From 501c877c9d627f5809694ddebb9507eb306e0b5b Mon Sep 17 00:00:00 2001 From: BNCMK Date: Fri, 7 Aug 2026 22:06:08 -0700 Subject: [PATCH] Release the whole broker when thread creation fails rd_free(rkb) frees the outer struct only. Everything rd_kafka_broker_destroy_final() would release is abandoned with it: rkb_origname, rkb_ApiVersions, the ops queue, six rd_avg structures, the locks and condition variables, and the two references taken above. Unwind through the destructor instead. It asserts it runs on the broker's own thread, which was never created here, so the assertion fires on an uninitialised handle. At this point the broker is not on rk_brokers and nothing else can reach it, so the calling thread is its only owner; recording that makes the assertion true rather than bypassed. Both references drop, the count reaches zero, and the destructor releases everything including the pipe, so the explicit closes are no longer needed and are removed. Refs #4456 --- src/rdkafka_broker.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/rdkafka_broker.c b/src/rdkafka_broker.c index d8e5c48e81..de8ced952f 100644 --- a/src/rdkafka_broker.c +++ b/src/rdkafka_broker.c @@ -5449,7 +5449,29 @@ rd_kafka_broker_t *rd_kafka_broker_add(rd_kafka_t *rk, rd_kafka_op_err(rk, RD_KAFKA_RESP_ERR__CRIT_SYS_RESOURCE, "Unable to create broker thread"); - rd_free(rkb); + /* Unwind through the destructor rather than by hand. + * + * rd_free() releases the struct without running + * rd_kafka_broker_destroy_final(), so the wake-up pipe opened + * above is never closed and the two descriptors stay open for + * the life of the process with nothing left holding their + * numbers. It also bypasses the refcount, leaving the two + * references taken here unaccounted for. + * + * At this point the broker is not yet on rk_brokers and nothing + * else can reach it, so dropping both references takes the count + * to zero and runs the destructor, which closes the pipe, tears + * down the locks and queues, and frees the struct. */ + /* The destructor asserts it runs on the broker's own thread, + * which is how it is reached in every other case. That thread + * was never created, and no other thread can reach this broker + * because it is not yet on rk_brokers, so this thread is the one + * that owns it. Recording that makes the assertion true rather + * than bypassed. */ + rkb->rkb_thread = thrd_current(); + + rd_kafka_broker_destroy(rkb); /* broker thread's refcnt */ + rd_kafka_broker_destroy(rkb); /* rk_broker's refcnt */ #ifndef _WIN32 /* Restore sigmask of caller */