Skip to content

feat(auth): add OIDC and rotating bearer tokens - #165

Merged
glasstiger merged 83 commits into
mainfrom
ia_oidc_auth
Nov 12, 2026
Merged

glasstiger merged 83 commits into
mainfrom
ia_oidc_auth

Conversation

@glasstiger

@glasstiger glasstiger commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds OIDC device-flow sign-in and rotating bearer-token authentication to the Python client. Interactive applications, including remote Jupyter notebooks, can sign in through a browser; unattended applications can supply credentials from Azure Identity, an OAuth2 client-credentials flow, or a secrets vault without rebuilding clients whenever a token rotates.

The new questdb.auth API uses the native client's authentication, caching, refresh and coordination logic, with Python renderers, token-source callbacks and PG-wire adapters.

What this adds

  • OIDC device flow: OidcDeviceAuth implements the OAuth 2.0 Device Authorization Grant (RFC 8628), with configuration discovered from QuestDB or supplied explicitly. It supports terminal and Jupyter prompts, optional QR codes, custom renderers, silent refresh and typed OidcError exceptions.
  • Rotating machine credentials: RefreshingTokenProvider wraps an application-defined token source with a shared native cache, proactive background refresh, bounded cold waits, refresh hints and backoff. Sources can return ExpiringToken, a (token, expires_at) tuple, or an SDK token with token and expires_on attributes. await_ready() and status expose readiness and fetch diagnostics without exposing credentials.
  • Application-managed providers: accept a callable returning a token, or an object implementing token() and optional on_rejected(). Shared providers coordinate acquisition across clients; eligible HTTP 401 responses can trigger a refresh and one retry with a replacement token.
  • Transport integration: add oidc_auth= and bearer_token_provider= to questdb.connect, QuestDB.from_conf, Sender, Sender.from_conf and Sender.from_env. Providers work with HTTP(S) and QWP/WebSocket, not TCP or UDP. They are mutually exclusive with each other and with fixed token, username or password credentials.
  • PG-wire adapters: sqlalchemy_engine supplies the current token as the _sso password for each new physical connection; psycopg_connect supplies it at connection time. Both accept OIDC and application token providers.
  • Structured failures: OidcError subclasses and TokenUnavailableError remain catchable as QuestDBError. The additive ConnectionEventKind.CredentialUnavailable distinguishes failure to obtain a credential from a server rejecting one (AuthFailed); existing event ordinals are unchanged.

Interactive sign-in

import questdb
from questdb.auth import OidcDeviceAuth

with OidcDeviceAuth.from_questdb("https://questdb.example.com:9000") as auth:
    auth.sign_in()
    with questdb.connect(
        "wss::addr=questdb.example.com:9000;", oidc_auth=auth
    ) as db:
        with db.query("select 1") as result:
            print(list(result.iter_rows()))

Rotating machine credentials

Wrap an application-defined fetch_token() returning a token and its expiry:

import questdb
from questdb.auth import RefreshingTokenProvider

with RefreshingTokenProvider(fetch_token) as tokens:
    with questdb.connect(
        "wss::addr=questdb.example.com:9000;",
        bearer_token_provider=tokens,
    ) as db:
        with db.sender() as sender:
            sender.row("events", columns={"value": 42}, at=questdb.ServerTimestamp)

The token-provider guide includes Azure Identity and OAuth2 client-credentials recipes. Cloud SDKs remain application dependencies; OIDC itself adds no mandatory Python dependency. SQLAlchemy, psycopg, IPython and QR support are loaded only when needed.

Lifecycle and security

  • Only sign_in() is interactive. Token reads, transport reconnects and PG pool connections never launch a sign-in prompt. Ctrl-C and cancel_sign_in() cancel an active attempt without retiring the provider; close() permanently closes it and terminates its attached clients' token acquisition.
  • Foreground retryability is not background termination. TokenUnavailableError.retryable controls foreground retry decisions; even a permanent token-unavailable failure does not stop background reconnects. To end them, close the provider, or have an application provider deliberately raise a plain QuestDBError with InvalidApiCall.
  • Persistence is opt-in. FileTokenStore stores plaintext credentials using atomic replacement and cross-process refresh coordination. Writes currently require POSIX storage with enforceable owner-only permissions; use in-memory authentication on other platforms. Discovery endpoints, browser targets, display text and credential diagnostics are validated or sanitized before use.
  • Protect bearer credentials in transit. Use https:: or wss::; plaintext transports warn rather than reject the configuration. PG adapters default to verify-full for remote hosts and reject destination or login overrides that could redirect the token. Numeric loopback addresses retain a local-development fallback.
  • Close clients before their providers and before interpreter exit. Token sources must bound their own I/O; RefreshingTokenProvider.close(wait=True, timeout=...) can drain an active fetch. Callback admission, shutdown draining, signal delivery and greenlet isolation protect the Python/native boundary. Providers and clients must not be carried across fork().

Compatibility notes

These affect existing APIs and are documented in the 6.1.0 (unreleased) changelog:

  1. Established QWP/WebSocket senders keep reconnecting after HTTP 401/403. They retain unacknowledged rows and report AuthFailed with capped backoff instead of becoming terminal. This also applies to fixed credentials. A waited-for initial connection still fails on rejection. Applications that want to stop an established sender must close it from their own code, outside its listener.
  2. A sender's own callbacks cannot drive that sender. The existing flush()/close() restrictions extend to row(), dataframe(), new_buffer(), establish() and transaction operations. Several native-backed getters also reject access during a native call. These refusals raise QuestDBError(InvalidApiCall); queue callback work or use another sender.
  3. Buffers reject cross-thread access while native code modifies them. Reads and writes fail with InvalidApiCall during a modifying flush or row-serializing DataFrame operation. A kept flush (clear=False) remains a read-only borrow and permits other readers.
  4. Query results reject same-thread re-entry while being read or decoded. Re-entrant close, cancel and batch pulls, including PooledReader.close(), raise InvalidApiCall. Close after the read returns or from another thread.
  5. Reserved provider configuration keys are rejected on every protocol. Remove token_provider, azure_resource, azure_client_id and azure_credential from configuration strings and pass the provider as a Python keyword argument instead.
  6. Sender subclasses see its attribute guard and instance dictionary. Use super().__setattr__ rather than object.__setattr__ on CPython 3.10–3.12, place attribute-hook mixins before Sender, and do not rely on subclass __slots__ to prevent new attributes.

Supporting changes

  • Make abandoned query-result, reader-lease and Arrow-stream cleanup safe around active native operations and garbage collection; preserve exception classes and metadata when annotating DataFrame failures.
  • Add authentication and token-provider guides, API/type-stub coverage and examples/oidc_device_auth.py.
  • Document the native client's request_durable_ack levels (local, replicated, local,replicated, plus on/off), server compatibility and the distinction between durable retention and ordinary acknowledgement waits.
  • Keep PyPy extension builds importable with Cython 3.3.1.

