← Back to Pull requests

Report oauth_cb failures to librdkafka and fail construction fast #2441

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 14, 2026 09:03 UTC
Author

What
----
Three problems with oauth_cb failures:

1. When oauth_cb returned something other than a (token, expiry[, principal, extensions]) tuple, or one of its extensions could not be converted, the C oauth_cb() left the TypeError set on librdkafka's background thread and never told librdkafka. librdkafka only schedules another token refresh once a token or a failure is set (rd_kafka_oauthbearer_enqueue_token_refresh_if_necessary()), so after one such return the client never asked for a token again. A raised exception was reported with rd_kafka_oauthbearer_set_token_failure(), but as "OAuth callback raised exception", without its message.
2. wait_for_oauth_token_set(), which the client constructors call, only watched for a token. A client whose oauth_cb failed during construction slept the full 10 seconds and raised OAuth token not set within 10 seconds timeout, although librdkafka retries a failed refresh only 10 seconds later. It also slept in steps of a second, so creating any client with an oauth_cb took at least a second, and it ignored Ctrl+C: the KeyboardInterrupt stayed set until the token came, and the constructor then failed with SystemError: ... returned a result with an exception set.
3. When the construction failed, destroying a Consumer or ShareConsumer ran the consumer close. The close served the queued _AUTHENTICATION error to error_cb while the constructor's KafkaException was set, so with an error_cb, the constructor raised SystemError: <built-in method append of list object at ...> returned a result with an exception set instead. This is the latent bug that test_share_consumer_oauth_expired_token_surfaces_error_cb in tests/integration/share_consumer_oauth/test_oauth_integration.py is skipped for.

With this change:

