Repository navigation
feat(pyo3): External auth — Python-callable token provider - #16
Closed
vikrantpuppala wants to merge 1 commit into
Closed
vikrantpuppala wants to merge 1 commit into
vikrantpuppala wants to merge 1 commit into
Conversation
Phase 1 step 5. Wires a Python callable into the kernel's
AuthConfig::External slot so the connector can delegate OAuth /
MSAL / federation flows back to its own auth provider rather than
re-implementing them in Rust.
New Python surface:
- Session(host, http_path, *, auth_type='external', token_callback,
catalog=None, schema=None) — `token_callback` is a no-arg callable
returning `str`. The kernel invokes it once per HTTP request that
needs auth; the callable owns its own caching / refresh.
- Session(host, http_path, *, auth_type='pat', access_token, ...) —
explicit PAT form.
- Session(host, http_path, *, access_token, ...) — implicit PAT
(auth_type defaults to "pat" when access_token is provided), kept
for backward compatibility with Phase 1 callers.
Errors map cleanly:
- Python exception inside the callback → KernelError(code=
'Unauthenticated', message='Python token_callback raised: ...')
- Non-string return → KernelError(code='Unauthenticated',
message='Python token_callback must return str: ...')
- Empty string → KernelError(code='Unauthenticated', message='...
returned an empty string')
Implementation notes:
- New `auth.rs` module owns the kwargs→AuthConfig translation and
the `PythonTokenProvider` trampoline (impl async TokenProvider for
a Py<PyAny>). GIL is re-acquired on the kernel-spawned tokio
worker via Python::attach.
- pyo3's `extension-module` feature moved to an opt-in Cargo feature
so `cargo test -p databricks-sql-kernel-pyo3` can link libpython
and run the trampoline's unit tests. Maturin enables the feature
via pyproject.toml when building the wheel.
- 4 Rust unit tests cover token roundtrip, Python exception
mapping, non-string-return rejection, empty-string rejection.
These run on cargo test without any live deps.
KNOWN LIMITATION (to be addressed in a follow-up kernel PR):
The kernel's `build_auth_provider` currently returns `InvalidArgument`
for `AuthConfig::External` ("reserved; v0 wires PAT + OAuthM2M +
OAuthU2M only"). End-to-end use of `Session(auth_type='external',
...)` will surface that error verbatim until the kernel wires
External into its HTTP-client auth path. This is a separate kernel
PR (likely a small ExternalAuthProvider adapter using
tokio::task::block_in_place + Handle::current().block_on to drive
the async TokenProvider from the sync AuthProvider trait).
The PyO3 trampoline itself is fully covered by the unit tests in
this PR; the wrapper layer is done.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
5 tasks done
Collaborator
Author
|
Collapsed into #13 — that PR now carries all four Phase 1 commits (scaffold, metadata, async, external auth) as a single review. Closing this one to consolidate the review. |
vikrantpuppala
added a commit
that referenced
this pull request
May 15, 2026
## Summary Phase 1 of the PySQL × kernel integration plan ([design](docs/designs/pysql-kernel-integration.md), [doc PR #12](#12)). Adds a workspace-member sub-crate at \`pyo3/\` that builds a Python extension module \`databricks_sql_kernel\` via maturin. **PAT auth only.** Sync \`execute()\` + async \`submit()\` execution paths; full metadata surface. Originally landed as four stacked PRs (#13–#16); collapsed into this one because they ship as a single Python module and reviewing the stack added overhead without adding signal. Each step is preserved as its own commit on the branch so the work is still browsable step-by-step. ## Commits | Commit | What it adds | |---|---| | [\`b41acc0\`](b41acc0) | Scaffold — \`Session\`, \`Statement\`, \`ExecutedStatement\`, \`KernelError\`. PAT auth, sync \`execute()\` | | [\`6bc3ecd\`](6bc3ecd) | \`Metadata\` + \`ResultStream\` — all 10 metadata methods, shared fetch helpers | | [\`0bd898f\`](0bd898f) | Async statement — \`Statement.submit() -> ExecutedAsyncStatement\` with \`status / await_result / fetch_result / cancel / close\` | | [\`c58710d\`](c58710d) | (Reverted in 4847a07) External auth POC | | [\`294730a\`](294730a) | Address first-round review — typed errors, \`run_kernel!\` macros, pytest harness | | [\`b60166a\`](b60166a) | Wire \`session_conf\` through \`Session(...)\` | | [\`4847a07\`](4847a07) | **Drop External auth.** Phase 1 ships PAT-only; OAuth decision deferred | | [\`da7a0c8\`](da7a0c8) | Address second-round review C1/C3/Statement.close docstring | ## Python surface \`\`\`python import databricks_sql_kernel as k s = k.Session( host=..., http_path=..., *, auth_type="pat", # only "pat" supported today; reserved variants raise ValueError access_token="dapi...", catalog=None, schema=None, session_conf={"ANSI_MODE": "false", ...}, # SEA session_configuration map, passed through verbatim ) # Sync execute stmt = s.statement() stmt.set_sql("SELECT * FROM t") exec_ = stmt.execute() table = exec_.fetch_all_arrow() # pyarrow.Table # Async submit + poll async_exec = stmt.submit() state, failure = async_exec.status() # (Pending|Running|Succeeded|Failed|Cancelled|Closed, Optional[KernelError]) rs = async_exec.await_result() # ResultStream — same fetch surface # Metadata (all kwarg-only) m = s.metadata() m.list_catalogs() m.list_schemas(catalog="main") m.list_tables(catalog="system", schema_pattern="information_schema") m.list_columns(catalog="system", schema_pattern="information_schema", table_pattern="tables") m.primary_keys(catalog=..., schema=..., table=...) m.foreign_keys(parent_catalog=..., foreign_catalog=..., foreign_schema=..., foreign_table=...) m.functions(...); m.procedures(...); m.type_info(); m.table_types() \`\`\` \`KernelError\` is a \`create_exception!(... PyException)\` subclass; structured fields (\`code\`, \`message\`, \`sql_state\`, \`error_code\`, \`vendor_code\`, \`http_status\`, \`retryable\`, \`query_id\`) ride as \`setattr\` attributes so abi3 stays clean (abi3 forbids subclassing native exception types via pyclass). Connector callers read \`err.code\` / \`err.sql_state\` directly. Every kernel call goes through \`py.detach(...)\` so the GIL releases during I/O. Arrow batches cross via \`arrow-pyarrow\` (zero-copy buffers). ## Workspace conversion Root \`Cargo.toml\` grows a \`[workspace]\` table with \`members = [".", "pyo3"]\`. The kernel stays the root crate; future bindings (napi-rs, etc.) slot in as additional members. ## Server-side cleanup model \`Statement.close()\` is a **no-op on the wire** — it just drops the local lifecycle owner. The kernel's three Drop impls handle server-side cleanup: | Drop on… | Server RPC? | What it does | |---|---|---| | \`Statement\` | No | Flips validity flag locally | | \`ExecutedStatement\` | **Yes** — fire-and-forget \`CloseStatement\` on the session runtime | Releases server-side statement | | \`ExecutedAsyncStatement\` | **Yes** — same | Same | Each executed handle owns its own \`Arc<SessionInner>\`, so it outlives the parent \`Statement\` cleanly and its own Drop hits the wire. Documented in the \`Statement.close()\` docstring in [\`da7a0c8\`](da7a0c8). ## Known gaps (will be follow-ups) - **Auth: PAT only.** OAuth M2M / U2M / federation / External-callback are reserved in the kernel's \`AuthConfig\` enum but not yet wired through PyO3. The connector backend ([databricks/databricks-sql-python#787](databricks/databricks-sql-python#787)) raises \`NotSupportedError\` for non-PAT, pointing users at \`use_sea=False\`. - **Parameter binding.** \`Statement\` exposes only \`set_sql\` today — no \`bind_param\` / \`bind_param_named\` / \`statement_conf\`. SQL-literal queries only this phase. - **\`unsendable\` pyclasses.** Each \`Session\` owns a multi-thread tokio runtime; the pyclasses are \`unsendable\` so Python can't migrate them across threads. A process-global \`OnceLock<Runtime>\` is a possible later refactor when measured pressure justifies it. ## Test plan - [x] \`cargo build --workspace\` - [x] \`cargo clippy --workspace --all-targets -- -D warnings\` - [x] \`cargo +stable fmt --all -- --check\` - [x] \`cargo test --workspace\` — kernel suite unchanged - [x] **Live pytest suite against dogfood** (\`pyo3/tests/\`, gated by env vars + \`@live\` markers). **29 tests pass** covering: \`Session\` lifecycle, sync execute (SELECT 1, range(10000), fetchmany pacing), all four metadata calls, async submit/status/await_result, idempotent close, use-after-close, structured DatabaseError on bad SQL, \`session_configuration={'ANSI_MODE': 'false'}\` round-trip. All in ~20s. This pull request and its description were written by Isaac. --------- Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
3 tasks
gopalldb
added a commit
that referenced
this pull request
May 22, 2026
…ject comments (#41) ## Summary Closes three audit findings related to CI and dependency hygiene. | Audit | Commit | What | |---|---|---| | #9 | `2acc8e5` | `dco-check.yml` checkout was `@v6.0.2`; all other workflows use `@v4`. Aligned to v4. Both SHA-pinned — no security delta. | | #10 | `820e69c` | No `.github/dependabot.yml`. Added one covering `cargo` + `github-actions`. `pip` intentionally omitted per `go/pinning-python-deps` (externally-published-library rule). | | #16 (dependency-pinning audit row 3) | `732827b` | `pyo3/pyproject.toml` comments claimed `uv sync --frozen` + committed `uv.lock` with SHA256 hashes. Actual CI uses `uv sync --group dev` (no `--frozen`, no committed lockfile) per the externally-published-library policy. Rewrote both comment blocks to match reality. Documentation-only fix. | ## #9 — Checkout pin alignment `dco-check.yml:37` was the only workflow using `actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2`. All other 7 workflows use `actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4`. Both are SHA-pinned, so no actual security delta — purely version-drift hygiene. ## #10 — Dependabot configuration New `.github/dependabot.yml`: - **`cargo`** ecosystem: tracks the Rust crate graph weekly, complements the existing `cargo-deny` gate. Patch + minor grouped to reduce PR churn; security advisories still surface as individual PRs. Limit: 10 open PRs. - **`github-actions`** ecosystem: tracks SHA-pinned action versions weekly. Patch + minor grouped. Limit: 5 open PRs. **`pip` ecosystem intentionally NOT included.** The kernel is treated as an externally-published library per [go/pinning-python-deps](https://docs.google.com/document/d/1thJsoOBW3NzvRV6pWpujcD8mn4KOXgAW8t10iw6Z6LA/edit): - Major-version upper bounds in `pyo3/pyproject.toml` (e.g. `pyarrow>=14,<19`). - `uv sync` re-resolves on each CI run within those bounds. - No committed lockfile (would impede downstream `pip install`). Letting Dependabot rewrite pinned pip versions would conflict with that policy. ## #16 — pyproject.toml comment accuracy The `[project].dependencies` block comment said: > The CI environment is fully hash-locked via `uv.lock` (see below), separately from this contract. And the `[dependency-groups].dev` block said: > `uv sync --frozen` installs from `uv.lock`, which carries SHA256 hashes for every artifact + transitive dep. Neither was true. The repo has **no `uv.lock`** committed; the workflow runs **`uv sync --group dev`** (no `--frozen`). The workflow's own inline comment correctly describes the policy ("No `--frozen` and no committed lockfile: per go/pinning-python-deps the externally-published-library rule says *not* to pin transitive deps") — only the pyproject comments were stale. This documentation drift was actively misleading dependency-pinning audits, contributing to false "unpinned pyarrow" findings. Both comment blocks now match the actual in-repo policy. No behavioural change. ## Audit items NOT addressed here - **#11** (audit-log alerts on `.github/workflows/**` changes) — org-level streaming, not a repo-admin action. - **#12** (`id-token: write` in 3 workflows) — audit confirms current scoping is correct. - **#13** (`persist-credentials: false` in rust-e2e) — audit confirms positive control, preserved. - **#14** (`azure-prod.can_admins_bypass: true`) — handled via repo settings PUT, already flipped to `false`. ## Test plan - [ ] Reviewer checks GitHub recognises the dependabot config (Insights → Dependency graph → Dependabot tab shows cargo + github-actions ecosystems active). - [ ] DCO check on this PR runs successfully with the new v4 checkout (the workflow runs on PR open, once Actions are enabled). - [ ] Reviewer skims the pyproject comment changes to confirm they match the workflow's actual behaviour (`uv sync --group dev`, no `--frozen`). This pull request and its description were written by Isaac. --------- Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Surface added
```python
import databricks_sql_kernel as k
def get_token() -> str:
# whatever auth flow the connector already has
return current_bearer_token()
session = k.Session(
host=...,
http_path=...,
auth_type="external",
token_callback=get_token,
)
```
Session constructor now accepts:
Errors map cleanly: Python exceptions in the callback → `KernelError(code='Unauthenticated', message='Python token_callback raised: ...')`. Non-string return / empty string surface as `Unauthenticated` with a pointed message.
Implementation
The kernel's `build_auth_provider` currently returns `InvalidArgument` for `AuthConfig::External` (`reserved; v0 wires PAT + OAuthM2M + OAuthU2M only`). End-to-end use of `Session(auth_type='external', ...)` surfaces that error verbatim today — the trampoline is wired all the way down, but the kernel rejects the variant before it's invoked.
A separate small kernel PR will land an `ExternalAuthProvider` adapter (likely using `tokio::task::block_in_place` + `Handle::current().block_on` to drive the async `TokenProvider` from the sync `AuthProvider` trait, or by making `AuthProvider` async). This PyO3 PR is the wrapper half — the kernel half belongs in its own review thread.
Test plan
This pull request and its description were written by Isaac.