Testing

Regression coverage includes device polling and refresh failures, credential-safe rendering, token-store permissions and concurrent refresh, cancellation and signals, provider sharing and shutdown, HTTP/WebSocket authentication, query failover, callback re-entry, garbage collection and real PG-driver handshakes. Dedicated OIDC, PG capture and QWP failover servers exercise these paths locally. Provider entry points also have mypy coverage.

At head cd29d4f, all 31 reported checks pass, including:

  • Linux, macOS and Windows test pipelines, minimum-dependency and NumPy/pandas variants, and tests against released QuestDB versions and master.
  • The dedicated SQLAlchemy 1.4/psycopg2 adapter job; standard jobs install the modern SQLAlchemy/psycopg stack and optional QR dependencies where available.
  • Release-wheel builds across the configured CPython/PyPy platforms, including macOS arm64 and free-threaded CPython.
  • Gitleaks. The test pipeline also builds the Sphinx documentation with warnings treated as errors.

Native dependency

The c-questdb-client submodule is pinned to 2a443686 from questdb/c-questdb-client#228. Update the pin to the merged native main commit before merging this PR.

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

This pull request adds OIDC device authentication and rotating bearer-token providers to the Python client. It adds PostgreSQL adapters, callback and query-result lifecycle safeguards, examples, documentation, and tests for authentication, compatibility, and lifecycle behavior.

Changes: Authentication and client lifecycle