1. Every failure (exception, invalid return value, extension that can't be converted, token rejected by librdkafka) is reported with rd_kafka_oauthbearer_set_token_failure() as oauth_cb failed: <type>: <message>, and the exception is then cleared. librdkafka retries 10 seconds later, and error_cb gets _AUTHENTICATION: Failed to acquire SASL OAUTHBEARER token: oauth_cb failed: TypeError: expect returned value from oauth_cb to be .... The extension strings already converted when a later one fails are now freed; they leaked.
2. wait_for_oauth_token_set() checks every 100 ms with Handle_sleep(). As soon as oauth_cb has failed, it raises KafkaException with the same code as before, SASL_AUTHENTICATION_FAILED, and the callback's error: Failed to acquire SASL OAUTHBEARER token: oauth_cb failed: RuntimeError: .... It also returns when a signal handler raises. The 10 second timeout is unchanged.
3. A Consumer or ShareConsumer whose construction fails is destroyed with RD_KAFKA_DESTROY_F_NO_CONSUMER_CLOSE: it never subscribed, so the close only served callbacks. Producer and AdminClient don't serve callbacks when destroyed. The Consumer's queue is destroyed before the handle, as librdkafka requires and as Consumer_close() does; it was left for dealloc, and leaked when __init__ was called again.
4. common_conf_setup() clears the token state before rd_kafka_new(), so that a client initialized again after a failed construction waits for its own token instead of failing with the first one's error.

Checklist
------------------

  • Contains customer facing changes? Including API/behavior changes

  • - A client whose oauth_cb fails during construction now raises right away, with the callback's error in the message, instead of after 10 seconds with a timeout message. The KafkaError code is unchanged. Creating a client with a working oauth_cb takes about 0.1 s instead of 1 s. CHANGELOG entry under Unreleased, which also says that the text of the callback's exception reaches librdkafka's log, and that error_cb gets an _AUTHENTICATION error for each failed refresh when that text changes every time.
  • Did you add sufficient unit test and/or integration test coverage for this PR?

  • - New tests in tests/test_oauth_cb.py:
    - test_oauth_cb_token_refresh_invalid_return: a refresh returning an invalid value is reported to librdkafka, and error_cb gets the callback's error. librdkafka's next refresh, 10 seconds after a failure, is not waited for.
    - test_oauth_cb_failure_fails_construction_with_its_error: Consumer, Producer, AdminClient and ShareConsumer, each with an error_cb and an oauth_cb that raises or returns an invalid value, raise the callback's error, and error_cb is not called.
    - test_oauth_cb_failed_init_does_not_fail_the_next_one: a second __init__ after a failed one waits for its own token.
    - test_oauth_cb_token_wait_is_interruptible: Ctrl+C during the wait raises KeyboardInterrupt.

    References
    ----------

  • tests/integration/share_consumer_oauth/test_oauth_integration.py::test_share_consumer_oauth_expired_token_surfaces_error_cb was skipped for the SystemError of point 3, and runs again. Its oauth_cb now gives librdkafka an expiry in the future, so that only the broker rejects the expired token; with this PR, librdkafka's rejection of the expired token would fail the construction first. I could not run the integration tests (no broker here).
  • Test & Review
    ------------

  • CPython 3.11.16 and 3.14.7t, librdkafka 2.16.0, Linux x86_64.

  • On master, the first 10 new tests fail on both:

  • - the construction cases take 10 s, and a Consumer or ShareConsumer whose callback raises then fails with the SystemError;
    - the refresh test's error_cb never gets the error;
    - the interrupt test gets the SystemError.
  • test_oauth_cb_failed_init_does_not_fail_the_next_one, added after review, fails on master at its first __init__ (timeout error instead of the callback's), and failed at its second __init__ (the first one's error) before common_conf_setup() cleared the token state.

  • With this branch, the 21 tests of tests/test_oauth_cb.py pass on both. The existing test_oauth_cb_failure and the ShareConsumer OAuth tests in tests/test_ShareConsumer_callbacks.py still pass. test_oauth_cb_malformed_return_fails_construction checks that the message mentions the token or SASL, and it still does.

  • The new and changed tests of tests/test_oauth_cb.py passed 40 of 40 runs on each, 3 at a time on one CPU, each run with a different PYTHONHASHSEED.

  • valgrind, with a Consumer initialized again after a failed construction: 216 bytes definitely lost from rd_kafka_queue_get_consumer() in Consumer_init when the queue was left for dealloc, none now.

  • Construction time with an oauth_cb that returns a token right away, 3 runs each: 1.00 s on master for Producer, AdminClient and Consumer, 0.10 s with this branch.

  • tests/test_*.py and tests/concurrency: 648 passed and 5 skipped on 3.11. On 3.14t, 487 passed, 7 skipped and 2 failed, plus 3 collection errors, all from my environment: the 2 tests/test_unasync.py tests need isort, and tests/test_log.py, tests/test_Producer.py and tests/test_serializer_error.py need urllib3, which my 3.14t environment lacks. tests/test_kafka_error.py::test_kafkaError_unknown_error was deselected there: with that environment's pluggy it stops the whole run, which https://github.com/confluentinc/confluent-kafka-python/pull/2444 fixes.

  • tools/style-format.sh and flake8 pass on the test files. clang-format 18.1.3 reports no differences in the changed C lines, and neither gcc (with the build's flags) nor clang -Wall -Wextra warns about them.

  • Merges without conflicts with master and with my other open pull requests, except for CHANGELOG.md conflicts with https://github.com/confluentinc/confluent-kafka-python/pull/2425 and https://github.com/confluentinc/confluent-kafka-python/pull/2429, which this PR already had before the review changes; Consumer.c, ShareConsumer.c and confluent_kafka.h merge cleanly.
  • Open questions / Follow-ups
    --------------------------

  • The wait counts its 100 ms steps toward the 10 seconds, as it counted seconds before. Once #2429 is merged, it could measure the time with the monotonic clock that #2429 adds.
  • 🤖 Generated with Claude Code

    https://claude.ai/code/session_01GwUvhmzgfkiZ6vo4uGyesN

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: pylaterreur Review duration: 10212m
    All Vouch review confidence checks passed
    Residual risk 0.42 = Change Risk (0.75) × (1 − Review Confidence (0.44)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.75 · 650 lines diff across 8 files
    0.75
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    44%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Sensitive Paths sensitive_paths
    0.075
    Real PR Conversation Timeline
    1 comments
    "Review active on #2441"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 44.2% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 75.2% (HIGH) · Higher = larger blast radius
    75.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 44.2% · Lower = rushed or shallow review
    44.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 42.0% · Moderate risk
    42.0%