Repository navigation
feat(auth)!: add OIDC and rotating bearer tokens - #133
glasstiger wants to merge 430 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 Walkthrough
Pre-merge checks:
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
src/questdb/auth/_questdb.py (1)
82-94: 💤 Low valueChain the import exception for better diagnostics.
When both
psycopgandpsycopg2fail to import, the raisedImportErrorloses the underlying cause. Chaining the exception preserves the diagnostic context.Suggested fix
def _pg_module(): try: import psycopg # type: ignore # psycopg v3 return psycopg except ImportError: pass try: import psycopg2 # type: ignore return psycopg2 - except ImportError: + except ImportError as e: raise ImportError( 'A PostgreSQL driver is required: install `psycopg` (v3) or ' - '`psycopg2-binary`.') + '`psycopg2-binary`.') from e🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/questdb/auth/_questdb.py` around lines 82 - 94, The second except ImportError block in the _pg_module() function should preserve the exception chain for better diagnostics. Capture the ImportError exception in the second except block using `as e` syntax, then use `raise ... from e` syntax when raising the new ImportError to chain the exception, which preserves the underlying cause and provides better debugging context.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.claude/skills/review-pr/SKILL.md:
- Around line 157-162: The Step 3 preamble at lines 157-162 states that every
agent receives the full change-surface map, but Agent 10's input contract at
lines 231-240 explicitly limits it to only the PR diff and changed file names.
Add an explicit exception clause in the Step 3 preamble section to clarify that
Agent 10 does not receive the full change-surface map and instead receives only
the diff and changed file names, ensuring consistency between the general rule
and the specific Agent 10 behavior documented at lines 231-240.
- Around line 39-42: The table at lines 39-42 states that level 0 (default)
skips Step 2.5, but there is a later reference (around lines 144-155) that marks
Step 2.5e as mandatory at every level, creating a contradiction. Fix this
inconsistency by clarifying the level 0 description in the table: either modify
the "Skip Step 2.5" statement to specify that Step 2.5e is an exception and is
still performed, or restructure it to list exactly which substeps (2.5a, 2.5b,
2.5c, 2.5d, 2.5e) are executed or skipped. Ensure the description at level 0 and
the mandatory requirement stated at lines 144-155 are aligned so the default
path is no longer self-contradictory.
In `@docs/auth.rst`:
- Around line 65-76: The code example in the documentation is missing the import
statement for TimestampNanos, which is used in the sender.row() method call. Add
an import statement at the top of the code snippet to include TimestampNanos
from the questdb.ingress module (or appropriate module) so that the example can
be executed successfully when copied verbatim.
In `@src/questdb/auth/__init__.py`:
- Around line 75-92: The `__all__` list in the module needs to be sorted
alphabetically to comply with Ruff's RUF022 rule and maintain consistency in the
public API exports. Reorder all the items in the `__all__` list (which includes
'connect', 'QuestDB', 'OidcDeviceAuth', 'OidcConfig', 'TokenCache', 'TokenSet',
'MemoryCache', 'FileCache', 'NullCache', and the various OidcError types) in
alphabetical order while ensuring all items remain in the list.
In `@src/questdb/auth/_http.py`:
- Around line 123-129: The `_opener()` function doesn't receive the `insecure`
parameter, so it cannot enforce HTTPS-only redirect policies. To fix this, add
an `insecure` parameter to the `_opener()` function signature. When
`insecure=False`, create a custom redirect handler that validates redirects do
not downgrade from HTTPS to HTTP for non-loopback hosts (similar to the
validation in `_require_secure()`), and pass this handler to
`urllib.request.build_opener()` instead of using the default. When
`insecure=True`, use urllib's default redirect handling. Update all callers of
`_opener()` to pass the `insecure` parameter value.
In `@test/test_auth.py`:
- Around line 600-605: The timed joins with a 10-second timeout do not verify
that threads actually completed, which can cause non-daemon threads to remain
running and hang the test process if a regression causes a deadlock. After
calling t.join(10) on each thread in both the loop at lines 600-605 and at lines
828-835, add a verification check that confirms each thread has terminated by
asserting that t.is_alive() returns False, or raise an exception if any thread
is still alive after the timeout. This ensures the test fails cleanly rather
than leaving hanging threads.
---
Nitpick comments:
In `@src/questdb/auth/_questdb.py`:
- Around line 82-94: The second except ImportError block in the _pg_module()
function should preserve the exception chain for better diagnostics. Capture the
ImportError exception in the second except block using `as e` syntax, then use
`raise ... from e` syntax when raising the new ImportError to chain the
exception, which preserves the underlying cause and provides better debugging
context.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: bf4af383-9022-4ae5-b189-73691f4ccd00
📒 Files selected for processing (18)
.claude/skills/review-pr/SKILL.mdCHANGELOG.rstdocs/api.rstdocs/auth.rstdocs/index.rstdocs/installation.rstexamples/oidc_device_auth.pysetup.pysrc/questdb/auth/__init__.pysrc/questdb/auth/_cache.pysrc/questdb/auth/_device.pysrc/questdb/auth/_discovery.pysrc/questdb/auth/_errors.pysrc/questdb/auth/_http.pysrc/questdb/auth/_questdb.pysrc/questdb/auth/_render.pytest/test.pytest/test_auth.py
Address moderate findings from the PR #133 review: - Persist and re-check `issuer` in the token store so a token pinned to one issuer is never served from disk to a session pinned to another. Kept out of the file-name hash, so the cross-language file contract and existing token files stay byte-stable; isolation is enforced via the on-load identity re-check, matching the in-memory cache_key. - FileTokenStore.load() now returns None (not raises) for an unreadable entry: a directory/symlink-loop at the token path (stat.S_ISREG/errno guard) and a deeply-nested attacker file (RecursionError), restoring its documented contract and matching every other json.loads site. - _display_url escapes a host that still carries a URL-structural char after IDNA (e.g. the U+FF3C/U+FE68 reverse-solidus fold) as a visible \uXXXX, instead of a bare backslash a browser would read as a slash. - CHANGELOG: relabel the Python 3.8->3.10 bump as a breaking change with the whole-package blast radius, EOL rationale, and a migration note. Adds regression tests for each; full auth suite passes (308 tests). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Code review —
|
Code review —
|
Code review —
|
Tandem review: py-questdb-client #133 + c-questdb-client #183Level 3, multi-agent, adversarial. These two PRs are one change: py #133 adds the native-backed OIDC device-flow binding and pins the Verdict: Approve. No Critical issues — no memory-unsafety, refcount imbalance, double-free, GIL violation, ABI mismatch, auth-bypass, secret-leak, or terminal-injection. This is an unusually well-hardened change. The two Moderate items are now resolved on the branch; the remainder are Minor. ✅ Resolved in
|
|
Note: this PR temporarily carries UUID / fixed-size-binary changes that belong to #140. Commit It appears here because this PR bumps the To be precise about what did and did not change: the QWP wire bytes are unchanged and still match the Java client — Merge order: #140 should land first. This branch's copy then collapses into the merge base and this PR's diff reduces to the OIDC feature alone. Watch the |
Picks up three fixes on the c-questdb-client branch: a misconfigured provider stays terminal instead of driving an endless reconnect, a failed token pull is reported to the connection listener instead of failing silently, and close drops the in-memory credential on every path rather than only when it drains. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
The event handler's user_data was an INCREF'd weakref, so the final native release ran a Py_DECREF -- and that release can run on a thread the interpreter neither manages nor joins. A token provider's acquisition is isolated onto its own worker so shutdown can abandon it, and that worker keeps the provider closure, and so the callback state, until its own HTTP call returns: potentially long after every handle is gone and after finalization has begun. The guard was a Py_IsFinalizing check, and no such check can be made safe -- finalization can begin between the test and PyGILState_Ensure, which then hangs the thread or faults. Weakening the closure's handle does not help either: the auth owns its renderer, which is the same CEventHandler, so anything holding the auth holds the callback. Hand native an opaque integer key instead and resolve the provider through a module-level registry under the GIL. Native then owns no Python reference, the release callback has nothing to free and never needs the GIL, and the entry is dropped in __dealloc__, which always runs on a managed thread. This removes the hazard rather than narrowing its window. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Nothing but __dealloc__ removes a registry entry now that native owns no Python reference, so a stale one would be a slow leak that no weakref assertion catches. Asserts the entry appears with the provider, does not keep it alive, and is gone once it is collected -- and that the registry does not grow across 200 create/destroy cycles. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up two fixes on the c-questdb-client branch: a long Retry-After is waited out in slices so the prompt keeps counting down and Ctrl-C stays deliverable, and the in-process token-store lock is bounded by the acquire budget instead of spinning without a deadline. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
The Renderer docstring said only that a callback must not call back into the same instance. It omitted that the guard applies to any thread, and now that token() succeeds from a valid cache but is refused when a fresh acquisition would be needed. States both, and points at signing in before putting a provider behind a connection pool so pooled checkouts hit that cache. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up the c-questdb-client fix that stops the OIDC callback guard failing unrelated callers: a valid cached token is now served to other threads during a sign-in prompt, and the two refusal cases carry distinct, accurate diagnostics. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up two c-questdb-client fixes: a future-dated lock file no longer disables the token store permanently, and a credential is no longer persisted into a directory whose permissions could not be restricted and which the client will therefore never read back. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
client_id, token_endpoint and device_authorization_endpoint are required positionals but went through the optional-string helper, which drops a None and leaves the field unset. Native then reported the field as missing from QuestDB's /settings and told the caller to pass it explicitly -- advice that makes no sense for a constructor that never contacts /settings, and that names a builder method this API does not have. from_questdb keeps the optional path, where the three are genuine overrides. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Only native enforced that oidc_auth excludes a fixed credential, and it reports the internal config key it knows -- "http_token_provider" or "qwp_ws_token_provider" -- which exists in no public API, so a caller who passed oidc_auth= together with token= was told about a symbol they cannot find. Reject it in terms of the parameters actually written, on both the Sender and the pool path, keeping the established QuestDBError(ConfigError) type. Also documents the 65536 ceiling on the two callback inbox capacities, which is enforced at connect time but was mentioned nowhere. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Asserts a credential conflict names oidc_auth and token rather than an internal provider key, and that each required constructor argument is rejected as required instead of being reported as missing from /settings. Adds the changelog entry for the callback inbox cap, which rejects a previously accepted value at connect time. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up three c-questdb-client fixes: advertised endpoints are confirmed against the IdP so Entra ID and Google work with issuer=, a 401 from a token that expired mid-retry is retried once with a rotated credential, and a persisted JWT honours the same one-hour rotation cap as one off the wire. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
OidcDeviceAuth is an extension type, so help() and the rendered API reference cannot introspect its signature -- Sphinx shows __init__(*args, **kwargs) and none of the sixteen parameters. Four of them (ca_bundle, interactive, default_interval, timeout) were described nowhere at all, and two carry contracts worth stating: insecure relaxes plaintext for the QuestDB discovery request only, never the identity provider, and timeout is a per-request timeout rather than a deadline for the sign-in. Documents all of them in the docstring, which is what the reference renders. token() and headers() now name OidcInteractionRequired, which both raise before the first sign_in. The renderer docs told custom implementations to sanitize untrusted identity-provider text without exporting anything to do it with, while oidc.pxi reached across the extension boundary for the private _strip_control. Exports sanitize_display_text and points both the Renderer docstring and docs/auth.rst at it. Also records why the event trampoline may enter Python when the release callback must not: renderer events are emitted only by the device flow, reached only through the foreground sign_in(), so no abandoned worker can reach it after finalization begins. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
- The object-dtype uuid.UUID column asserts concrete wire bytes. It drives qwp_numpy_s16, a different native entry point from the Arrow routes every other UUID test uses, and it is the one changed to hand over canonical RFC 4122 bytes and rely on native to reverse them. A round-trip through one symmetric transform would pass either way. - OidcError's control-character stripping is asserted through a real flow with a hostile error_description. Native does not sanitize this path, so the Python layer is the only sink guard, yet every existing test used clean strings yet -- deleting it passed the whole suite. - The SUCCESS/FAILURE non-cancellation guard: an interrupt raised from on_success must not discard the token just acquired. - Cancellation tests now advertise a short device-code lifetime. They assert promptness after the blocking call, so a regressed cancellation stalled for ten minutes rather than failing, and the CI watchdog re-arms past that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up the c-questdb-client test work: the hand-maintained OIDC and connect-options headers are now guarded against drifting from the Rust definitions they mirror, and the C++ event handler's ownership contract is covered. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
Picks up the c-questdb-client CI work: the OIDC device-flow test that reached for the WS builder API is now gated on the WS feature, so the HTTP-only leg of the cargo matrix compiles again; two clang-format violations are cleared; and the token-store interop goldens are pinned against line-ending conversion, which was corrupting the byte-exact comparison on Windows checkouts alone. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GjKmdBcwtTjoSb8mZwv4xz
`_finish_builder` inserts the provider into `_OIDC_PROVIDERS` before installing the native event handler, but only the handler-failure path dropped that entry. A failed `questdb_oidc_builder_build` left it behind with `_raw` still NULL -- and the already-initialized guard keys on `_raw != NULL`, so it does not fire on a retry. A caller that re-runs `__init__` on the same object, such as a subclass catching OidcConfigError and calling `super().__init__()` again with a corrected endpoint, then overwrote `_provider_id` and stranded the previous key as a dead weakref in a module-global dict for the life of the process, once per retry. The post-registration block is now wrapped so every failure unwinds the entry, not just the one that happened to be handled, restoring "registered <=> built" against future raise sites too. `test_event_handler_weakref_released_on_failed_build` could not have caught this: its empty client_id is rejected by `_oidc_required_utf8` before the builder is populated, so it never reached a build failure at all, and its rationale described the pre-integer-key ownership model this branch replaced. Two tests take its place, using an unreadable ca_bundle -- stored by the setter, opened by build() -- and asserting registry size rather than a weakref proxy. One holds the half-built object alive, because asserting after it is dropped proves nothing: __dealloc__ pops the entry either way. Both fail without the fix. Also pins the causal-chain contract from the Python side: a token failure reaching a transport arrives as a typed OidcInteractionRequired that is still a QuestDBError and still carries the transport's own SocketError code, which is what retry logic keys on. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012QoXxcyoqduoW9Mi3ZSnyy
`_direct_dataframe_run` rebuilt the error as a bare QuestDBError when a one-shot stream had already been consumed. That flattened every subclass that can reach the branch: an OIDC token failure on an `oidc_auth` transport arrives as OidcNetworkError, OidcDeviceFlowError or OidcTimeoutError -- each carries a retryable code by design, so it clears both the terminal-OIDC gate and the code check above it -- and rebuilding stopped `except OidcError` matching while discarding .status, .retry_after, .error and .error_description. Those are the attributes `c_err_to_py` promises are catchable. It now appends the note to the original exception and re-raises it. `args` is what Exception.__str__ reads and every field lives on the instance, so code, in_doubt and sender_error survive for free. The existing consumed-stream test gains the discriminating assertion: `raise X from exc` set __cause__, re-raising the original leaves it None. Also corrects the `c_err_to_py` / `c_err_to_py_fmt` docstrings, which asserted the native view means the error is an OIDC failure. It means one is in its causal chain, so `c_err_to_py_fmt` dropping its format string on that branch was reasoning from a premise that does not hold -- the caller cannot tell a pure auth failure from a transport failure an auth error caused, and dropping the transport's context is only ever wrong for the second. That branch is in fact unreachable today (its sole caller is the TCP flush path, and native rejects oidc_auth on TCP); the formatting is made correct anyway rather than left as a trap, and the unreachability is now stated where the next reader will look. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012QoXxcyoqduoW9Mi3ZSnyy
`proj.py doc` builds with `-nW --keep-going`, and this branch failed it: "build finished with problems, 6 warnings (with warnings treated as errors)". Every warning came from new content. Five were `:mod:`questdb.auth`` cross-references -- in docs/auth.rst, docs/installation.rst, CHANGELOG.rst (twice, reached through docs/changelog.rst) and the OidcError docstring rendered by docs/api.rst -- with no `py:module` target anywhere under docs/ for them to resolve to. Declaring the module in api.rst gives them one; the auth entries there are all fully qualified, so the directive changes nothing else. The links now resolve to a real anchor rather than merely stopping the warning. The sixth was `sqlalchemy.engine.Engine`, the return annotation of the autodoc'd `questdb.auth.sqlalchemy_engine`. It goes in `nitpick_ignore` rather than intersphinx on purpose: SQLAlchemy is an optional, lazily imported integration, and a mapping for it would make every docs build fetch the inventory of a dependency the package does not require, and fail when that host is unreachable. Readthedocs sets no `fail_on_warning`, so these degraded to unlinked text there while breaking the project's own doc command. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012QoXxcyoqduoW9Mi3ZSnyy
Keep callback targets on GC-visible owners and retain bearer holders on query readers until teardown. Honor permanent dataframe failures, retain typed auto-flush errors, validate snapshot expiry ranges, and reset the Python callback lock after fork. Correct source, adapter and snapshot typing and strengthen lifecycle, GC, LONG256 and mypy regressions. Pin c-questdb-client to 0211c8d4 for native provider fixes.
Pin c-questdb-client to 3dc38c73, including the token provider header formatting fix required by CI.
Keep bearer-provider ownership in GC-visible instance dictionaries so PyPy can collect sources that own their providers, pools or senders. Remove the redundant application-wrapper source reference. Use dictionary-field access during native-handle teardown to avoid recreating dying cpyext wrappers. Extend the ownership-cycle regression to standalone senders as well as pools. Validated full CPython and PyPy aggregates, focused provider suites, strict Sphinx documentation and diff checks.
test_the_gil_is_released_while_waiting failed on the cp314 leg of the
macOS arm64 wheels job ("5 not greater than 5"). It counted how often a
second Python thread woke from 5 ms sleeps during a 0.2 s wait, which
measures scheduling, not the GIL: token() releases the GIL for the whole
native wait. Locally, CPU-bound Python threads in the same process
reproduce the failure (9 of 20 runs with eight of them), while the
GIL-release behaviour is unchanged.
Make the check causal instead: the source returns only after another
Python thread has slept and re-acquired the GIL ten times and then
opened the gate. If token() held the GIL, that thread could not run, and
token() fails after cold_wait, as a mutant build without the nogil
section confirms. Under load the test only runs slower.
|
/azp run questdb.py-questdb-client-release |
|
Azure Pipelines successfully started running 1 pipeline(s). |
Preserve main-thread interrupts and signal-handler exceptions across token callbacks, propagate foreground-terminal OIDC dataframe failures, and share application-provider isolation across client attachments without rooting ownership cycles. Add bounded cooperative source draining via RefreshingTokenProvider.close(wait=True, timeout=...), reject cursor reentry while decoding borrowed batches, and document the shutdown and token-store coordination requirements. Add regression tests and typing coverage, and pin the native OIDC fixes at 426fe4c8f4d1097ecf43f334318506de564625f7. Validation: broader Python run (477 passed, 2 skipped); final focused run (233 passed, 15 skipped, 105 subtests passed).
Changes extracted from the OIDC / rotating bearer token PR (#133) that do not depend on either feature, so that PR can shrink to the feature itself. The c-questdb-client pin is unchanged. Breaking: - QuestDB.close() raises QuestDBError(InvalidApiCall) instead of waiting for a pool operation or lease held by the calling thread. Uses are counted per thread-state token, so a recycled thread ID cannot inherit a departed thread's lease; a sender lease follows the thread that last used it, a reader lease stays with the thread that borrowed it. - A sender's own connection_listener / error_handler can no longer call row(), dataframe(), new_buffer(), establish(), transaction() or the SenderTransaction operations on it. The guard is keyed on the owning sender, so peers sharing the default handler are unaffected. - A Buffer that a native call is modifying rejects reads and writes from any thread; a kept flush only borrows it for reading. - SenderTransaction.commit() after close raises QuestDBError instead of TypeError; a failed commit discards its rows itself. - An abandoned QueryResult reclaims its cursor before warning, and a ResourceWarning promoted to an error reaches sys.unraisablehook. Fixes: - Finalizers and GC never block on, or free, a cursor another operation is using; cursor close/cancel/pulls reject same-thread re-entry. - An unknown connection-event ordinal is dropped with one warning instead of being delivered as Connected; event and server-role enums bind the header constants. - DataFrame errors keep their class, in_doubt and sender_error when a hint or note is appended; the batch-too-large hint also covers the trailing sync. - A close waiting on a concurrent close that gives up closes the pool. - Small fixes: dataframe() buffer leak on a closed handle, PyWeakref_GetRef error handling, numpy enum names in the .pxd, connect() rephrases duplicate keys only for ConfigError, .pyi constructors. CI and tests: wheel jobs check out the submodule, PyPy pinned to 3.10 and 3.11, Windows cp314t wheels, pandas 3 only on 64-bit, pyarrow<26 with NumPy 1.x, PyYAML, authenticated questdb clone, JDK 25 module flags, quieter mock server, pandas 3 dtype fix, release-download retry, leak harness settling windows, manifest and suite-wiring guards. Docs: 6.0.0 changelog entries, 5.0-to-6.0 migration section, free-threaded wheel note, cross-repo merge procedure, polars.DataFrame(result).
Stack this PR on #160, which carries the changes extracted from it that do not depend on OIDC, token providers or #140. The extracted code now matches #160; what remains in this PR's diff against #160 is the feature, #140's UUID / fixed-size-binary work, and what #160 leaves here because it needs the newer native client (the config-string and callback-inbox caps, CredentialUnavailable, the native fixes reaching Python through the pin). Conflicts: took #160's version of the extracted code and wording, plus this PR's OIDC additions. Changelog and migration guide: #160's entries in #160's order, with this PR's own entries around them; dropped this PR's copies of the cursor re-entry and close-retry bullets that #160 now carries. Bump c-questdb-client to the head of questdb/c-questdb-client#183, now stacked on questdb/c-questdb-client#226.
test_far_future_source_results_are_classified_not_broken_snapshots read status.last_failure right after token() raised. With cold_wait=0.02, token() can give up before the refresher thread has run the source at all; it then raises the generic "no usable token" error and no failure is recorded yet, so last_failure was None (seen on the windows_i686 wheel job). Wait for the failure to be recorded before reading it, and do the same in the three sibling tests that share the race with a 200 ms cold_wait. test_a_classified_failure_reaches_the_caller also asserts the raised error's classification, so it gets a cold_wait that outlasts a slow first fetch: below the source's retry_after, token() still returns as soon as that fetch fails.
Bring in #140 (UUID, IPV4, BINARY, CHAR, DATE, LONG256 and GEOHASH columns). Both branches had reworked the same lifecycle, callback and UUID code independently, so most conflicts were semantic: - Callback dispatch: main's owner-token dispatch contexts replace this branch's _DispatchTarget stack. Kept this branch's global active-dispatch counter as the fast path for the per-row callback check, and its drop-and-warn for unknown connection-event kinds. - QuestDB.close(): main's bounded, one-way close (timeout, scoped-call refusal, Ctrl-C hardening) replaces this branch's per-thread lease attribution. Ported the OIDC rules on top: refused inside the pool's own persistence-warning callback, waits for in-flight diagnostics first, every wait bounded to two seconds inside any OIDC callback, and the provider released with the callbacks. The renderer-close test now expects the handle to stay closing after that bound. - Re-entry guards: this branch's native borrows and in-flight flags still refuse other threads and OIDC callbacks. Python that a dataframe() frame, or a reader query's bind values, runs on its own thread follows main's row and lease rules instead, as the re-entrancy and concurrency grids pin. SenderTransaction checks main's state first. - SenderTransaction.commit(): main's outcome rules (over once the flush was attempted, still open if refused before it), with this branch's callback guard. - DataFrames: main's planner and UUID object builder. This branch's tests that expected unlabelled 16/32-byte pandas columns to land as BINARY, or a short int.to_bytes to be refused, now expect main's behaviour. _direct_dataframe_run keeps the OIDC fail-fast gate under main's call-level in_doubt aggregation; widened errors keep their class and chain the original. - Kept this branch's col_target_t layout (no reserved LONG256 target). - Type stubs: SchemaOverride gains 'binary' and SupportsIndex bits. - CI: pipeline variables in list form, so the variable group and main's defaults coexist. OIDC and token-provider classes are excused from the re-entrancy and concurrency grids (test/api_surface.py). - Changelog: one 6.0.0 section under main's headings; dropped this branch's UUID and close() entries that main's supersede. Migration guide updated to match. Bump c-questdb-client to 456e8e72 (rotating-provider attach checks).
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).
|
superseded by #165 |
* feat(auth)!: add OIDC and rotating bearer tokens
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).
* test(auth): run the Arrow C stream tests on pyarrow 14
`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.
* fix(auth): record the native main-thread ident under gevent
`_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.
* update submodule
* feat(auth): let Python token providers stop background reconnects
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.
* update submodule
* fix(auth): keep row() publish errors typed, and other review fixes
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).
* fix(auth): let Sender and QuestDB construct on CPython 3.10-3.12
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.
* update submodule
* test(auth): wait for the CredentialUnavailable event before closing the 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.
* update submodule
* fix(ci): retry the QuestDB release download on a transient network error
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.
* update submodule
* fix(auth): let exit-time flushes reach token providers, bound durations
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.
* update submodule
* fix(auth): keep Sender.row() fast and token callbacks out of frames
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).
* fix(auth): stop a reader-lease GC crash and a dataframe() retry spin
_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.
* docs(auth): scope background token retries to QWP/WebSocket
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.
* fix(auth): keep a ws dataframe's token provider through a close
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.
* fix(egress): let close() and cancel() from another thread wait for a read
The cursor guard refused any thread while a native read was in progress,
though the changelog and comments limit it to same-thread re-entry.
Refuse only the lock's owner; other threads wait as before. Also name
QWP/UDP among the protocols that ignored token-provider config keys.
* docs: correct the Arrow C-stream token error and cursor close() notes
The token-provider guide and the 6.1.0 changelog said that a query whose
failover cannot get a token raises TokenUnavailableError, and the
__arrow_c_stream__ caveat limited the loss of the exception type to
oidc_auth. A result read through its Arrow C stream -- pyarrow.table(),
RecordBatchReader.from_stream(), polars.DataFrame() -- carries only an
error string, so with a bearer_token_provider the consumer raises its
own exception type, OSError from pyarrow, with the provider's message,
and an `except TokenUnavailableError` around it never matches. Document
that for both providers, name the readers that keep the typed error,
and add a test that pins both behaviours.
The changelog also said cursor close(), cancel() and pulls refuse
same-thread re-entry only while a native read is in progress. They also
refuse it while a batch is decoded, where 6.0 accepted close() and freed
the cursor once the decoder let go of the batch. Say so, and update the
_CursorHandle docstring, which still described close() as deferred.
* fix(auth): accept callable providers in the PG adapters
sqlalchemy_engine() and psycopg_connect() called auth.token() directly, so
a function returning a token -- a provider bearer_token_provider= accepts,
the documented `lambda: tokens.token()` included -- failed with a bare
AttributeError: at once from psycopg_connect(), and from sqlalchemy_engine()
only when its first connection opened. Both now take an OidcDeviceAuth or
any provider bearer_token_provider= takes, and refuse anything else with
OidcConfigError up front, as they do every other bad argument. A token that
is not a str, which the driver would turn into the password with str(), is
refused too.
Also:
- questdb.connect() and QuestDB.from_conf() reject the reserved
token-provider keys in Python, with Sender.from_conf()'s message, rather
than native's, which also names the C, C++ and Rust APIs.
- QuestDB.from_conf() no longer calls every auth rejection terminal: a
sender that has connected rides it out. The ConnectionEventKind
descriptions move from #: comments, which Sphinx does not render for the
compiled module, into the class docstring.
* fix(auth): keep an interrupted pool close from holding the OIDC lock
QuestDB.close() waited for its provider's persistence diagnostics with
`with _OIDC_DIAGNOSTICS_DRAINED:`. Condition.__enter__ and __exit__ are
Python, so a Ctrl-C or a raising signal handler that fired just after the
lock was taken, or as __exit__ began, left the process-wide registry lock
held by the closing thread. Every provider built, collected or warning on
another thread then blocked on it, and a blocked non-daemon thread hung
interpreter exit. Take the lock through the RLock's own C-level `with`, as
close() takes _state_cond through acquire().
Also stop OidcDeviceAuth from importing IPython to learn that no shell is
running. In a plain process with IPython installed, every default
construction loaded about 600 modules and 200 ms, and the changed teardown
order made a pool left open print an unraisable AttributeError at exit. A
running shell has always imported IPython already.
* docs(auth): warn that signal handlers can run inside provider calls
An application bearer_token_provider runs inside the client call that
asks for a token on the caller's thread: every ILP/HTTP flush, and a
connection the call waits for. CPython runs a pending signal handler at
the first Python code on the main thread, which there is the provider,
so a SIGTERM handler that closes the sender can run mid-flush. Its
close() is refused with InvalidApiCall and closes nothing, while the
same handler works with a fixed token=. Nothing said so.
Add a "Code that runs inside a client call" section to the token
provider guide, and point to it from the BearerTokenProvider docstring
and the bearer_token_provider parameter docs. Correct the changelog
entry that read as if signal handlers themselves were deferred: only
the exception a handler raises is. The refusal message no longer names
only the OIDC diagnostic callback.
* fix(auth): bound lease and pool waits inside bearer-token calls
A bearer_token_provider= runs on a native thread when a QWP/WebSocket
sender, query or pool reconnects, and the reconnect waits for it. A
provider, or a logging handler it triggers, that used a PooledSender
lease another thread held across an indefinite ACK wait (wait(),
flush(wait=True)) blocked on the lease lock forever: the ACK needed the
reconnect, and the reconnect needed the provider to return. The stuck
callback then also blocked interpreter exit, and a db.close() made there
waited out the 60 s lease limit. OIDC callbacks already gave up after
two seconds; token-provider calls now do too, raising
QuestDBError(InvalidApiCall) that names a token-provider callback.
A provider that let that refusal escape token() would have stopped its
clients for good, which is what an InvalidApiCall from a provider means.
The lease or pool it gave up on is busy, not broken, so the refusal is
marked and counts as retryable instead.
Also:
- RefreshingTokenProvider refuses unknown attributes, as Sender and
QuestDB do. `tokens.cold_wait = 5` was stored and read back while
configuring nothing, and `tokens.token = None` hid the method.
- ConnectionEventKind.CredentialUnavailable and the changelog said a
foreground QuestDB.dataframe() fails fast on a SocketError credential
failure. With bearer_token_provider= it retries a retryable one for up
to reconnect_max_duration_millis, as token_providers.rst says. Say so.
- The auto_flush_bytes docstring now says it also raises from any thread
while the sender is inside a native call.
* update submodule
* fix(auth): give Sender subclasses the generic attribute setter back
49e50f6 gave Sender a __setattr__ that refuses misspelt settings on
Sender itself, and every Python subclass inherited it. Each attribute
store on a subclass then went through the Cython hook, about 4 ns more,
and CPython 3.11+ stopped specializing those stores: a __slots__ store
took about twice as long.
A subclass whose MRO reaches Sender's __setattr__ now gets object's
setter and deleter back, so its stores skip the hook and CPython can
specialize them again. A class in between with its own __setattr__
keeps it. The hook is a class attribute, as Cython refuses an extension
type's own __init_subclass__ method.
* update submodule
* fix(auth): treat a client refusal escaping a provider as retryable
A bearer_token_provider= that raises QuestDBError with code
InvalidApiCall stops its clients for good. The client raises the same
code when it refuses a call, and bc690a1 exempted only the lease and
close waits a callback gave up on. A provider, or a logging handler it
triggers, that borrowed from a pool at its sender_pool_max cap and let
the "Connection pool exhausted" refusal escape stopped the reconnecting
sender for good: its wait failed with ConfigError and the rows in that
lease were never sent. An InvalidApiCall now stops the clients only
when the provider raised it itself. One raised inside the questdb
package refuses a call to a busy or closing client, not a broken
credential, and is retried. The traceback says where it was raised, as
it already does for signal handlers.
Also:
- A Sender subclass that lists a class defining __setattr__ or
__delattr__ after Sender, as in class S(Sender, Mixin), raises
TypeError when it is defined. Sender's own method comes first, so the
mixin's silently never ran. The changelog now lists this, and the
other subclass changes that Sender's instance dictionary and
__setattr__ bring, as breaking.
- The changelog said a waited-for connection fails at once on any
provider failure but a retryable TokenUnavailableError. A plain
exception is retried too, and only with initial_connect_retry on. Say
so there and in the token-provider guide.
- The max_name_len, protocol_version, connection_events_dropped,
connection_events_delivered, published_fsn(), acked_fsn(),
poll_error() and error_events_dropped() docstrings say they raise
InvalidApiCall while the sender is inside a native call.
* fix(auth): accept a timedelta for OidcDeviceAuth timeout
OidcDeviceAuth(timeout=timedelta(seconds=30)) raised OidcConfigError
saying the timeout must be a positive, finite number no greater than
120 seconds, while every RefreshingTokenProvider duration takes a
timedelta. Accept one, and name a wrong type as such rather than as an
out-of-range value.
Also:
- CHANGELOG: list the refusal of same-thread QueryResult.close(),
cancel() and PooledReader.close() during a read under the 6.1.0
breaking changes. 6.0 accepted such a close().
- The comment on the dataframe() token-probe branch said a different
provider failure is retried. A busy refusal is; any other OIDC
failure is raised at once.
* fix(auth): clear a failed flush's rows before converting its error
Sender.flush() converted the native error before clearing the internal
buffer, and with a token provider attached that conversion runs Python.
With oidc_auth= it builds an OidcError, and a pending signal handler
runs there; on PyPy, or on CPython with a full pending-call queue, a
token provider's parked interrupt is re-raised there too. A Ctrl-C or a
SIGALRM deadline during an ILP/HTTP flush that then failed, on an
identity-provider outage say, raised from flush() with the failed rows
still buffered. The next flush sent them again, twice over if the
caller re-ran the ingestion, which the flush documentation presents as
safe: a failed flush discards its rows.
Clear the buffer before converting the error, deciding the
BatchTooLarge exemption from the native error code, as
flush_and_get_fsn() and the dataframe auto-flush already do.
* fix(auth): deliver diagnostic signal exceptions on PyPy
On PyPy, an exception a Python signal handler raised during an OIDC
persistence warning inside a client call -- an ILP/HTTP flush that
refreshed the token, say -- never reached the caller unless it was a
KeyboardInterrupt: a SIGTERM handler's sys.exit() and a SIGALRM
deadline's TimeoutError were dropped, and Ctrl-C was re-armed, which
ran a custom SIGINT handler again at every later bytecode of the
callback (four times for one signal).
Park it as CPython does. PyPy delivers no pending call, so the
native-return boundary raises it, as it already does for token
callbacks. OidcDiagnosticSignalTest now runs on PyPy, except two tests
that depend on CPython behaviour: cpyext runs an exception's __setattr__
when compiled code raises it, and PyPy runs a second pending handler
only at a later bytecode.
* fix(auth): preserve token provider errors in connect
Keep TokenUnavailableError out of duplicate-key diagnostic rewriting so callers retain the provider's classification and retry metadata.\n\nCover sender and reader warm-up with retryable and permanent provider failures.
* docs(auth): clarify terminal WebSocket credential failures
* fix(auth): keep Sender.row() specialized after its __dict__ is read
Sender gained an instance dictionary for the bearer-token holder, which
__cinit__ drops on CPython so the method lookup of `sender.row(...)`
stays cached. Any later read of `__dict__` -- dir(), vars(),
inspect.getattr_static(), an IDE completing `sender.` -- recreated it,
and nothing dropped it again: every later row() on that sender took the
generic lookup, about 13 ns (4%) per row on CPython 3.13.
dir() now drops the dictionary it recreates, and every flush drops one
any other read left, so the cost lasts at most until the next flush.
Only an empty dictionary of a Sender itself is dropped: the client
stores nothing there on CPython, and a subclass keeps its own.
* fix(auth): stop transports silently skipping token() overrides
A RefreshingTokenProvider subclass that overrode token() or
on_rejected(), passed as bearer_token_provider=, had its native handle
attached as is: every flush, connect and query read the native cache
and never called the override, while the PG-wire adapters and
bearer_token_provider=tokens.token did. Such a subclass, or an instance
attribute shadowing either method, is now attached as an application
provider, so its clients call its methods. One that overrides neither
still attaches its native provider.
oidc_auth= cannot honour an override: connections take the token from
the native OIDC provider. An OidcDeviceAuth whose token() is overridden
is now refused there with TypeError instead of being attached and
silently bypassed. The dataframe() fail-fast probe reads the native
provider through a private _foreground_token(), which the probe tests
now intercept in place of token().
* fix(auth): stop clients of closed overriding token providers
RefreshingTokenProvider subclasses that override token() or on_rejected()
use the application-provider bridge. After close(), their permanent token
failures were still retried by background reconnects, and pooled
flush(wait=True) could wait forever.
Report failures from closed refreshing providers as terminal through the
bridge, preserving main-thread interruption handling. Attached overrides
report ConfigError; attaching an already-closed override raises the same
nonretryable AuthError as the native-cache provider.
Also address the minor review findings:
- Give refreshing-provider subclasses Sender's generic attribute handling
and mixin-order guard.
- Remove the unused foreground OIDC classifier argument.
- Document closure behavior and include Buffer.dataframe() in the list of
operations guarded during native modification.
Add regressions for both override types, closed attachment, background
connects, pooled rows and flush waits, and subclass attribute handling.
Validation:
- CPython 3.13: full mock suite passed (1626 tests, 61 skipped).
- Auth suite passed (330 tests, 3 skipped).
- CPython 3.10 and 3.12: builds and token-provider suites passed
(83 tests, one optional-mypy skip each).
- Sphinx -nW --keep-going and git diff --check passed.
* test(auth): let the concurrent-attach test pass on PyPy mid-suite
test_concurrent_provider_attachments_publish_one_holder snapshots the
callback registry before it runs, then waited for the registry to equal
that snapshot again. On PyPy, an earlier test's provider entries are
garbage but not yet collected when the snapshot is taken, and the test's
own gc.collect() frees them too, so the registry ends up a strict subset
of the snapshot and the wait timed out. Since 4b190ee added the test that
runs just before it, it failed in every class and full-suite run on PyPy,
failing the PyPy wheel build. Nothing leaked: every entry the test
registered was released.
Wait for the registry to be a subset of the snapshot instead, which the
sibling tests' checks already allow for.
* fix(auth): make token-provider argument errors QuestDBErrors too
OidcDeviceAuth and the PG-wire adapters report a bad argument as
OidcConfigError, a QuestDBError with code ConfigError. The token-provider
API raised a plain TypeError or ValueError instead: for a
RefreshingTokenProvider source, duration or name, an ExpiringToken value,
a TokenUnavailableError retry_after, and a bearer_token_provider= or
oidc_auth= of the wrong kind. An `except QuestDBError` around provider
setup caught a bad OidcDeviceAuth timeout, but not a bad
RefreshingTokenProvider cold_wait.
Raise a TypeError or ValueError that is also a QuestDBError with code
ConfigError, so either except clause catches it. Existing handlers of the
built-in errors keep working. RefreshingTokenProvider.on_rejected()
validates its arguments the same way; before, a None token raised
AttributeError and a status beyond the C int range OverflowError. A
provider failure message still names the built-in error, not the private
class.
* fix(auth): stop clients of a closed provider reached through a wrapper
A RefreshingTokenProvider that an application provider calls --
`lambda: tokens.token()` or `tokens.token`, documented and tested for
401 refresh -- did not end its clients when closed. Its "is closed"
failure reached native as an ordinary non-retryable error, which
QWP/WebSocket background reconnects retry for good: a pooled
flush(wait=True) of rows already published never returned. Attaching
the bound method of an already-closed provider was accepted, unlike the
provider itself, so an async sender took rows it could never send.
_tp_token now marks a closed provider's failure and _tp_sink_exception
reports it as terminal, as for a closed overriding subclass: clients
stop with ConfigError. A method bound to a closed provider is refused
at attach with the provider's own error.
Also:
- RefreshingTokenProvider.__exit__ is stubbed Literal[False], so mypy
no longer reports a missing return after `with` blocks.
- A source whose fetch_token is not callable raises TypeError, or is
called itself when callable, instead of failing every fetch for good.
- An uninitialized provider passed as bearer_token_provider= raises the
ConfigError ValueError an uninitialized oidc_auth= does, and a
non-str name raises TypeError.
* fix(build): keep PyPy builds importable with Cython 3.3.1
Cython 3.3.1 builds PyPy's extension types from type specs by default
(cython/cython#7947). For a cdef class that declares both
`cdef dict __dict__` and `cdef object __weakref__` -- Sender,
_TokenProviderHandle and _ApplicationTokenProvider -- it puts two
Py_tp_members slots in the spec, which the interpreter rejects when the
module is imported:
SystemError: Multiple Py_tp_member slots are not supported
so the linux_x64_pypy wheel job failed at `import questdb`. CPython
rejects the same spec when type specs are on; it builds static types by
default, so it is unaffected.
Define CYTHON_USE_TYPE_SPECS=0 for PyPy builds, keeping the static
types PyPy used up to Cython 3.3.0.
* docs(auth): list unix_sock among rejected PG destination keys
The PG-wire adapters reject unix_sock in connect_args / connect_kwargs
like the other destination keys -- pg8000 dials that Unix socket
instead of the validated host -- and the CHANGELOG and the adapter
docstrings already say so, but the guide in docs/auth.rst left it out.
The comment explaining _DESTINATION_PARAMS now covers it too.
* update submodule
* update submodule
* update submodule
* docs(auth): say when a permanent source failure ends a connection
The token-provider guide said a connection the caller waits for -- a
synchronous initial connect, or an eager connect or pool borrow with
initial_connect_retry=on -- fails at once when the source of a
RefreshingTokenProvider raises TokenUnavailableError with
retryable=False. The connection does not retry that failure, but the
provider's cold wait comes first: the provider retries a failed fetch
whatever its classification, and the connection waits up to cold_wait
for a retry to succeed. With the default options a synchronous connect
failed only after about 21 s.
That wait follows the dynamic-credential specification (§5.3, §5.4)
and matches the Java client. The C header now describes it the same
way (questdb/c-questdb-client#228), and the guide now says a permanent
failure ends the connection when the provider's cold wait does.
A new test covers it: through a refreshing provider with a 0.5 s cold
wait, a permanent source failure is retried within the wait and ends a
synchronous connect after it, well inside the connect's 10 s budget.
* update submodule
* fix(auth): type bearer_token_provider on every entry point
The type stubs declared bearer_token_provider as Optional[Any] on
QuestDB.from_conf, Sender, Sender.from_conf and Sender.from_env, and
questdb.connect left it unannotated, so a type checker accepted any
value there -- an int, or the token string itself -- and the mistake
surfaced only at runtime. They now take the
Union[BearerTokenProvider, Callable[[], str]] that the PG adapters
already accept. connect() imports BearerTokenProvider only for type
checkers, so importing questdb still does not load questdb.auth.
The typing fixture now passes a refreshing provider, an object with
token(), a callable and a bound token() through the five entry points,
and marks a wrong value on each as a type error that
--warn-unused-ignores keeps honest.
* update submodule
* test(auth): fix login capture race and optional pandas guard
* Update examples/oidc_device_auth.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* fix(auth): resolve connect type hints at runtime
* fix(auth): update native pin for exception-safe token copying
Pull in questdb/c-questdb-client#228 at 5de775e975fa4d17be8b2cd5e71d79d38e79f4cf, which frees the native token if the C++ string copy throws.
* fix(auth): normalize oversized token timing arguments
* fix(auth): defang embedded schemes in refused sign-in prompts
Update the native pin to include renderer callback deadline accounting.
* update submodule
* Update native client with bounded cold-wait test
* fix(auth): align terminal failure cancellation semantics
Pin the native client to 29468d7e2670792217423f6bba91c8989c565991,
which commits terminal device-flow failures before renderer callbacks.
Document cancellation during on_failure as a no-op and verify that the
original denial or timeout survives while the provider remains reusable.
* fix(auth): pin native sign-in recovery fix and add regression
* test: measure promoted column allocations instead of RSS
* fix(auth): report ExpiringToken expiry as datetimes
ExpiringToken stored expires_at and refresh_at as float epoch seconds, even
when they were given as timezone-aware datetimes, while
RefreshingTokenProvider.status reports token_expires_at, last_success_at and
last_failure.at as datetimes. Ordering the two raised TypeError, and ==
returned False for the same instant.
The attributes now hold timezone-aware UTC datetimes; the constructor still
accepts a datetime or epoch seconds. ExpiringToken is new in the unreleased
6.1.0, so no released API changes.
* fix(auth): pin the native refresh-spacing and status-padding fixes
Picks up questdb/c-questdb-client#228 commits 985e472a and 87a7ee12:
- A RefreshingTokenProvider with min_refresh_interval below a millisecond
-- 0, or up to 0.0004 s, which this wrapper rounds to 0 ms -- no longer
fetches without pause while its source returns a refresh hint at or
before receipt, as Azure Identity does with a cached token during an
IMDS outage. The new test counts source calls over 0.3 s: about 40,000
before, at most 300 now.
- questdb_token_provider_get_status zeroes the padding of its snapshot.
* docs(auth): say that bearer_token_provider= refuses an OidcDeviceAuth
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.
* fix(auth): pin the native fix for cut-off device-flow poll replies
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.
* test(auth): cover a device-flow poll reply cut off mid-body
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.
* fix(auth): pin the native shared-401 and sign-in target fixes
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.
* fix(auth): accept datetime.max expiries and lone-surrogate refusals as 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.
* fix(auth): keep gevent greenlets apart in token-provider callbacks
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.
* fix(auth): pin the native token-store, sign-in target and forced-refresh 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.
* fix(auth): treat what a provider can never recover from as permanent
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.
* fix(auth): keep a signal that interrupts a callback's own error handling
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.
* docs(auth): say PyPy keeps a provider-owned client alive through a lease
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.
* docs(auth): scope sqlalchemy_engine's sign-in note to OidcDeviceAuth
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.
* fix(auth): keep a provider failure that cannot be printed out of later 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.
* docs(auth): say that a TokenUnavailableError never stops reconnects
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.
* docs(conf): document the request_durable_ack levels this release accepts
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.
* fix(auth): pin the native display-text cap and provider-close docs
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(auth): give the token() interrupt test the default IdP timeout
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.
* update submodule
---------
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary
Adds native-backed OIDC device-flow authentication for QuestDB Enterprise. The
Python API runs OAuth 2.0 Device Authorization Grant (RFC 8628) through the
native QuestDB client, including from remote Jupyter kernels where the browser
and Python process are on different machines.
Discovery, endpoint validation, token selection, caching, refresh, persistence,
and concurrency control use the native implementation. Python provides the
public authentication API, Jupyter/terminal rendering, PG-wire adapters, and
integration with QuestDB transports.
It also adds rotating Bearer-token providers, for machine credentials that
rotate: Microsoft Entra ID managed identities and service principals, OAuth2
client credentials, a secrets vault.
bearer_token_provider=accepts a nativeRefreshingTokenProvideraround a token source you write, or any callable orobject that returns the current token. They follow the cross-language
dynamic-credential specification shared with the Java client; see Rotating
Bearer tokens.
Merge order
This branch temporarily carries the UUID / fixed-size-binary changes that belong
to #140 (
a363777). They are here because bumping thec-questdb-clientsubmodule past questdb/c-questdb-client#186 — which added
reverse_uuid_bytesand has been on
mainsince 18 Aug — obliges the Python side to supplycanonical RFC 4122 bytes; without that adaptation every UUID would be silently
stored byte-reversed. The QWP wire bytes themselves are unchanged and still
match the Java client.
#140 should land first. This branch's copy then collapses into the merge
base and this PR reduces to the OIDC and token-provider features alone. This
branch currently documents the combined changes under
6.0.0, with a5.0-to-6.0 migration guide; reconcile those headings when merging #140.
User-visible breaking changes
The 5.0-to-6.0 migration guide records eleven changes that may require action:
Arrow-backed query results; remove any application-side byte reversal.
use the
arrow.uuidlabel, preserved whole-table/stream Arrow fieldmetadata (
questdb.column_type=uuidorquestdb.column_type=long256),or
schema_overridesas documented.schema_overridestuple is accepted only for('geohash', bits); values such as('symbol', 16), whose argument waspreviously discarded, must become
'symbol'. The publicquestdb.SchemaOverridealias describes accepted values.error_inbox_capacityconfig-string key,reject capacities above 65,536.
QuestDBError(InvalidApiCall), on every entry point:Sender.from_conf,Sender.from_env/QDB_CLIENT_CONF,questdb.connectandQuestDB.from_conf.SenderTransactionafter its sender was closed now raisesQuestDBError(InvalidApiCall)instead of an internalTypeError. A commitwhose flush fails leaves the sender's buffer empty and the transaction
completed, exactly as in 5.0 -- that is not a change.
QueryResult'sResourceWarningto an exception, the finalizer now lets it reach
sys.unraisablehookinsteadof swallowing it, after releasing the cursor. Otherwise normal warning filters
apply as before. Close results deterministically (preferably with
with).already admitted, including those paused before acquiring the GIL. Renderer
and persistence-warning callbacks must return promptly: a blocked callback
can delay process exit, even on a daemon sign-in thread.
failover_max_duration_mswhile attemptsremain, after a last round rejected on role, at the WebSocket upgrade or at
TLS, now raises that
RoleMismatch/HandshakeError/TlsErrorinsteadof the connection failure that started the failover.
QuestDB.close()raisesQuestDBError(InvalidApiCall)instead of waitingwhile the calling thread holds a pool operation or lease. That includes a
sender lease handed to a worker that has not used it yet, which 5.0 waited
for; have the worker use the lease before closing on the borrowing thread.
sender's own
connection_listenerorerror_handler,row(),dataframe(),new_buffer(),establish(),transaction()and theSenderTransactionoperations raiseQuestDBError(InvalidApiCall), asflush()andclose()already did. 5.0 acceptedrow()there; handlistener events to another sender or to the owning thread instead.
rejects its credential with HTTP 401 or 403 on a reconnect, a fixed
token=orusername=/password=included: it keeps reconnecting withcapped backoff, keeps its unacknowledged rows, and reports each attempt as
ConnectionEventKind.AuthFailed. 5.0 stopped the sender at the firstrejection and raised
AuthErrorfrom its next call. A connection that iswaited for -- a sender's first connection, an eager
questdb.connect--still fails at once. Code that relied on the sender stopping must close it
itself.
See
CHANGELOG.rstanddocs/migration.rstfor exact affected entry points andmigration examples.
Usage
Interactive sign-in is explicit.
sign_in()is the only operation that mayprompt or open a browser;
token(),headers(), and transport connect/reconnectpaths only use cached or silently refreshable credentials and otherwise raise
OidcInteractionRequired.questdb.connect,Sender, andSender.from_confretain the shared nativeprovider and request a current token on every connect or reconnect. A fixed
token=is not required and is mutually exclusive withoidc_auth=.For PG-wire,
sqlalchemy_engine()injects a current token as the_ssopassword on each new pooled connection, while
psycopg_connect()captures thecurrent token for one connection. Other clients can use
auth.token()orauth.headers()after explicit sign-in.Configuration and lifecycle
OidcDeviceAuth.from_questdb()discovers configuration from QuestDB's public/settingsendpoint; explicit constructor arguments can override discovery,and the direct constructor supports fully explicit IdP endpoints.
groups_in_token=Trueselects the ID token; otherwise the access token isused. It does not modify
scope: the configured scope is sent verbatim onthe initial device-authorization request, including in groups mode. Refresh
requests intentionally omit
scope, matching the Java client, so the IdPpreserves the scope originally granted. Include
openidexplicitly when theidentity provider requires it to issue an ID token.
FileTokenStore.at_default_location()enables opt-in native persistence withatomic files, owner-only permissions, and cross-process refresh coordination.
On non-Unix platforms the bundled store rejects mutation-required operations
before creating credentials or transient coordination metadata; use
memory-only authentication there. Custom Python token stores are not
supported (the native Rust API alone accepts a custom/keychain-backed store).
terminals, with optional QR output. Renderer callbacks receive bounded,
native display-normalized but still untrusted text. Custom renderers must
encode it for their output sink and use only the native-vetted
browser_targetfor actionable URLs.questdblogger,often on a token-refresh thread. A QWP/WebSocket ACK wait made inside such a
handler raises
OidcInteractionRequiredpromptly once its sender'sreconnect needs a token the provider cannot supply until the handler
returns; the frame stays queued. ACK waits on other threads are not
rejected: they wait for the handler to return.
close()permanently closes a provider and cancels a device flow, refreshcoordination, or token-store lock wait running on another thread; it is safe
from any thread, including a renderer callback, so a notebook "Cancel" button
can call it.
OidcDeviceAuthis a context manager.Ctrl-Cduringsign_in()cancels only the current attempt and raisesKeyboardInterrupt;the provider and its attached transports remain usable. Operations on a
closed provider -- including attaching it to a new
Sender, pool or reader-- raise
OidcCancelledError, exceptclear(), which staysavailable so the persisted credential can still be removed;
cancel_sign_in(), which remains an idempotent no-op when no flow isrunning; and
config, which remains readable.OidcErrorsubclasses, includingOidcConfigError,OidcNetworkError,OidcInteractionRequired,OidcDeviceFlowError,OidcTimeoutError, andOidcCancelledError, allQuestDBErrorsubclasses. Theircodereports the failing call's nativecategory and is not a recovery instruction: with no usable credential,
auth.token()reportsAuthErrorwhile an HTTP sender flush reportsSocketError, yet retrying cannot succeed until someone signs in. CatchOidcInteractionRequiredbefore any retry logic keyed oncode; itsacquisition_busyflag tells a wait-and-retry case (another thread isacquiring) from one that needs
sign_in().insecure=Trueapplies only to QuestDB discovery transport. Attach theprovider to
https::/wss::transports: over plaintexthttp::/ws::to a non-loopback host the token travels in cleartext.
The public surface comprises
OidcDeviceAuth,OidcConfig,FileTokenStore,Renderer, the PG-wire adapter functions, and the typed exceptions. There is nopublic
TokenSet;token()returns the selected token string.OIDC itself adds no optional Python dependency. SQLAlchemy, psycopg/psycopg2,
qrcode, Pillow (for notebook PNG QR output), and IPython are imported lazily
for their respective integrations.
Rotating Bearer tokens
bearer_token_provider=works onquestdb.connect,QuestDB.from_conf,Sender,Sender.from_confandSender.from_env, and is mutuallyexclusive with
oidc_auth=,token=,username=andpassword=.Passing an
OidcDeviceAuththere raisesTypeErrorpointing atoidc_auth=, which is unchanged.questdb.auth.RefreshingTokenProvideris the native refreshing cache. Itssource -- a callable or an object with
fetch_token()-- returns anExpiringToken, a(token, expires_at)tuple, or any object withtokenand
expires_on. Azure Core'sAccessTokenandAccessTokenInfoare suchobjects, so Azure Identity works without this package importing it. The
source runs only on the provider's own thread;
token(),await_ready()and
on_rejected()release the GIL.token()and an optionalon_rejected(token, http_status), works as an application provider. It iscalled on every connection attempt, possibly on a native thread.
questdb.auth.TokenUnavailableErrorclassifies a source's failure asretryable or permanent; any other exception counts as retryable. A
connection that is waited for retries only a retryable failure, while a
connected sender keeps retrying either kind. A provider's failure surfaces
as a
TokenUnavailableError, aQuestDBErrorthat keeps the transport'serror code.
the endpoint once with a new one, unless the
WWW-Authenticatechallengenames an error a new token cannot fix. A rejection that persists is handled
by phase: a connected sender rides it out (see the breaking change above),
a store-and-forward slot left by an earlier sender rides it out and is then
left on disk for the next session, and a query fails, with its pooled
connection replaced for the next one.
live in an id-keyed registry owned by their Python wrappers, which clients
keep alive, and every callback passes the process-wide callback gate that
is drained before interpreter finalization. A provider is not usable across
fork(). A provider used overhttp::orws::, anoidc_auth=oneincluded, is warned about once per process on the
questdblogger.token_providerand
azure_*keys are rejected on every protocol, and there is noazureextra. The token-provider guide shows Entra ID and OAuth2
client-credentials recipes in application code instead. This deviates from
the specification, which proposes
token_provider=azurewith an optionalPython extra; the note asking it to make connect-string providers optional
is still to be raised on feat(qwp): add refreshing token providers for Entra ID authentication java-questdb-client#102.
Documentation and example
docs/auth.rstand API reference entries indocs/api.rst.docs/token_providers.rst, withEntra ID and OAuth2 client-credentials recipes and a section on rejections
that persist, plus API reference entries.
examples/oidc_device_auth.py, including native transport, PG-wire,manual-token, and opt-in persistence examples. The example requires a live
OIDC-enabled QuestDB Enterprise deployment and a human sign-in, so it is not
part of the automated example suite.
Test scope
test/test_auth.pycontains the Python binding/integration test suite andrequires the compiled
questdb._clientextension. It is imported bytest/test.pyfor the aggregate CI run.The focused tests cover:
views, typed errors, and the interactive/non-interactive lifecycle split;
renderer interface validation, and provider/renderer ownership and GC;
FileTokenStoreacceptance and default-location configuration;Sender,Sender.from_conf, and lazyquestdb.connect, including invalid types and fixed-token conflicts;before token retrieval or connection creation;
close(), closing from a renderercallback,
Ctrl-Cduringsign_in(),clear()afterclose(), andrejection of an explicitly closed provider at attach;
Spyder, and stderr-vs-stdout redirection), token-store path resolution, and
propagation of the native error code onto
OidcError.These Python tests use
OidcTestServerto simulate discovery, deviceauthorization, polling, token acquisition, and refresh. The human-in-the-loop
live-IdP example remains intentionally outside the automated suite.
test/test_token_provider.py, also imported bytest/test.py, covers thetoken providers:
ExpiringTokenforms and validation, andTokenUnavailableErrorclassification;
RefreshingTokenProvider: every source shape, classified and unclassifiedfailures, a forced refresh through
on_rejected,close()failing everyholder, the GIL released while waiting, the source released with the
provider, argument validation, and the protocol classes;
a
Senderand to a pool against a QWP/WebSocket mock that checks theAuthorizationheader: a 401 heard byon_rejectedand retried once, apermanent failure ending a synchronous connect and a retryable one
retried, conflicting arguments, the reserved configuration keys, the
holder's lifetime, and the cleartext warning;
reprof a token, a provideror its status.
Additional maintenance
32-bit wheels, and makes the parquet dtype expectation compatible with pandas
3's string dtype.
JDK 25.
server errors.
Interactive detection and browser opening
sign_in()prompts by default, wherever it is called from. There is deliberatelyno TTY check: a missing TTY is not evidence of a missing human, and refusing on
it turned away sign-ins that work —
prog 2>&1 | tee logat a real terminal, aprocess supervisor, an IDE run configuration. The one exception is a notebook
executed headlessly (papermill,
nbclient,nbconvert --execute), whose kernelstates at protocol level that it accepts no input; there
sign_in()raisesOidcInteractionRequiredimmediately. Passinteractive=Falseto get thatfail-fast behaviour anywhere else, such as cron or CI.
open_browseris tri-state for the same reason: the defaultNoneopens abrowser except inside a Jupyter kernel, where it may be on a different machine
from the reader;
Trueopens one anyway — correct for a localjupyter lab,where the previous unconditional suppression was simply wrong and had no
override — and
Falsenever does.Submodule pin
This branch pins
c-questdb-clientat3dc38c73896fa05623aba1c3870888cd5c7a2743,the current head of questdb/c-questdb-client#183. It adds the refreshing token
providers and phase-specific credential-failure handling on top of the OIDC
integration. Compared with the earlier
c3c58866pin, it also includes the C++test and gitleaks updates and a merge of native
main(6317e5d3, #195:maximum GEOHASH values and Arrow FFI validation). The two must merge together:
line_sender.pxdbindsthat PR's
oidc.h,client.handtoken_provider.hsurface and does notcompile against the current
main. That pin also carries changes to APIalready present on native
main:ReaderConfig::upgrade_headersnow returnsResult<Vec<_>>rather thanVec<_>for direct Rust callers, callback inboxcapacities are capped at 65,536, config strings are capped at 1 MiB, a
QWP/WebSocket sender that has connected rides out an HTTP 401 or 403 instead
of becoming terminal, and the reserved token-provider configuration keys are
rejected on every protocol. All but the Rust signature change reach Python;
CHANGELOG.rstdocuments the caps and the 401/403 change under Breakingchanges and the reserved keys under Other changes. The TTY behavior and
non-copyable C++
device_authconcern APIs introduced inside the native PRitself, so they do not break a pre-existing API.