Layer / File(s) Summary
Authentication contracts and client wiring
src/questdb/_client.pyi, src/questdb/line_sender.pxd, src/questdb/__init__.py, src/questdb/_token_provider.py
Public declarations and client entry points accept OIDC authentication and bearer-token providers. Native connection declarations add OIDC and provider options.
Rotating bearer-token provider
src/questdb/token_provider.pxi, src/questdb/_token_provider.py, src/questdb/auth/_token_provider.py
The provider implementation validates token sources and expiry values, coordinates refresh and failures, exposes status and lifecycle methods, and adapts provider objects and callables.
OIDC device flow and token storage
src/questdb/auth/*, docs/auth.rst, docs/api.rst
OIDC modules add configuration and error types, file-token-store path handling, prompt rendering, and public authentication exports.
PG-wire adapters and OIDC example
src/questdb/auth/_adapters.py, examples/oidc_device_auth.py, examples.manifest.yaml
The adapters validate connection arguments and inject provider tokens into SQLAlchemy and psycopg connections. The example demonstrates sign-in, PostgreSQL queries, persistence, and sender use.
Callback, buffer, and query-result safeguards
src/questdb/_client_helper.*, src/questdb/dataframe.pxi, src/questdb/egress.pxi
The client adds callback admission and shutdown coordination, checks for re-entry during native operations, and attempts nonblocking query-result cleanup.
Integration tests and compatibility support
test/*, ci/*, setup.py, docs/*, CHANGELOG.rst
Fixtures and tests cover authentication, adapters, cursor cleanup, callbacks, buffer access, and typing. Build and CI settings add PyPy and legacy adapter coverage, and documentation describes the APIs and behavior.

Estimated code review effort: 4 (Complex) | ~70 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Application
  participant OidcDeviceAuth
  participant QuestDB
  participant Renderer
  participant ClientTransport
  Application->>OidcDeviceAuth: discover configuration and start sign-in
  OidcDeviceAuth->>QuestDB: request device authorization and tokens
  OidcDeviceAuth->>Renderer: display device authorization prompt
  Renderer-->>OidcDeviceAuth: report prompt status
  OidcDeviceAuth-->>Application: return authenticated provider
  Application->>ClientTransport: attach OIDC provider
  ClientTransport->>OidcDeviceAuth: obtain credentials
Loading

Possibly related issues

Suggested reviewers: kafka1991, mtopolnik, jerrinot

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 43.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the pull request’s main changes: OIDC authentication and rotating bearer-token support.
Full details: Docstring Coverage

Explanation

Docstring coverage is 43.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 105 functions across 27 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Comment thread test/test_auth.py Resolved
Comment thread test/test_auth.py Resolved
Native-backed OIDC device-flow sign-in and rotating Bearer-token
providers for the Python client (`questdb.auth`, `oidc_auth=`,
`bearer_token_provider=`), split out of #133 so the feature can be
reviewed against `main` without the unrelated fixes of #160.

The feature runs user callbacks (token providers, sign-in renderers)
inside native calls, so this also carries the re-entry guards from #160
that keep such a callback from using an object a native call holds:

- a sender rejects its methods while a native call borrows it, and
  from its own connection listener or error handler;
- a `Buffer` that a native call is modifying rejects reads and writes;
- a query cursor rejects same-thread re-entry during a native read,
  and finalizers reclaim cursors without blocking;
- a DataFrame error keeps its class when a note is appended, so
  `except OidcError` still matches.

Bumps c-questdb-client to the matching native change
(questdb/c-questdb-client#228).

The full history is on branch `ia_oidc_device_flow` (#133).
`RecordBatchReader.from_stream` and a dict argument to `pa.record_batch`
arrived in pyarrow 15, so ten OIDC tests failed on the linux-min-deps
job (pyarrow 14.0.1). Import the stream through `_import_from_c_capsule`
there, as `system_test.py` does, and build the batch from a list of
arrays.
`_OIDC_MAIN_THREAD_IDENT` came from `threading.main_thread().ident`,
which gevent's monkey-patching makes a greenlet id. On 64-bit Windows
that does not fit an `unsigned long`, so `import questdb` after
`monkey.patch_all()` raised OverflowError, failing `main`'s
`test_scoped_calls_from_greenlets_on_one_thread` on both Windows jobs.
Elsewhere it never matched the native `PyThread_get_thread_ident()` the
main-thread checks compare it with, so under gevent no thread counted
as the main one.

Read the native ident when `get_native_id()`, which gevent leaves
alone, says this is the main OS thread, and compare natively in
`_tp_on_main_thread` too. Without gevent nothing changes.
Bump c-questdb-client from a038a0a7 to b3e8f361: 7.2.0, merged from
main, and the OIDC branch's fixes since. Its new
`questdb_token_sink_set_terminal_error` lets an application provider
report a failure that retrying can never clear. Until now clients kept
retrying every failure of a Python provider in the background,
whatever its TokenUnavailableError said, so a provider that knew it
could never succeed kept its senders, queries and pools reconnecting
until the application closed them.

A provider now raises QuestDBError with code InvalidApiCall to stop
them, as a Rust provider returns `InvalidApiCall` and a C++ one throws
`questdb::error` with `invalid_api_call`: a QWP/WebSocket sender, query
or pool fails with ConfigError and stops reconnecting, and an ILP/HTTP
flush fails at once. A TokenUnavailableError keeps its classification
whatever its code. A RefreshingTokenProvider's source cannot report
one: its sink refuses it, so the exception counts as retryable like any
other, and closing the provider is what stops its clients.

The bump also brings:
- A RefreshingTokenProvider wrapped in a provider of one's own
  (`lambda: tokens.token()`) refreshes early on a 401 instead of
  handing the rejected token back until its scheduled refresh.
- A 401 re-fetch no longer takes the rejected token back from a fetch
  another connection started, and a forced refresh no longer logs
  under the provider's state lock, which could deadlock.
- A close drain, and a flush that waits out sf_append_deadline_millis
  on a full queue, name a failing reconnect when they time out, rather
  than reporting a bare timeout or advising a larger
  sf_max_total_bytes. An ACK-wait or close-drain timeout no longer
  carries a server rejection's sender_error, which marks a terminal
  error.

Document the terminal failure, and that ILP/HTTP calls the provider on
every flush, on the flushing thread. Test that each kind of client
stops on it, that a source's stays retryable, and that wrapped
refreshing providers refresh on a QWP/WebSocket or ILP/HTTP 401.
Bring in 6.0.0: row egress (iter_rows, columns), EXEC_DONE counts,
per-query timeouts, the UUID byte order, and QWP row auto-flush that
keeps frames within the frame cap.

Both branches reworked the same re-entry guards, so the conflicts are
resolved by combining them:

- Callback dispatch depths use main's native per-thread table. Our
  Python thread-local and its global fast-path counter are dropped.
- Sender.flush() keeps main's _flush_c_buf split. Our native-borrow
  guard and parked-signal delivery move into _flush_c_buf, which now
  takes the Buffer, so row() auto-flush publishes under them too.
- Sender.row() keeps our refusal from the sender's own callbacks
  whatever the auto-flush mode. Main's narrower per-row check is
  redundant and dropped; its docstring and docs/sender.rst follow.
- _CursorHandle takes main's pin/defer model and keeps our
  _native_in_flight / _check_not_driving guards and non-blocking
  finalizer reclaim. A busy reclaim now leaves the free to a pinned
  holder, which main's lease-finalised-mid-decode test needs.
  QueryResult.close() refuses same-thread re-entry but frees through
  _close(), so a close interrupted while it waits is finished by the
  worker. Main's row-stream pulls deliver parked OIDC signals like the
  other reader pulls.
- test_ci_wiring expects our OIDC CI extras in the minimum-versions run:
  none of them depends on a pinned package.

CHANGELOG: our entries move from the released 6.0.0 section to a new
6.1.0 (unreleased) section, worded against 6.0 instead of 5.0.
QWP/WebSocket row() reworded a failed auto-flush publish by calling the
exception's class with QuestDBError's positional signature. The classes
c_err_to_py now returns for token-provider and OIDC failures do not
share it. TokenUnavailableError, OidcDeviceFlowError and
OidcTimeoutError raised TypeError, which `except QuestDBError` misses:
row() did that during an IdP outage that fills the store-and-forward
queue, and after a RefreshingTokenProvider was closed. The other
OidcError classes came back with a tuple as their message and their
class's default code. Copy the instance instead, as
_dataframe_call_error does.

Also:
- _dataframe raised the main-thread signal-deferral counter before a
  check that can refuse the call outside the try that lowers it. One
  refused re-entrant dataframe() then swallowed every later Ctrl-C a
  token callback parked, for the rest of the process.
- Sender and QuestDB gained a __dict__ for the bearer-token holder, so a
  misspelt setting (sender.request_timeout = 5000) was stored and read
  back while configuring nothing. Refuse new names as before; Python
  subclasses keep their dictionary.
- RefreshingTokenProvider.close(wait=True) could return before a source
  call that had already passed the closed check ran. Mark the call in
  progress before checking.
- An on_rejected lookup that raised was reported as an internal
  AttributeError: the signal-handler snapshot started as a tuple.
- Docs: list the rejected token-provider config keys under 6.1.0
  breaking changes; the PG adapters raise whatever the provider raises,
  not always OidcError; bearer_token_provider is keyword-only too
  (conf.rst, Sender.from_env).
49e50f6 routed every attribute assignment on Sender and QuestDB through
_setattr_without_dict, which stored the value with object.__setattr__.
Before 3.13, CPython refuses that call ("can't apply this __setattr__ to
... object") on an instance whose class overrides the C-level setattr
slot, as the Cython __setattr__ does. __cinit__ sets
_bearer_token_provider that way, so neither class could be constructed
on CPython 3.10-3.12, and every wheel and test job for those versions
failed. CPython 3.13+ and PyPy do not make the check.

Call PyObject_GenericSetAttr, the function object.__setattr__ wraps,
directly. Cython's own setattr slot already calls it for deletes.
…he pool

test_pooled_dataframe_does_not_spin_on_oidc_network_failure counted the
listener's events only after leaving `with questdb.connect(...)`. The
event is queued on the pool's dispatcher inbox before dataframe() raises,
but delivery runs on the dispatcher thread, and closing the pool discards
anything it has not delivered yet. On a loaded CI agent the dispatcher had
not been scheduled before close, so the listener saw no event at all
(cp312 manylinux aarch64: `AssertionError: 0 != 1`).

Wait for the event while the pool is open, as the OIDC failover tests'
`_run` helper already does, then pause briefly so a surplus event from a
retrying call would still be counted before close discards it.
The "on mac" leg failed because DNS on the runner briefly stopped
resolving the GitHub release host. The first two system-test classes to
run, TestColumnIngressFailover and TestColumnIngressNarrowTypes, each
spent 30s in getaddrinfo, got URLError ([Errno 8] nodename nor servname
provided), and errored in setUpClass. The third class downloaded the same
tarball a minute later and every remaining test passed.

may_install_questdb() now retries a URLError up to four times with
1/2/4s backoff, and never retries an HTTP response such as a missing
release asset. This is the same retry #160 carries (ac24653), ported
verbatim so the two branches merge cleanly. The egress _exec timeout
change from that commit is unrelated and is left out.
@glasstiger

Copy link
Copy Markdown
Contributor Author

/azp run questdb.py-questdb-client-release

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

questdb's atexit hook closes the callback gate before logging.shutdown()
and before any atexit callback registered ahead of `import questdb`. An
ILP/HTTP flush from either, with a Python bearer_token_provider, therefore
retried for retry_timeout, raised TokenUnavailableError and lost its rows.
A token callback that the main thread makes from inside its own native
call now still runs while the interpreter is not finalizing. Callbacks on
native threads stay refused, so the docs now say to flush and close
QWP/WebSocket clients, and anything that needs a token refresh, before
the interpreter exits.

RefreshingTokenProvider durations had no upper bound. close(wait=True)
with a timeout above threading.TIMEOUT_MAX raised OverflowError instead
of waiting, a duration beyond the uint64 millisecond range reached an
undefined double-to-integer conversion, and a huge retry_after overflowed
and lost the source's classification. Waits are now sliced and the
conversions clamped.

The CHANGELOG now lists every read-only call that raises during a native
call, and QuestDB.from_conf as a bearer_token_provider entry point.
Sender gained an instance __dict__ to hold the bearer-token holder
where PyPy's collector can see it. Cython allocates that dictionary in
tp_new, and while an instance has one, CPython cannot cache the method
lookup of `sender.row(...)`: every row took the generic lookup, with or
without a provider, about 7 ns per call over ILP/HTTP and 18 ns over
QWP/WebSocket. CPython now keeps the holder in a typed slot and drops
the empty dictionary in __cinit__; PyPy keeps it in the dictionary as
before. row() now runs its own-callback check whatever the auto-flush
mode, so a process-wide count of callback dispatches in progress
answers it first, and the full check runs only while one is.

An ILP/HTTP Sender.dataframe() auto-flush calls a bearer_token_provider
on the caller's thread, inside the native flush. The frame took that
callback for its own Python, so the provider could drive the sender it
was supplying -- new_buffer(), a flush of another buffer -- and nest a
native flush inside the one that called it. Outside a frame the same
calls were already refused. Token callbacks now count as callbacks
there, as OIDC ones do. Two holes in the same guard are closed too: a
nested flush cleared the sender's in-native flag for the rest of the
frame instead of restoring it, and a nested Buffer.dataframe() or
SenderTransaction.dataframe(), refused anyway, dropped the outer
frame's buffer borrow on its way to the refusal.

CHANGELOG: CredentialUnavailable reports bearer_token_provider failures
too, including the terminal stop on InvalidApiCall (ConfigError).
_ReaderHandle gained a __dict__ and an object field to keep the token
providers alive, which made it a GC type with a Cython tp_clear that puts
None in its __dict__ slot. When the cyclic collector freed an unclosed
QuestDB.reader() lease -- one held in a frame that also kept a caught
exception, say -- it cleared the handle first, and the lease's
__dealloc__ then closed the reader and wrote _bearer_token_provider
through that None: SIGBUS or SIGSEGV on CPython 3.13 and 3.14, an
unraisable SystemError before. Mark the handle no_gc_clear, as
_CursorHandle and _TokenProviderHandle are. The providers it references
have their own tp_clear, so cycles through it stay collectable.

QuestDB.dataframe() and PooledSender.dataframe() borrowed again at once
after a connect that had already been given the rest of the reconnect
budget. Native ends such a connect early on a failure it does not retry
for a caller that waits -- an application bearer_token_provider that
returns an empty token, or one with a trailing newline -- so the call
spun until reconnect_max_duration ran out (300 s by default), calling the
provider thousands of times a second, where query(), an eager connect()
and Sender.establish() fail after one call. A connect that had a retry
budget and failed is now final for the call.
The token-provider guide and the BearerTokenProvider docstring said that
clients keep retrying a provider failure in the background, whatever a
TokenUnavailableError says. That holds for the background reconnects of
a QWP/WebSocket sender, query or pool, but not for ILP/HTTP: a flush
calls the provider on the flushing thread, retries a retryable failure
for up to retry_timeout, fails at once on a permanent one, and then
raises, discarding the rows in the sender's internal buffer as any
failed flush does. A reader who trusted the background retry could log
the error and lose those rows.

Scope the claim to QWP/WebSocket reconnects, note that a waited-for
connect honours the classification, describe the ILP/HTTP flush, and
show how to keep a batch for a resend: build it in sender.new_buffer()
and flush it with clear=False.
Sender.dataframe() over ws:: connects with its own clone of the sender's
options, so a close() from Python its plan build runs -- a logging
handler, an attrs read, an object cell -- does not stop it. With a
callable bearer_token_provider the close released the sender's only
reference to the provider's holder. That unregistered its callback id
while the clone still pulled tokens through it, so the call raised
TokenUnavailableError ("the token provider was released") and wrote
nothing, where the same sequence with token= or no auth completes. Keep
the holder alive for the call, as the dispatch context already is.
OidcDeviceAuth has a token() method, so it matches the BearerTokenProvider
protocol and type checkers accept it as bearer_token_provider=, but clients
refuse it there with TypeError: it must be attached as oidc_auth=. Say so on
the protocol, and correct the PG-wire paragraph and the adapters' docstring,
which said the adapters accept exactly what bearer_token_provider= accepts:
they also take an OidcDeviceAuth.
Picks up questdb/c-questdb-client#228 commit 886b497f.
OidcDeviceAuth.sign_in() no longer fails with OidcDeviceFlowError ("the
identity provider rejected the request") when a token-endpoint poll reply
is cut off after its status line: an early close or reset, or a body that
stalls past the timeout. It keeps polling, as it already did when a poll
got no reply at all, so a user still approving the code in the browser can
finish signing in. A complete non-JSON reply is still a rejection.
OidcTestServer can now cut a token-endpoint reply off: an override body
wrapped in TruncatedBody is sent with the whole body's Content-Length, but
only its first half goes out before the connection closes.

The new test cuts off the first device-grant poll's authorization_pending
reply. With the previous native pin, 87a7ee12, sign_in() raised
OidcDeviceFlowError ("the IdP rejected the token request ... Peer
disconnected") after one poll. With 886b497f it polls again and signs in.
Picks up questdb/c-questdb-client#228 commits 7f2b01f1 and fab63e5b:

- Senders that share a RefreshingTokenProvider all replay a 401 for the
  same token with its replacement. A rejection inside
  forced_min_interval got the rejected token straight back while the
  forced fetch was still running, so every ILP/HTTP flush but the first
  failed with AuthError and dropped its batch.
- A device-flow sign-in no longer opens, links or QR-encodes a loopback
  https:// URL that a remote identity provider hands out. Only a
  loopback IdP may name a loopback target, over either scheme.

The RefreshingTokenProvider.on_rejected() docstring and the comment on
the fallback URL vetter say so.
…s ConfigError

ExpiringToken(token, datetime.max.replace(tzinfo=timezone.utc)), the
usual Python way to say that a token does not expire, was rejected as
outside the datetime range, against the docstring: the expiry went
through a float, which rounds past the last microsecond near the year
9999, and a provider whose source returned it never became ready, so
every client failed after cold_wait. An aware datetime is now checked by
its UTC instant and clamped to 9999-12-31T23:59:59.999Z, the latest
instant native represents, as native clamps it. Epoch seconds and status
times no longer go through the C library's gmtime, which on Windows
stops at the year 3000.

RefreshingTokenProvider(name=...) and on_rejected(token) raised a bare
UnicodeEncodeError for a str with a lone surrogate, which
`except QuestDBError` missed although the API documents every bad
argument as a ConfigError. They now raise its ValueError, as
OidcDeviceAuth does for the same input.

ExpiringToken.expires_in's docstring now says that refresh_at is an
instant, as for the constructor, not a delay like lifetime: a refresh_in
passed as is reads as an instant in 1970, and the provider then refreshes
every min_refresh_interval.

Tests: test_the_latest_instant_means_no_expiry and the new surrogate
cases in InvalidArgumentErrorTest fail without the fix.
With gevent, a token provider that waits on I/O suspends its greenlet
inside the token callback while the other greenlets on the main thread
run. The client counted those callbacks per OS thread, so it took every
greenlet for the suspended one:

- Interpreter exit hung for good when a greenlet was suspended in a
  provider at exit. The exit hook waited for every admitted callback,
  but the greenlet could only resume once the main thread, blocked in
  that wait, ran the hub again. Ctrl-C did not end it; only SIGTERM or
  SIGKILL did. The callback gate now counts the main thread's callbacks
  apart, and the drain skips them when the main thread itself drains:
  only a suspended greenlet can hold one then. A drain on another
  thread still waits for them.
- A gevent.Timeout or the GreenletExit of kill() thrown into a greenlet
  inside its provider is not an Exception, so it is parked like a
  signal, and it was raised in whichever greenlet ran next: another
  greenlet failed with B's Timeout, B never saw it, and a killed B ran
  on. A parked exception now records its greenlet and is raised only
  there; one whose greenlet died is dropped.
- While one greenlet waited in a provider, every other greenlet counted
  as inside a token callback, so its QuestDB.close() or lease wait gave
  up after two seconds ("cannot wait ... inside a token-provider
  callback"). Such waits are now bounded only in the greenlet that is
  inside the callback.

The main thread's regions where a parked exception must not be raised
-- token callbacks, diagnostic dispatches, dataframe serialization --
are tracked per greenlet. Without greenlets, or for a region entered
before greenlet was imported, they count for the whole thread as
before, and the main greenlet keeps the existing delivery order. On
PyPy, whose greenlet module is Python code, greenlets are not told
apart.

The docs and changelog say that exit does not wait for a greenlet
suspended in a provider call, so its flush never finishes.

Tests: the three TokenProviderGreenletTest tests, which run gevent in a
child interpreter and skip without it, fail without the fix: the exit
and close() children time out, and A raises B's Timeout.
…esh fixes

Pins questdb/c-questdb-client#228 at 6df7aa67, which:

- refuses a symlinked OIDC token store however its path is spelled. A
  trailing separator (`FileTokenStore('<dir>/link/')`, or the same in
  QUESTDB_CLIENT_OIDC_TOKEN_STORE_DIR) passed the symlinked-leaf check,
  and a sign-in then chmodded and wrote the link's target;
- refuses every spelling of the local machine as a browser sign-in
  target from a remote identity provider: `127.1`, `2130706433`,
  `0x7f.0.0.1`, IPv4-mapped loopback, unspecified addresses and
  `*.localhost` got past the loopback refusal;
- returns from a RefreshingTokenProvider's forced refresh at once when
  failure backoff lets no fetch start before forced_wait ends. Every
  ILP/HTTP flush answered 401 while the provider backed off stalled
  forced_wait (5 s) before failing with the same 401. The on_rejected()
  docstring says so;
- passes on a C++ provider's escaping line_sender_error unchanged, and
  links the OIDC headers from the C and C++ guides. Neither affects
  this binding.
Two application-provider failures that no retry can fix were reported
to native as retryable:

- A token() that returns something other than a str (bytes from
  base64.b64encode() or response.content, None) or a str that is not
  valid Unicode (a lone surrogate from a surrogateescape-decoded file or
  environment variable). The binding refuses it before native sees it,
  and reported a retryable failure, so a connect the caller waits for
  and QuestDB.dataframe() called the provider until the reconnect budget
  ran out -- five minutes by default -- while an empty or non-printable
  token already failed at once. It is now reported as permanent: those
  calls and an ILP/HTTP flush end at once. Background reconnects keep
  retrying, as for any classification. The message names the type or
  the position, never the token.
- A closed OidcDeviceAuth reached through a provider of one's own,
  bearer_token_provider=lambda: auth.token(). Its OidcCancelledError
  was retried for good: a QWP/WebSocket sender kept reconnecting and
  reporting CredentialUnavailable with SocketError, and an ILP/HTTP
  flush used up retry_timeout. The error is now marked as a closed
  RefreshingTokenProvider's is, so closing the auth ends the provider's
  clients, reported as ConfigError, as with lambda: tokens.token().

Tests: test_a_token_that_is_no_str_fails_at_once_without_leaking_it,
test_closing_an_oidc_auth_a_provider_calls_ends_its_clients and the
new cases of test_an_unusable_token_does_not_spin_dataframe_retries fail
without the fix.
The token-provider and OIDC callbacks park a Python signal handler's
exception for the caller, so a Ctrl-C or a SIGALRM deadline that lands
in one still interrupts the flush or sign-in that ran it. Three windows
lost it instead:

- Classifying an application provider's failure runs Python: the
  signal-handler test calls into the `signal` module, and the failure's
  text runs its __str__. A handler that raised there was swallowed with
  the failure, which was reported as "the token callback failed". On
  the on_rejected() path it escaped the noexcept callback and was printed
  as unraisable. The snapshot of installed handlers taken before the
  call, Python too, had the same gap.
- A second interruption during sign_in() -- two signals together, or the
  first one's queued sibling raised by its pending call -- was dropped
  when it arrived while a SUCCESS or FAILURE event was rendered: the
  provider keeps one interrupt to raise.

The token callbacks now park an exception raised while they examine a
failure, as the OIDC dispatchers already did, and the event path queues
a second interrupt for the main thread. sign_in() raises the first and
the second surfaces at its native-return boundary, chained to it.

Tests: test_a_signal_while_a_provider_failure_is_classified_reaches_the_caller
and test_a_second_interrupt_at_sign_in_success_is_not_lost fail without
the fix.
A provider may own the client it is attached to: an object that
implements token() and keeps its own QuestDB or Sender. CPython collects
such an object together with its unclosed client, and so does PyPy,
since the client keeps the provider in its instance dictionary. On PyPy
that stops holding once the object also holds an unclosed lease or
QueryResult of that client: a lease or cursor holds the client and its
reader in typed fields, which PyPy's collector cannot see, so the
object, the client and its connections stay alive until the process
exits.

Moving those references where PyPy sees them is not a fix: a value set
through the generic attribute protocol lives in PyPy's own instance
dictionary, which __dealloc__ cannot read, and every lease and cursor
release path needs it there. The token-provider guide now says to close
such leases and results, as the API docs already ask, and the reader
handle's comment no longer claims cycles through it are collectable
everywhere.
The docstring told every caller to sign in first, and said a connection
made before any token was acquired raises OidcInteractionRequired
rather than blocking the pool. That holds for an OidcDeviceAuth only.
The function also takes a RefreshingTokenProvider, which has no
sign_in(), and whose token() waits up to cold_wait for a token and then
raises TokenUnavailableError, and any other provider, which behaves as
its own token() does.
…r code

Classifying a bearer_token_provider's failure formats it, which runs the
exception's __str__. On the main thread, any exception raised while the
failure was classified was parked as if a signal handler had raised it.
A failure whose __str__ itself raises -- a provider's own error type
that reads a response an unreachable identity provider never sent --
interrupted nothing, yet the flush then failed with "the token callback
was interrupted", and the __str__ error was raised again on the main
thread once the flush's error had been caught: inside the caller's
`except QuestDBError` block, in a context manager's __exit__, at
threading shutdown. One for every token request the flush made -- 16
with the default retry_timeout -- and a SystemError at interpreter exit.

Such an exception is now parked only when it is no Exception, such as
KeyboardInterrupt, or the signal-handler test attributes it to a
handler, using the handler snapshot taken before the provider ran;
anything else is reported as "the token callback failed", as on any
other thread. on_rejected() errors use the same test. A deadline that a
signal handler raises while a failure is classified still reaches the
caller.

Tests: test_an_unprintable_provider_failure_stays_in_its_call fails
without the fix, with pending calls queued and with the native-return
fallback; test_a_signal_while_a_provider_failure_is_classified_reaches_the_caller
still passes.
An application bearer_token_provider stops its clients' background
reconnects by raising its own QuestDBError with code InvalidApiCall. A
TokenUnavailableError is a QuestDBError, and its public `code=` accepts
InvalidApiCall, but clients classify one by `retryable` alone and keep
reconnecting -- deliberately, as native keeps a token-unavailable error
apart from InvalidApiCall. The CHANGELOG ("except QuestDBError with code
set to QuestDBErrorCode.InvalidApiCall that an application provider
raises itself, which stops them") and token_providers.rst ("Only an
InvalidApiCall your provider raises itself has that effect") read as if
it stopped them, so a provider that raised
TokenUnavailableError(..., code=InvalidApiCall) got endless reconnects
and CredentialUnavailable events with cause SocketError instead of a
ConfigError.

The CHANGELOG, token_providers.rst and the TokenUnavailableError,
BearerTokenProvider and ConnectionEventKind docstrings now say to raise
a plain QuestDBError, and that a TokenUnavailableError's code only
labels it. Behaviour is unchanged.
The c-questdb-client pin brings in questdb/c-questdb-client#208, so
request_durable_ack now also accepts local, replicated and
local,replicated, and sends them to the server. The configuration
reference still listed only 'on' and 'off', described for Enterprise
object storage, and the 6.1.0 CHANGELOG did not mention the new values,
which the previous release rejected.

docs/conf.rst now lists every value, what each acknowledgement means and
which servers grant it: local needs cairo.commit.mode=adaptive, which
QuestDB 10.1.0, Enterprise 4.1.0 and earlier lack; replicated is on's
new name, Enterprise only, and Enterprise 4.1.0 and earlier know only
on. It also says that the store-and-forward queue keeps a frame until
its durable acknowledgement, while this client's acknowledgement waits
-- PooledSender.wait(), flush(wait=True), await_acked_fsn() -- wait for
the ordinary OK acknowledgement. The CHANGELOG gains an entry.
Pins questdb/c-questdb-client#228 at 2a443686, which:

- counts every non-spacing mark against the display sanitizer's cap of
  four marks on one base character. A combining mark outside its list of
  stacking blocks ended the run, so interleaving one between listed
  marks kept a whole "Zalgo" stack in an identity provider's error text.
  This binding's own renderers and OidcError messages already applied
  the full cap; a custom Renderer's on_failure() received the native
  text;
- documents that closing a token provider does not wait for a fetch
  already running. Python's RefreshingTokenProvider.close(wait=True)
  already offers that wait.
test_interrupt_in_persistence_diagnostic_reaches_token failed on the
linux_arm64_manylinux_a release leg (cp312) with OidcNetworkError
"Failed to reach .../token: timeout: global".

Before it sends a refresh, native tombstones the stored parent token:
it takes the store lock, unlinks the entry and fsyncs the directory.
That time counts against the request's timeout, and the test inherits
the helper's 5 s. A plain OidcNetworkError, not OidcInteractionRequired,
means the request was never sent, so the agent spent all 5 s on that
local work. Stalling directory fsyncs for 6 s reproduces the same error
locally. With the library's 30 s default, the test passes.
@glasstiger

Copy link
Copy Markdown
Contributor Author

Reviewing PR #165 at level 3, head cd29d4f, base 8190c2a.

Verdict: approve. There are no Critical or Moderate findings, only one optional Minor about an error message.

Critical

None.

Moderate

None.

Minor

1. The refusal for an OidcDeviceAuth subclass that overrides token() gives no working route (in-diff)

  • Problem: bearer_token_provider= sends an overriding OidcDeviceAuth subclass to oidc_auth=, which refuses it too.

  • Net impact: Users overriding OidcDeviceAuth.token() get misleading TypeError text. Nothing is lost at runtime or in data.

  • Evidence: at cd29d4f both keywords raise TypeError, while bearer_token_provider=lambda: auth.token() is accepted:

    class Sub(OidcDeviceAuth):
        def token(self):
            return 'x' + super().token()
    
    auth = Sub('questdb', device_authorization_endpoint='https://idp.example/device',
               token_endpoint='https://idp.example/token', interactive=False, open_browser=False)
    Sender(Protocol.Https, 'localhost', 9000, bearer_token_provider=auth)
    # TypeError: Pass an OidcDeviceAuth as "oidc_auth=", not as "bearer_token_provider=".
    Sender(Protocol.Https, 'localhost', 9000, oidc_auth=auth)
    # TypeError: "oidc_auth" must not override token(): ... Remove the override.
    Sender(Protocol.Https, 'localhost', 9000, bearer_token_provider=lambda: auth.token())
    # accepted

How it happens:

  • _tp_resolve_bearer_token_provider (src/questdb/token_provider.pxi:1517-1522) refuses any OidcDeviceAuth, overridden or not, and points to oidc_auth=.
  • _oidc_require_native_token (src/questdb/oidc.pxi:1261-1275) refuses the override and says to remove it.
  • Sender.from_conf, Sender.from_env, QuestDB.from_conf and questdb.connect go through the same two checks.
  • Neither message names the accepted way to keep the override. The docs mention lambda: auth.token() only to explain what closing the provider does.
  • This is a new surface, so there is nothing to compare at base. The two refusals themselves are documented design (CHANGELOG, BearerTokenProvider docstring); only the message wording is at issue.

Suggested fix: in _tp_resolve_bearer_token_provider, when token() is overridden, name both options in the message: remove the override and pass the object as oidc_auth=, or keep it with bearer_token_provider=lambda: auth.token(). The oidc_auth= refusal could add the same alternative.

Adjacent findings

None new.

Coverage map

The test gate passes, with 0 admitted coverage gaps. The new behaviour has tests that run on every CI leg and in every wheel build: the buffer and sender guards, cursor re-entry and finalizer reclaim, retry slicing, the attribute guard, and the callback and token paths. The one live OIDC round trip (test_oidc_provider_query_and_ingress_round_trip) is gated only on pandas and the server supporting QWP/WebSocket, so it is eligible on the released-server legs as well as linux-qdb-master.

Summary

  • Correctness gate: passes, no Critical findings. Test gate: passes, 0 admitted coverage gaps.
  • Severity and split: 0 Critical, 0 Moderate, 1 Minor; 1 in-diff and 0 breakages in unchanged callers.
  • Build profile:
    • Cython 3, with only language_level=3 and binding=True set (_client.pyx:25-27). setup.py:202 passes no compiler directives, so bounds, wraparound and initialization checks are on.
    • Exceptions propagate by default; only explicit noexcept and extern functions swallow them.
    • questdb-rs-ffi aborts on panic in both release and dev (Cargo.toml:77-81 at the pin).
    • The module is not free-threading compatible, so free-threaded builds re-enable the GIL.
    • _ReaderHandle and _TokenProviderHandle are newly marked no_gc_clear, and PyPy builds now define CYTHON_USE_TYPE_SPECS=0.
  • Submodule: c-questdb-client moves b741c622 → 2a443686 (OFF-DEFAULT, tandem). The new commit exists only on origin/ia_oidc_auth, and feat(oidc): add OIDC and rotating bearer tokens c-questdb-client#228 is still open. Its Rust code belongs to that PR's review. Here the .pxd declarations and the Cython callers were checked against the pinned headers, and the build raised no C type warnings. Moving the pin to a main commit before release is merge mechanics, not a finding.
  • CI at this head: all 31 checks pass, including the PyPy (linux_x64_pypy) and free-threaded (macos_cp314t) wheels, the released-server leg (linux-qdb10), linux-qdb-master, Windows, macOS and the SQLAlchemy 1.4/psycopg2 job. I did not read the job logs to confirm that the live OIDC round trip ran rather than skipped.
  • Local validation (CPython 3.13.5, macOS arm64, scratch worktrees built at the exact revisions):
Check Result
Full mock suite at head 1654 tests, 64 skipped, 1 failure
Full mock suite at base 1180 tests, 58 skipped, 2 failures
Strict Sphinx build (-nW --keep-going) Clean
Sender.row() and Buffer.row() speed No slowdown versus base
Provider attach, self-owning cycle and RefreshingTokenProvider create/close loops No growth beyond base's allocator noise; no leftover callbacks or garbage
  • The head failure, test_an_interrupt_during_the_native_close_still_finishes_it, comes from running the suite as a background job, which ignores SIGINT. It passes in the foreground at both head and base.
  • Base's second failure, test_pooled_sender_plans_for_default_cap_without_server_cap, did not recur at head.
  • Not run locally: polars, gevent, a live server, PyPy, free-threaded Python.
  • Documented breaking changes, accepted as intended:
    • A sender's own callbacks can no longer drive it.
    • Getters and buffer access raise from other threads while a native call is running.
    • A connected QWP/WebSocket sender keeps reconnecting after HTTP 401/403, even with a fixed credential, instead of stopping.
    • The token-provider configuration keys are rejected on every protocol.
    • Query results refuse re-entry from the thread reading them.
    • Sender subclasses see the new attribute guard.
    • QuestDB.close() gives up after 2 s while its provider's persistence-warning callback is running on another thread.
  • PR description is slightly out of date:
    • The Tandem section calls the pin #228's head, but #228 is now at 99dd41a3, one commit past it.
    • The Testing section stops at 679de40; this head adds cd29d4f, which only changes a test.

The review was read-only: builds and probes ran in scratch worktrees, and the PR's base/head pair was revalidated before posting.

@glasstiger

Copy link
Copy Markdown
Contributor Author

Reviewing PR #165 at level 3, head cd29d4f, base 8190c2a.

Reviewing PR #228 at level 3, head 99dd41a38972b2dd2b58b16fa73f3413e1a225d4, base a6fd07f153e9cdeffc5959e738a4de69add7789c.

This is a tandem review of #165 and questdb/c-questdb-client#228. Each PR was reviewed with its own repository's review skill.

Verdict: approve both. #165 has one optional Minor; #228 has no findings. Both PRs were unchanged at the end of the review.

#165

Critical

None.

Moderate

None.

Minor

1. An exception raised by a provider's on_rejected() is not logged (in-diff, src/questdb/token_provider.pxi:918-924)

  • Problem: on_rejected() exceptions are dropped silently. The connection_listener, error_handler and Renderer callbacks log theirs.
  • Net impact: a broken on_rejected, such as a one-argument signature, gives no hint why 401 recovery isn't working. No rows or outcomes are affected.
  • Evidence: at cd29d4f an ILP/HTTP flush got a 401, and on_rejected raised TypeError, RuntimeError, QuestDBError(InvalidApiCall) or TokenUnavailableError.
    • Nothing was logged on any logger, no warning was issued, nothing reached sys.unraisablehook or threading.excepthook, and nothing went to stderr.
    • The flush failed with the same AuthError as a provider with no on_rejected.
    • This is new surface: the base has no providers.

How it happens:

  • _ApplicationTokenProvider wires vtable.on_rejected (token_provider.pxi:1461), which reaches _token_rejected_dispatch.
  • That function calls on_rejected(token, status) at lines 918-920.
  • Its except BaseException parks only interrupts. Every other exception reaches # Otherwise ignored (line 924).
  • QWP/WebSocket senders, readers and pools use the same dispatch. Only the HTTP path was run.

The documented behaviour of the other callbacks:

  • connection_listener / error_handler: "Exceptions raised by the listener are logged and swallowed" (_client.pyx:3470, implemented at 3808-3810).
  • Renderer: "an exception raised by one is logged" (auth/_render.py:795-796, implemented at oidc.pxi:1656-1658).
  • Neither the BearerTokenProvider docstring nor docs/token_providers.rst says what happens to an exception from on_rejected.

Suggested fix:

  • When the exception is not parked as an interrupt, log it with logging.getLogger('questdb').exception(...). Guard that call the way _oidc_event_dispatch guards its own (oidc.pxi:1656-1671).
  • Add one line to the BearerTokenProvider docs: on_rejected exceptions are logged and do not change the outcome.
  • Assert the log record in test_a_failing_on_rejected_lookup_is_ignored or a sibling test.

Adjacent findings

Nothing new. #172 (QuestDBError cannot be unpickled) is already filed.

Coverage map

The test gate passes with 0 admitted coverage gaps. The new guards and the provider and OIDC paths are covered by mock-only tests that run on every CI leg and in the wheel builds, for example TestBufferNativeBorrow and BearerTokenProviderAttachTest.

Summary

  • Verdict: approve. The correctness gate passes. The test gate passes, with 0 admitted coverage gaps.
  • Findings: 0 Critical, 0 Moderate, 1 Minor. The Minor is in-diff and optional; no out-of-diff breakage.
  • Build profile:
    • Cython 3, with only language_level=3 and binding=True (_client.pyx:26-27).
    • setup.py:202 passes no directives, so bounds and wraparound checks stay on.
    • Exceptions propagate unless a function is explicitly noexcept.
    • The module is not free-threading compatible.
    • questdb-rs-ffi uses panic = "abort" in both release and dev (Cargo.toml:77-81 at the pin).
  • Submodule: c-questdb-client moves b741c622 → 2a443686. That commit is not on main (tandem).
    • The Rust is reviewed under #228.
    • The .pxd declarations and Cython callers were checked here against the pinned headers. The head build raised no C type warnings.
    • 2a443686 is #228's head minus one commit, which only changes the OIDC browser-target check.
    • Moving the pin to a main commit before release is merge mechanics, not a finding.
  • CI at cd29d4f: all 31 checks pass. That includes linux-qdb10, linux-qdb-master, PyPy (linux_x64_pypy), free-threaded (macos_cp314t) and the SQLAlchemy 1.4/psycopg2 job.
  • Local validation (CPython 3.13.5, macOS arm64, Cython 3.2.5, NumPy 2.4.6, pandas 3.0.3, pyarrow 24.0.0; scratch worktrees built at the exact revisions):
    • Mock suite: 1654 tests at head (64 skipped), 1180 at base (58 skipped). Both had one failure, the same test, test_an_interrupt_during_the_native_close_still_finishes_it. The suites ran as a background job, which ignores SIGINT.
    • Provider churn under PYTHONMALLOC=debug: 300 create/close cycles, plus a source that drops its provider's last reference. No crash, and the callback registry returned to empty.
    • Cross-thread access during a flush blocked in its provider: len, row, close, the getters, new_buffer, transaction and dataframe were all refused with InvalidApiCall.
  • Breaking changes: the documented ones (CHANGELOG 6.1.0) were treated as intentional.
  • PR description:
    • The Tandem section calls 2a443686 #228's head, but #228 is now at 99dd41a3.
    • The Testing section stops at 679de40. cd29d4f only changes a test.

questdb/c-questdb-client#228

Critical / Moderate / Minor

None.

Adjacent findings

Nothing new. #231 and #232 are already tracked.

Coverage map

The test gate passes with 0 admitted coverage gaps.

Summary

  • Verdict: approve. The correctness gate passes. The test gate passes, with 0 admitted coverage gaps.
  • Findings: 0 Critical, 0 Moderate, 0 Minor. Nothing in the diff and no out-of-diff breakage.
  • Panic and overflow: questdb-rs-ffi aborts on panic in release and dev. Overflow checks are at Cargo's defaults: on in dev and test, wrapping in release. The global allocator is test-only.
  • Submodule: questdb moves 2d9244fe → 8da4e347. That commit is already on upstream master, so its contents are out of scope.
  • CI at 99dd41a3: all 26 checks pass. That includes ASan/UBSan, Vs QuestDB master, the egress live-server suite and enterprise e2e.
  • Local validation: the questdb-rs lib tests (almost-all-features,ffi-support) matching token_provider, oidc, qwp_ws_auth_rejection, orphan and display_text: 571 passed.
  • Documented tradeoffs worth knowing before release:
    • An established QWP/WebSocket sender retries 401/403 indefinitely, static credentials included.
    • An orphan drainer gives a slot up for the session after a credential ride-out. The slot stays on disk (doc/SECURITY.md:69-73).
    • An ILP/HTTP flush can wait up to cold_wait (30 s by default) when a RefreshingTokenProvider holds no usable token, beyond retry_timeout (docs/token_providers.rst:69-70 in feat(auth): add OIDC and rotating bearer tokens #165).
  • PR description: it does not cover 99dd41a3, which keeps a local identity provider's sign-in target however its host is spelled.

The review was read-only: builds and probes ran in scratch worktrees, and both PRs' base/head pairs were revalidated before posting.

jovfer
jovfer previously approved these changes Nov 11, 2026

@jovfer jovfer left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

review approve seems valid, please double-check if we should really mark this PR as "breaking changes"

@glasstiger glasstiger changed the title feat(auth)!: add OIDC and rotating bearer tokens feat(auth): add OIDC and rotating bearer tokens Nov 11, 2026
@glasstiger
glasstiger merged commit 2d6b8b2 into main Nov 12, 2026
31 checks passed
glasstiger added a commit to questdb/documentation that referenced this pull request Nov 16, 2026
## Summary

- Document OIDC device-flow sign-in and rotating bearer-token providers
for C/C++ and Rust 7.3.0+, and Python 6.1.0+, with language-specific
examples.
- Cover discovery, issuer pinning, scopes, silent refresh, token
persistence, provider ownership, error handling, and shutdown. Include
Python notebook support, managed identities, and PGWire adapters.
- Replace obsolete unsupported-authentication claims and align the
shared OIDC, connection-string, and QWP behavior references with the new
provider and reconnect behavior.
- Update connection-setup guidance to reflect eager pool initialization
and where authentication failures surface.

Related implementation PRs: questdb/c-questdb-client#228 and
questdb/py-questdb-client#165.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants