Repository navigation
feat(pyo3): Phase 1 — PyO3 binding for the Databricks SQL Kernel - #13
Conversation
Phase 1 of the PySQL × kernel integration plan (docs/designs/pysql-kernel-integration.md). Adds a workspace-member sub-crate at `pyo3/` that builds a Python extension module named `databricks_sql_kernel` via maturin. PAT auth only; sync execute path; no metadata or async statement yet. Surface exposed to Python: - `Session(host, http_path, *, access_token, catalog=None, schema=None)` — opens a session against the live warehouse, owns a per-session multi-thread tokio runtime, exposes `.session_id`, `.statement()`, `.close()`. - `Statement` — `.set_sql(text)`, `.execute()`, `.close()`. - `ExecutedStatement` — `.statement_id`, `.arrow_schema()`, `.fetch_next_batch()`, `.fetch_all_arrow()`, `.cancel()`, `.close()`. - `KernelError` — single Python exception carrying structured `(code, message, sql_state, error_code, vendor_code, http_status, retryable, query_id)` for connector-side re-raising as PEP 249 classes. Every kernel call detaches the GIL with `py.detach(...)` so other Python threads can run during I/O. Arrow batches cross via arrow-pyarrow's `ToPyArrow` (zero-copy buffers, per-batch Python wrapper creation under the GIL). Workspace conversion: root `Cargo.toml` grows a `[workspace]` table with `members = [".", "pyo3"]`. Future bindings (napi-rs, etc.) slot in as additional members. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Phase 1 step 3 of the PySQL × kernel integration plan. Wraps the kernel's `Metadata` API and adds a standalone `ResultStream` Python class for the bare streams the metadata calls return. New Python surface: - `Session.metadata() -> Metadata` - `Metadata.list_catalogs() -> ResultStream` - `Metadata.list_schemas(*, catalog=None, schema_pattern=None) -> ResultStream` - `Metadata.list_tables(*, catalog=None, schema_pattern=None, table_pattern=None, table_types=None) -> ResultStream` - `Metadata.list_columns(*, catalog, schema_pattern=None, table_pattern=None, column_pattern=None) -> ResultStream` - `Metadata.primary_keys(*, catalog, schema, table) -> ResultStream` - `Metadata.foreign_keys(*, parent_catalog=None, parent_schema=None, parent_table=None, foreign_catalog, foreign_schema, foreign_table) -> ResultStream` - `Metadata.functions / procedures(*, catalog=None, schema_pattern=None, name_pattern=None) -> ResultStream` - `Metadata.type_info() / table_types() -> ResultStream` (static, no wire call) - `ResultStream` — `arrow_schema()`, `fetch_next_batch()`, `fetch_all_arrow()`, `close()`. The Python surface collapses kernel `Identifier` / `LikePattern` back to `Option[str]`; the kernel still enforces empty / NUL / backtick / length-cap checks, surfacing bad input as `KernelError(code='InvalidArgument', ...)`. Implementation notes: - New `fetch.rs` shared helpers (`next_batch`, `drain`, `batches_to_pyarrow_table`) so `ExecutedStatement` and the new `ResultStream` produce identical Python objects from the same code path. - `ExecutedStatement::fetch_*` refactored to call the helpers; no behavior change. - `Metadata` methods are inline `block_on`s — the `for<'a> FnOnce(&'a Metadata) -> Fut` HRTB trick can't express the bound the borrow checker needs, and the inline form is simpler anyway. Smoke test (`pyo3/smoke.py`) extended with the metadata surface and validation checks; verified end-to-end against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
…esult) Phase 1 step 4. Wraps the kernel's `ExecutedAsyncStatement` so the connector can run `cursor.execute(async_op=True)` workflows through the kernel: submit returns immediately with a `statement_id`, the caller polls `status()` and pulls results via `await_result()` or `fetch_result()` once a terminal state is reached. New Python surface: - `Statement.submit() -> ExecutedAsyncStatement` - `ExecutedAsyncStatement.statement_id` - `ExecutedAsyncStatement.status() -> (state: str, failure: Optional[dict])` Returns one of `Pending / Running / Succeeded / Failed / Cancelled / Closed`. `failure` is populated only for `Failed` and carries the same structured-attrs dict that `KernelError` exposes (code, sql_state, error_code, query_id, etc.). Surfacing failure as a dict rather than raising lets polling callers branch without a try/except boundary. - `ExecutedAsyncStatement.await_result() -> ResultStream` — blocks with kernel-managed poll cadence, raises on `Failed` / `Cancelled`. - `ExecutedAsyncStatement.fetch_result() -> ResultStream` — fetches without polling; raises `KernelError(code='InvalidState')` if the statement is still running. - `ExecutedAsyncStatement.cancel() / close()` — same semantics as the sync handle's counterparts. Smoke test (`pyo3/smoke.py`) extended with the async surface; all checks pass against dogfood. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
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>
| } | ||
| } | ||
|
|
||
| #[pyclass(name = "ExecutedAsyncStatement", unsendable)] |
There was a problem hiding this comment.
The PR drives kernel async with runtime.block_on(...) inside py.detach. That works but forces a sync Python API even though every kernel method is async. The 2024+ idiom for binding async-Rust to Python is:
#[pymethods]
impl Session {
fn execute<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
pyo3_async_runtimes::tokio::future_into_py(py, async move {
inner.execute().await.map_err(to_py_err)
})
}
}
This returns a Python awaitable — callers do await session.execute() from Python async def. Combined with pyo3-async-runtimes, the kernel's tokio runtime serves as Python's event loop too, no per-Session
multi-threaded runtime, no block_on.
| let _ = attrs.set_item("retryable", err.retryable); | ||
| let _ = attrs.set_item("query_id", err.query_id.as_deref()); | ||
|
|
||
| KernelError::new_err((err.message.clone(), attrs.unbind())) |
There was a problem hiding this comment.
Instead of packing fields into a Python dict (to_py_err builds a dict of attrs), make KernelError a #[pyclass(extends=PyException)] with fields exposed via #[pyo3(get)]:
#[pyclass(extends=PyException, module="databricks_sql_kernel")]
pub struct KernelError {
#[pyo3(get)] pub code: String,
#[pyo3(get)] pub message: String,
#[pyo3(get)] pub sql_state: Option,
// ...
}
Python sees err.code directly (instead of err.args[1]['code']). Cleaner Python API, no dict-building cost per error. The current create_exception! approach is shorter to write but produces a worse Python
ergonomics. Recommend the change.
Session, Statement, ExecutedStatement, ExecutedAsyncStatement, ResultStream all implement the same pattern: let Some(inner) = self.inner.take() else { return Ok(()); }; Option::take() is the right idiom but the pattern is repeated 5×. A trait PyClose { fn close_inner(&mut self); } with a blanket close() -> PyResult<()> default, or a close_idempotent!() macro, would collapse
Every method that touches inner starts with: let inner = self.inner.as_ref() This appears ~25 times across the wrappers. ResultStream got an alive_mut() helper (line 1636); Session/Statement/etc. didn't follow the convention. Fix: add alive() / alive_mut() helpers to every wrapper,
Every kernel call is wrapped with the same three steps:
A run_kernel!(py, self, |inner| inner.foo(...)) macro that hides all three is the obvious factoring. This is the single highest-value refactor. ~25 method bodies shrink to a one-liner. Borrows nothing from
list_catalogs, list_schemas, list_tables, list_columns, primary_keys, foreign_keys, functions, procedures, type_info, table_types all do: (a) check closed, (b) convert each Option<&str> to Option The cleanest factoring is a declarative macro metadata_method!(name, signature, kernel_call_args) that emits the full method body. ~280 lines → ~80. Worth doing this PR because napi-rs will need the same 10
The "smoke test" is one main() with ~25 sections, each a banner(...) + check(...)-style assertion. Bare prints, no fixtures, no pytest. Maintenance burden is OK today; it'll be painful when Phase 2 doubles
The conversion is mostly mechanical: each banner("X") + check(...) becomes def test_x(): + assert. Other findings (not duplication, but adjacent) KernelError field mapping is well-centralised (good) errors.rs::to_py_err (lines 1769–1786) is the single conversion site. code_str (lines 1748–1767) uses an exhaustive match on ErrorCode so new kernel variants force a wrapper update at compile time. This is Auth trampoline is structurally fine but cannot be exercised end-to-end yet (high) auth.rs::PythonTokenProvider (lines 711–750) holds Py, implements #[async_trait] TokenProvider, uses Python::attach(...) to re-acquire the GIL for the sync callback call, maps Python exceptions to But: the PR description says the kernel's build_auth_provider still rejects AuthConfig::External with InvalidArgument. The trampoline's 4 unit tests exercise PythonTokenProvider::token() in isolation but Also: the trampoline doesn't cache tokens. Every kernel HTTP request triggers a Python callback invocation under the GIL. For high-QPS workloads that's a serialisation point. PR says "the callable owns its tokio = { version = "1", features = ["rt-multi-thread"] } spins up a per-Session runtime (note) Each PyO3 Session owns its own multi-threaded runtime. For most workloads that's fine; for users embedding the kernel in an already-async application, they end up running two runtimes. PyO3's pyo3-async cdylib + extension-module feature gate for cargo test (good) PR uses the standard maturin pattern: pyo3 = { features = ["abi3-py39"] } always; extension-module only when building the wheel. cargo test -p databricks-sql-kernel-pyo3 builds a normal binary that links PyPI package name collision risk (medium — verify before publishing) pyproject.toml's [project] name = "databricks-sql-kernel" doesn't have a -pyo3 suffix. Existing PyPI has databricks-sql-connector (the PySQL connector). Verify the name is available and intentional before arrow-pyarrow = "57" aligns with kernel arrow = "57" (good) No version skew → no buffer-layout corruption. ✓ Workspace conversion is minimal and right (good) Root Cargo.toml gains 5 lines: [workspace] members = [".", "pyo3"]. No resolver = "2", no shared deps. Extensible to napi-rs without ceremony. ✓ Required-before-merge — my call Should fix in this PR:
Worth doing now, before Phase 2: |
Addresses the review comments on #13: - KernelError exposes structured fields as Python attributes (err.code / err.message / err.sql_state / err.error_code / err.vendor_code / err.http_status / err.retryable / err.query_id) instead of packing them into err.args[1] as a dict. Reviewer's preferred change was a #[pyclass(extends= PyException)] subclass with #[pyo3(get)] getters, but abi3 rejects native-exception subclassing at compile time ("with the abi3 feature enabled, PyO3 does not support subclassing native types"). Same Python ergonomics achieved by attaching attributes via setattr on the exception value; abi3 stays. ExecutedAsyncStatement.status() now returns (state, Optional[KernelError]) — the KernelError instance itself, not a dict — so callers branch on failure.code rather than failure["code"]. - run_kernel! / run_kernel_block! / run_sync_kernel! macros collapse the py.detach + runtime.block_on + map_err pattern that repeated across ~25 sites. Single source of truth for the GIL handoff and error mapping. (Review item #3 — "single highest-value refactor.") - alive! / alive_mut! macros applied across Session, Statement, ExecutedStatement, ExecutedAsyncStatement, ResultStream so the use-after-close guard is one consistent shape. closed_err() helper in errors.rs builds the InvalidStatementHandle-coded KernelError once. (Review item #2.) - Metadata methods use run_kernel_block! to handle the outer GIL+runtime scaffolding; inner Identifier/LikePattern conversions stay explicit (they vary too much across the 10 methods for a single declarative macro to beat readability). (Review item #4 — partial; "outer scaffolding" win without the DSL cost.) - smoke.py (353 lines of print+check) converted to pytest with 30 tests across 6 modules: test_module / test_session / test_execute / test_metadata / test_async / test_auth. Module-scoped session fixture sessions reduces wall-time; pytest.ini sets up conftest discovery. Live tests gated on DATABRICKS_HOST / DATABRICKS_HTTP_PATH / DATABRICKS_TOKEN — no-network tests run unconditionally. All 30 tests pass against dogfood in ~19s. (Review item #5.) - Token-callback docstring on Session.__new__ now flags that the callback fires once per HTTP request and must be cheap. (Reviewer's "Other findings — token caching" note.) - PyPI name `databricks-sql-kernel` verified available via the Databricks JFrog proxy (404 on the kernel name, 200 for the known-existing databricks-sql-connector — proxy works). Safe to claim on first publish. Deferred to follow-up PRs (acknowledged in the review reply): - pyo3-async-runtimes shift to return Python awaitables instead of blocking inside py.detach. Fundamental shape change to every method; doesn't unblock Phase 2 because the connector's DatabricksClient contract is sync. - PyClose trait to collapse the 5× idempotent close() pattern. Reviewer marked it not-blocking. - Kernel-side AuthConfig::External enablement (separate PR against build_auth_provider) plus a wiremock integration test for the trampoline end-to-end. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
|
@gopalldb thanks for the thorough review — addressed the bulk of the feedback in 294730a. Summary: Addressed
Deferred (acknowledged, follow-up tracked)
Net diff in the new commit: +262 / -594 (-332 lines). All checks green: workspace Ready for another look. |
Folds in the small kernel-side gap noticed during Phase 2 planning.
The kernel's SessionBuilder already exposes `.session_conf(HashMap<
String, String>)` and serialises it as SEA `session_configuration`
on CreateSession; the PyO3 wrapper just wasn't passing it.
New kwarg on Session.__new__:
k.Session(host=..., http_path=..., access_token=...,
session_conf={"ANSI_MODE": "false", ...})
The connector backend uses this to pipe its `session_configuration`
dict through to the kernel. SEA enforces an allow-list (ANSI_MODE,
USE_CACHED_RESULT, STATEMENT_TIMEOUT, QUERY_TAGS, etc.); the kernel
passes the map through verbatim, the server applies what it accepts
and errors on the rest.
Live test added: `test_session_conf_round_trips` sets
`ANSI_MODE=false` and verifies `SET ANSI_MODE` returns `false`,
proving the map reached the server and was honoured. (`ANSI_MODE`
was chosen after sanity-testing because `TIMEZONE` is rejected by
this warehouse as "Unsupported configuration" and
`USE_CACHED_RESULT` / `STATEMENT_TIMEOUT` are workspace-policy-
clamped.)
All 31 pytests pass; cargo clippy/fmt/test green.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
|
Folded in one more small commit (b60166a) — wires Live test added: |
Rebuild the kernel's CI/CD from a half-broken adbc-drivers/databricks inheritance into a working pipeline that mirrors the conventions in databricks/databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, and databricks-sql-python. What was wrong: - rust_test_pr.yaml called a reusable workflow (`rust_test.yaml`) that was never ported from adbc-drivers/databricks. Its own TODO comment said it would fail. - rust_coverage_report.yaml waited for a workflow named "Rust Test" that doesn't exist locally — it would never fire. - ci/test_package.py imported adbc_driver_manager; the legacy ADBC layer was removed in PR 7 (#11). The kernel is no longer an ADBC driver; the smoke test it implemented exercises a delivery vector the kernel no longer offers. PyO3 smoke testing comes via PR #13. - manifest.toml was the ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI." - The "proxy" and "tls" jobs in rust-e2e.yml referenced tests/proxy_e2e.rs / tls_e2e.rs, both #![cfg(feature = "legacy-adbc")]-gated and deleted alongside ADBC in PR #11. What's added (.github/workflows/): pr-checks.yml cargo fmt --check + clippy -D warnings + cargo test --workspace on every PR. Replaces the broken rust_test_pr.yaml. dco-check.yml Verbatim port of databricks-sql-go's dco-check.yml. CLAUDE.md mandates `git commit -s`; this enforces it. coverage.yml cargo llvm-cov → Codecov via OIDC. Standalone — no longer waits on a missing "Rust Test" workflow. license-check.yml cargo-deny against deny.toml. Replaces the cargo-about reference in CLAUDE.md; cargo-deny is the standard Rust-ecosystem gate (handles licenses + advisories + bans). apache-rat.yml Java-based Apache RAT against the source tree. CLAUDE.md claimed this ran but no workflow existed. Files to skip live in .ratignore. close-stale.yml 30-day stale + 7-day close window. Direct port from databricks-jdbc. release.yml Triggers on `v*.*.*` tag push: tag-version vs Cargo.toml version check → fmt → clippy → test → dry-run publish → real publish. workflow_dispatch with dry_run input for manual rehearsals. pyo3-checks.yml Maturin build + cargo test for the pyo3/ sub-crate. Path-gated on pyo3/** so this workflow only fires after PR #13 lands the Python wrapper. rust-e2e.yml Reworked: kept the live-workspace v0 E2E job (Session::open, execute, submit, await_result, metadata). Proxy + TLS jobs are kept and ported to the v0 surface — see "Proxy / TLS port" below. Proxy / TLS port (replaces dropping the jobs): - tests/proxy_e2e.rs and tests/tls_e2e.rs are restored with v0 bodies: they call SessionBuilder::proxy(ProxyConfig { url, username, password, bypass_hosts }) and SessionBuilder::tls(TlsConfig { trusted_certificate_path, allow_self_signed, allow_hostname_mismatch }). These fields don't exist yet in src/config.rs (both structs are #[non_exhaustive] placeholders); the test files are #![cfg(feature = "proxy_tls_e2e")]-gated so they're excluded from the default build. - Cargo.toml gains a `proxy_tls_e2e = []` feature. - rust-e2e.yml's proxy and tls jobs run a `cargo check --features proxy_tls_e2e --tests` precondition; if it doesn't compile (the v0.1 ProxyConfig/TlsConfig work isn't done), the job emits a clear ::warning and short-circuits cleanly. When v0.1 lands the fields, the feature compiles and the jobs auto-fire. - ci/proxy/ configs are kept — consumed by the proxy job once the feature compiles. - docs/migration-plan.md §7 gains a "Proxy + TLS E2E coverage (v0.1)" entry naming the four-step kernel work that unblocks this: flesh ProxyConfig, flesh TlsConfig, plumb both through client/http.rs, flip the feature default. What's deleted (only files genuinely tied to vectors the kernel no longer offers): .github/workflows/rust_test_pr.yaml (broken — replaced) .github/workflows/rust_coverage_report.yaml (dead — replaced) ci/test_package.py (ADBC vector gone; PyO3 in PR #13) manifest.toml (ADBC discovery file; the kernel isn't an ADBC driver) Other: - deny.toml — license + advisory allowlist for cargo-deny. Mirrors the prior about.toml allowlist plus a few standard permissive licenses cargo-deny encounters in the dep tree. - .ratignore — globs Apache RAT should skip (Cargo.lock, markdown, target/, LICENSE, etc.). - .gitignore — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - CLAUDE.md — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at deny.toml (not about.toml); "License headers" mentions .ratignore. All workflows run on the `databricks-protected-runner-group / linux-ubuntu-latest` pool, matching peer repos. Action versions SHA-pinned per the convention in the peer repos. Verified locally: - cargo build (clean) - cargo test --lib (366 passing) - cargo clippy --all-targets -- -D warnings (clean) - cargo check --features proxy_tls_e2e --tests fails with a precise error pointing at the missing ProxyConfig/TlsConfig fields — the rust-e2e.yml precondition handles this cleanly - All 9 workflow YAML files parse Co-authored-by: Isaac Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
External auth (Python-callable TokenProvider trampoline) was Phase 1
step 5 of the integration plan. Removing it in favour of a smaller
PAT-only surface for the first connector cutover; the OAuth question
(kernel-owned OAuth vs connector-delegated tokens) gets revisited
when there's actual demand on the kernel-backed code path.
What's removed:
- `auth.rs::PythonTokenProvider` and its 4 Rust unit tests.
- The `token_callback` kwarg on `Session.__new__`.
- The `extension-module` Cargo feature gymnastics (only existed
to let cargo test link libpython for the trampoline unit tests
— no Rust unit tests remain in the pyo3 crate, so the feature
is back to always-on, matching the original Phase 1 setup).
- The `async-trait` dependency (only the trampoline used it).
- Smoke and pytest cases that exercised External end-to-end.
What stays:
- PAT path: unchanged.
- All other Phase 1 surface (Statement / Metadata /
ExecutedAsyncStatement / ResultStream / KernelError) unchanged.
Surface today on `Session.__new__`:
k.Session(
host=..., http_path=...,
access_token="dapi...", # or auth_type='pat', access_token=...
catalog=..., schema=...,
session_conf={...},
)
Anything else for `auth_type` raises ValueError ("unsupported
auth_type 'X'; only 'pat' is supported today"), surfacing at
construction time, not deep in HTTP retry.
Verified:
- cargo build --workspace
- cargo clippy --workspace --all-targets -- -D warnings
- cargo +stable fmt --all -- --check
- 29 pyo3/tests pytests pass against dogfood.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
|
Dropped External auth (commit 4847a07). The credential-ownership question (kernel-owned OAuth vs connector-delegated tokens) is getting deferred until there's real demand on the kernel-backed code path. PAT-only for Phase 1 keeps the surface small and removes the need for a kernel-side enablement PR (which was on the connector's critical path). What's gone:
What stays: everything else. Surface is now 29 pyo3/tests still pass. -249 lines net. |
Rebuild the kernel's CI/CD from a half-broken adbc-drivers/databricks inheritance into a working pipeline that mirrors the conventions in databricks/databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, and databricks-sql-python. What was wrong: - rust_test_pr.yaml called a reusable workflow (`rust_test.yaml`) that was never ported from adbc-drivers/databricks. Its own TODO comment said it would fail. - rust_coverage_report.yaml waited for a workflow named "Rust Test" that doesn't exist locally — it would never fire. - ci/test_package.py imported adbc_driver_manager; the legacy ADBC layer was removed in PR 7 (#11). The kernel is no longer an ADBC driver; the smoke test it implemented exercises a delivery vector the kernel no longer offers. PyO3 smoke testing comes via PR #13. - manifest.toml was the ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI." - The "proxy" and "tls" jobs in rust-e2e.yml referenced tests/proxy_e2e.rs / tls_e2e.rs, both #![cfg(feature = "legacy-adbc")]-gated and deleted alongside ADBC in PR #11. What's added (.github/workflows/): pr-checks.yml cargo fmt --check + clippy -D warnings + cargo test --workspace on every PR. Replaces the broken rust_test_pr.yaml. dco-check.yml Verbatim port of databricks-sql-go's dco-check.yml. CLAUDE.md mandates `git commit -s`; this enforces it. coverage.yml cargo llvm-cov → Codecov via OIDC. Standalone — no longer waits on a missing "Rust Test" workflow. license-check.yml cargo-deny against deny.toml. Replaces the cargo-about reference in CLAUDE.md; cargo-deny is the standard Rust-ecosystem gate (handles licenses + advisories + bans). apache-rat.yml Java-based Apache RAT against the source tree. CLAUDE.md claimed this ran but no workflow existed. Files to skip live in .ratignore. close-stale.yml 30-day stale + 7-day close window. Direct port from databricks-jdbc. release.yml Triggers on `v*.*.*` tag push: tag-version vs Cargo.toml version check → fmt → clippy → test → dry-run publish → real publish. workflow_dispatch with dry_run input for manual rehearsals. pyo3-checks.yml Maturin build + cargo test for the pyo3/ sub-crate. Path-gated on pyo3/** so this workflow only fires after PR #13 lands the Python wrapper. rust-e2e.yml Reworked: kept the live-workspace v0 E2E job (Session::open, execute, submit, await_result, metadata). Proxy + TLS jobs are kept and ported to the v0 surface — see "Proxy / TLS port" below. Proxy / TLS port (replaces dropping the jobs): - tests/proxy_e2e.rs and tests/tls_e2e.rs are restored with v0 bodies: they call SessionBuilder::proxy(ProxyConfig { url, username, password, bypass_hosts }) and SessionBuilder::tls(TlsConfig { trusted_certificate_path, allow_self_signed, allow_hostname_mismatch }). These fields don't exist yet in src/config.rs (both structs are #[non_exhaustive] placeholders); the test files are #![cfg(feature = "proxy_tls_e2e")]-gated so they're excluded from the default build. - Cargo.toml gains a `proxy_tls_e2e = []` feature. - rust-e2e.yml's proxy and tls jobs run a `cargo check --features proxy_tls_e2e --tests` precondition; if it doesn't compile (the v0.1 ProxyConfig/TlsConfig work isn't done), the job emits a clear ::warning and short-circuits cleanly. When v0.1 lands the fields, the feature compiles and the jobs auto-fire. - ci/proxy/ configs are kept — consumed by the proxy job once the feature compiles. - docs/migration-plan.md §7 gains a "Proxy + TLS E2E coverage (v0.1)" entry naming the four-step kernel work that unblocks this: flesh ProxyConfig, flesh TlsConfig, plumb both through client/http.rs, flip the feature default. What's deleted (only files genuinely tied to vectors the kernel no longer offers): .github/workflows/rust_test_pr.yaml (broken — replaced) .github/workflows/rust_coverage_report.yaml (dead — replaced) ci/test_package.py (ADBC vector gone; PyO3 in PR #13) manifest.toml (ADBC discovery file; the kernel isn't an ADBC driver) Other: - deny.toml — license + advisory allowlist for cargo-deny. Mirrors the prior about.toml allowlist plus a few standard permissive licenses cargo-deny encounters in the dep tree. - .ratignore — globs Apache RAT should skip (Cargo.lock, markdown, target/, LICENSE, etc.). - .gitignore — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - CLAUDE.md — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at deny.toml (not about.toml); "License headers" mentions .ratignore. All workflows run on the `databricks-protected-runner-group / linux-ubuntu-latest` pool, matching peer repos. Action versions SHA-pinned per the convention in the peer repos. Verified locally: - cargo build (clean) - cargo test --lib (366 passing) - cargo clippy --all-targets -- -D warnings (clean) - cargo check --features proxy_tls_e2e --tests fails with a precise error pointing at the missing ProxyConfig/TlsConfig fields — the rust-e2e.yml precondition handles this cleanly - All 9 workflow YAML files parse Co-authored-by: Isaac Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-5 review fixes: - pyo3-checks.yml: add precondition step that checks for pyo3/Cargo.toml and gates every subsequent step. The workflow's paths: filter still fires on root Cargo.toml/Cargo.lock changes (kernel deps can affect pyo3) but the pyo3/ sub-crate itself lands in PR #13. Until then, the job skips cleanly with a ::notice:: instead of red-lighting kernel-only PRs. - pr-checks.yml: tighten the cargo-test comment to be explicit about which suites run (unit + doc + wiremock integration) and which don't (v0_*_e2e — #[ignore]'d, run by rust-e2e.yml). - apache-rat.yml: remove `|| echo "0"` silent-failure fallback in the UNAPPROVED parse. If RAT changes report format, CI now fails loud with a clear error rather than passing with 0. Added a follow-up note pointing at --output-style xml + xmlstarlet as the proper future-proof fix. - .ratignore: remove dangling comment block about CI files; add .ratignore itself to the ignore list. Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
Review — PyO3 Phase 1Verified locally against Architecture is sound and the design choices line up with the kernel:
Required before mergeC1. C2. PR description is stale. C3. C4. Drop the unused Important — decide now or document
Two options:
I'd take (a) — the kernel split is consistent but leaks through the close semantics; wrapping it in a user-friendly Phase 2 / follow-up (not blocking)
The architecture is right. After C1-C4 land and a decision on — Isaac (AI-assisted review) |
Rebuild the kernel's CI/CD from a half-broken adbc-drivers/databricks inheritance into a working pipeline that mirrors the conventions in databricks/databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, and databricks-sql-python. What was wrong: - rust_test_pr.yaml called a reusable workflow (`rust_test.yaml`) that was never ported from adbc-drivers/databricks. Its own TODO comment said it would fail. - rust_coverage_report.yaml waited for a workflow named "Rust Test" that doesn't exist locally — it would never fire. - ci/test_package.py imported adbc_driver_manager; the legacy ADBC layer was removed in PR 7 (#11). The kernel is no longer an ADBC driver; the smoke test it implemented exercises a delivery vector the kernel no longer offers. PyO3 smoke testing comes via PR #13. - manifest.toml was the ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI." - The "proxy" and "tls" jobs in rust-e2e.yml referenced tests/proxy_e2e.rs / tls_e2e.rs, both #![cfg(feature = "legacy-adbc")]-gated and deleted alongside ADBC in PR #11. What's added (.github/workflows/): pr-checks.yml cargo fmt --check + clippy -D warnings + cargo test --workspace on every PR. Replaces the broken rust_test_pr.yaml. dco-check.yml Verbatim port of databricks-sql-go's dco-check.yml. CLAUDE.md mandates `git commit -s`; this enforces it. coverage.yml cargo llvm-cov → Codecov via OIDC. Standalone — no longer waits on a missing "Rust Test" workflow. license-check.yml cargo-deny against deny.toml. Replaces the cargo-about reference in CLAUDE.md; cargo-deny is the standard Rust-ecosystem gate (handles licenses + advisories + bans). apache-rat.yml Java-based Apache RAT against the source tree. CLAUDE.md claimed this ran but no workflow existed. Files to skip live in .ratignore. close-stale.yml 30-day stale + 7-day close window. Direct port from databricks-jdbc. release.yml Triggers on `v*.*.*` tag push: tag-version vs Cargo.toml version check → fmt → clippy → test → dry-run publish → real publish. workflow_dispatch with dry_run input for manual rehearsals. pyo3-checks.yml Maturin build + cargo test for the pyo3/ sub-crate. Path-gated on pyo3/** so this workflow only fires after PR #13 lands the Python wrapper. rust-e2e.yml Reworked: kept the live-workspace v0 E2E job (Session::open, execute, submit, await_result, metadata). Proxy + TLS jobs are kept and ported to the v0 surface — see "Proxy / TLS port" below. Proxy / TLS port (replaces dropping the jobs): - tests/proxy_e2e.rs and tests/tls_e2e.rs are restored with v0 bodies: they call SessionBuilder::proxy(ProxyConfig { url, username, password, bypass_hosts }) and SessionBuilder::tls(TlsConfig { trusted_certificate_path, allow_self_signed, allow_hostname_mismatch }). These fields don't exist yet in src/config.rs (both structs are #[non_exhaustive] placeholders); the test files are #![cfg(feature = "proxy_tls_e2e")]-gated so they're excluded from the default build. - Cargo.toml gains a `proxy_tls_e2e = []` feature. - rust-e2e.yml's proxy and tls jobs run a `cargo check --features proxy_tls_e2e --tests` precondition; if it doesn't compile (the v0.1 ProxyConfig/TlsConfig work isn't done), the job emits a clear ::warning and short-circuits cleanly. When v0.1 lands the fields, the feature compiles and the jobs auto-fire. - ci/proxy/ configs are kept — consumed by the proxy job once the feature compiles. - docs/migration-plan.md §7 gains a "Proxy + TLS E2E coverage (v0.1)" entry naming the four-step kernel work that unblocks this: flesh ProxyConfig, flesh TlsConfig, plumb both through client/http.rs, flip the feature default. What's deleted (only files genuinely tied to vectors the kernel no longer offers): .github/workflows/rust_test_pr.yaml (broken — replaced) .github/workflows/rust_coverage_report.yaml (dead — replaced) ci/test_package.py (ADBC vector gone; PyO3 in PR #13) manifest.toml (ADBC discovery file; the kernel isn't an ADBC driver) Other: - deny.toml — license + advisory allowlist for cargo-deny. Mirrors the prior about.toml allowlist plus a few standard permissive licenses cargo-deny encounters in the dep tree. - .ratignore — globs Apache RAT should skip (Cargo.lock, markdown, target/, LICENSE, etc.). - .gitignore — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - CLAUDE.md — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at deny.toml (not about.toml); "License headers" mentions .ratignore. All workflows run on the `databricks-protected-runner-group / linux-ubuntu-latest` pool, matching peer repos. Action versions SHA-pinned per the convention in the peer repos. Verified locally: - cargo build (clean) - cargo test --lib (366 passing) - cargo clippy --all-targets -- -D warnings (clean) - cargo check --features proxy_tls_e2e --tests fails with a precise error pointing at the missing ProxyConfig/TlsConfig fields — the rust-e2e.yml precondition handles this cleanly - All 9 workflow YAML files parse Co-authored-by: Isaac Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-5 review fixes: - pyo3-checks.yml: add precondition step that checks for pyo3/Cargo.toml and gates every subsequent step. The workflow's paths: filter still fires on root Cargo.toml/Cargo.lock changes (kernel deps can affect pyo3) but the pyo3/ sub-crate itself lands in PR #13. Until then, the job skips cleanly with a ::notice:: instead of red-lighting kernel-only PRs. - pr-checks.yml: tighten the cargo-test comment to be explicit about which suites run (unit + doc + wiremock integration) and which don't (v0_*_e2e — #[ignore]'d, run by rust-e2e.yml). - apache-rat.yml: remove `|| echo "0"` silent-failure fallback in the UNAPPROVED parse. If RAT changes report format, CI now fails loud with a clear error rather than passing with 0. Added a follow-up note pointing at --output-style xml + xmlstarlet as the proper future-proof fix. - .ratignore: remove dangling comment block about CI files; add .ratignore itself to the ignore list. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-6 review fixes: - rust-e2e.yml proxy job: drop the job-level `services: squid` block and launch the unauthenticated proxy inline via `docker run`. The services block starts the container before any step runs — even when the precondition gate trips — and pays setup cost on every PR until v0.1. Inline matches the `tls` job's approach: zero boot on a skipped job, single cleanup step tears down both proxies. - pyo3-checks.yml: split the file-existence check into its own precondition job; the matrix `build-and-test` job declares `needs: precondition` + `if: needs.precondition.outputs.ready == 'true'` so the matrix doesn't expand (no runner boot, no checkout, no toolchain install for 3.9 / 3.12) when pyo3/ doesn't exist. - apache-rat.yml: validate the parsed UNAPPROVED is a bare integer with `[[ "${UNAPPROVED}" =~ ^[0-9]+$ ]]` before the `-gt` comparison. If a future RAT release adds a unit suffix (e.g. "5 files"), CI now fails with a precise error instead of bash arithmetic blowing up with "integer expression expected". - coverage.yml: tighten the Codecov OIDC comment to flag the silent-failure mode — `use_oidc: true` requires repo enrolment in Codecov's GitHub App + OIDC enabled; otherwise the action falls back to anonymous upload that Codecov rate-limits and may drop. `fail_ci_if_error: false` is the right call (don't red- light unrelated PRs on a Codecov outage) but it does mean the first few PRs must be visually inspected for the Codecov check to confirm uploads are flowing. Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
|
Thanks @gopalldb — taking C1–C4 now. Wanted to push back on the Drop already fires
|
| Drop on… | Fires server RPC? | What it does |
|---|---|---|
Statement (statement/mutable.rs:329) |
No | Flips validity flag locally |
ExecutedStatement (statement/executed.rs:140) |
Yes — fire-and-forget CloseStatement on the session's runtime |
Releases server-side statement |
ExecutedAsyncStatement (statement/executed_async.rs:374) |
Yes — same fire-and-forget pattern | Same |
Each executed handle owns its own Arc<SessionInner>, so when the parent Statement is dropped first, the still-live executed handle outlives it and its Drop does hit the wire. The last_statement_id field on Statement is intentionally left as-is in its Drop:
last_statement_idis left as-is. By construction it is only set immediately beforeExecutedStatement::newwraps it; if the caller still holds anExecutedStatement, that handle owns the close-on-drop responsibility. If the caller dropped the handle before thisStatement, the handle's ownDropalready spawned the close. There is no remaining cleanup obligation here.
That comment is right. No CloseStatement is missed in any actual scenario.
Why option (a) would be worse, not better
The framing was "users expect stmt.close() to send CloseStatement." But in the realistic flow:
exec_ = stmt.execute() # mints server-side statement, owns it
# ... user uses exec_ ...
stmt.close() # what should this do?
# exec_ is still aliveIf Statement::close fires CancelStatement + CloseStatement against last_statement_id (option (a)), it rips the executed handle out from under the caller — exec_ is still in their hands but the server-side statement is gone. That's strictly worse than the current behavior.
The cases that exist:
| Flow | Current behavior | Correct? |
|---|---|---|
exec_ produced, stmt dropped first, exec_ dropped later |
stmt::Drop no-op; exec_::Drop fires CloseStatement |
✅ |
exec_ produced and dropped, then stmt dropped |
exec_::Drop fires CloseStatement; stmt::Drop no-op |
✅ |
Spec built (no execute), then stmt dropped |
Both no-op (nothing minted) | ✅ |
exec_ produced, then stmt.close() called explicitly |
Same as case 1 above | ✅ |
So my read is the kernel's design is internally consistent and correct; what's left is documentation. The PyO3 Statement.close() docstring should be more explicit about which handle owns server-side cleanup. Will add that in the upcoming push.
If you still want option (a) for ergonomics reasons (some other consumer of the kernel-Rust API expects Statement::close to short-circuit even the executed handle), happy to file it as a follow-up kernel issue — but I don't think it should block this PR, and I'd want to talk through the "rip exec_ out from under the caller" surprise before committing to it.
C1–C4 incoming
All four landing in the next push:
- C1:
crate-type = ["cdylib", "rlib"]so future Rust tests inpyo3/src/**aren't silent. - C2: PR description rewrite to match the PAT-only state (External / trampoline references gone).
- C3:
test_session_conf_round_tripsgated by@live. - C4: Drop the dead
async-traitdep.
Plus a docstring expansion on Statement.close() to head off the ergonomic concern.
— Isaac (AI-assisted reply)
C1 — crate-type = ["cdylib", "rlib"]. Without rlib, future
`#[cfg(test)]` modules in `pyo3/src/**` are silently invisible
to `cargo test -p` ("running 0 tests / ok"). One-line fix; clippy
stays green.
C3 — `test_session_conf_round_trips` already had `@live` (from
commit b60166a where the test was introduced), but the body
read os.environ[...] directly which would KeyError if `@live`
ever stopped matching. Switched to the same `HOST`/`HTTP_PATH`/
`TOKEN` module-level constants conftest defines. Robust to
future refactors.
Bonus — expanded the `Statement.close()` docstring to document
that server-side cleanup is owned by `ExecutedStatement` /
`ExecutedAsyncStatement` (each fires fire-and-forget
`CloseStatement` from its own Drop). `Statement.close()` only
drops the local lifecycle owner and flips the validity flag;
any executed handle the caller still holds continues to work.
Per the PR thread, C4 was already addressed in commit 4847a07
(async-trait dep was removed when External auth was dropped).
C2 (PR description rewrite) follows in a description edit.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Reversing my earlier reply to the reviewer — option (a) is in fact
the right call. The "rip exec_ out from under the caller" framing
was a strawman: if a caller is still actively using exec_, they
wouldn't be calling stmt.close() anyway. When they do call
stmt.close(), they're explicitly opting out of further use — which
is exactly what JDBC `Statement.close()`, ODBC `SQLFreeStmt(SQL_CLOSE)`,
and PySQL `cursor.close()` users already expect.
The kernel even had the underlying mechanism the whole time:
invalidate_prior() is called by execute()/submit() before re-use,
fires CancelStatement + CloseStatement against last_statement_id,
and flips the validity flag. So Statement::close just needs to
expose that capability as a public entry point.
Kernel side:
- New `Statement::close(mut self) -> Result<()>` (statement/mutable.rs)
consumes self and routes to invalidate_prior. Symmetric with
Session::close(self).
- Wiremock test (`statement_close_cancels_and_closes_outstanding_
executed_handle`) confirms the held ExecutedStatement's next
cancel/close call short-circuits with InvalidStatementHandle.
PyO3 side:
- Statement.close() rewritten from `self.inner = None` to drive
the kernel's close() through run_kernel!. Idempotent (Option::take).
- Docstring rewritten to match the new behavior — no more "doesn't
send any RPC" claim.
- Two new pytests:
- `test_statement_close_invalidates_held_executed_statement`:
proves cancel() on the held handle now errors with
InvalidStatementHandle. Also documents the subtlety that
already-buffered Arrow batches still drain locally
(fetch_next_batch doesn't go through valid.check()) — same
semantic as JDBC.
- `test_statement_close_is_idempotent`: a second close() is a
no-op.
cargo build/clippy/fmt/test clean; 31/31 pyo3 pytests pass against
dogfood.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
|
Walking back my earlier reply — you were right, taking option (a). The "rip Landed in
One subtlety the pytest documents: 31/31 pyo3 pytests pass; cargo build/clippy/fmt/test workspace-wide clean. With C1/C3 from the previous push ( — Isaac |
Rebuild the kernel's CI/CD from a half-broken adbc-drivers/databricks inheritance into a working pipeline that mirrors the conventions in databricks/databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, and databricks-sql-python. What was wrong: - rust_test_pr.yaml called a reusable workflow (`rust_test.yaml`) that was never ported from adbc-drivers/databricks. Its own TODO comment said it would fail. - rust_coverage_report.yaml waited for a workflow named "Rust Test" that doesn't exist locally — it would never fire. - ci/test_package.py imported adbc_driver_manager; the legacy ADBC layer was removed in PR 7 (#11). The kernel is no longer an ADBC driver; the smoke test it implemented exercises a delivery vector the kernel no longer offers. PyO3 smoke testing comes via PR #13. - manifest.toml was the ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI." - The "proxy" and "tls" jobs in rust-e2e.yml referenced tests/proxy_e2e.rs / tls_e2e.rs, both #![cfg(feature = "legacy-adbc")]-gated and deleted alongside ADBC in PR #11. What's added (.github/workflows/): pr-checks.yml cargo fmt --check + clippy -D warnings + cargo test --workspace on every PR. Replaces the broken rust_test_pr.yaml. dco-check.yml Verbatim port of databricks-sql-go's dco-check.yml. CLAUDE.md mandates `git commit -s`; this enforces it. coverage.yml cargo llvm-cov → Codecov via OIDC. Standalone — no longer waits on a missing "Rust Test" workflow. license-check.yml cargo-deny against deny.toml. Replaces the cargo-about reference in CLAUDE.md; cargo-deny is the standard Rust-ecosystem gate (handles licenses + advisories + bans). apache-rat.yml Java-based Apache RAT against the source tree. CLAUDE.md claimed this ran but no workflow existed. Files to skip live in .ratignore. close-stale.yml 30-day stale + 7-day close window. Direct port from databricks-jdbc. release.yml Triggers on `v*.*.*` tag push: tag-version vs Cargo.toml version check → fmt → clippy → test → dry-run publish → real publish. workflow_dispatch with dry_run input for manual rehearsals. pyo3-checks.yml Maturin build + cargo test for the pyo3/ sub-crate. Path-gated on pyo3/** so this workflow only fires after PR #13 lands the Python wrapper. rust-e2e.yml Reworked: kept the live-workspace v0 E2E job (Session::open, execute, submit, await_result, metadata). Proxy + TLS jobs are kept and ported to the v0 surface — see "Proxy / TLS port" below. Proxy / TLS port (replaces dropping the jobs): - tests/proxy_e2e.rs and tests/tls_e2e.rs are restored with v0 bodies: they call SessionBuilder::proxy(ProxyConfig { url, username, password, bypass_hosts }) and SessionBuilder::tls(TlsConfig { trusted_certificate_path, allow_self_signed, allow_hostname_mismatch }). These fields don't exist yet in src/config.rs (both structs are #[non_exhaustive] placeholders); the test files are #![cfg(feature = "proxy_tls_e2e")]-gated so they're excluded from the default build. - Cargo.toml gains a `proxy_tls_e2e = []` feature. - rust-e2e.yml's proxy and tls jobs run a `cargo check --features proxy_tls_e2e --tests` precondition; if it doesn't compile (the v0.1 ProxyConfig/TlsConfig work isn't done), the job emits a clear ::warning and short-circuits cleanly. When v0.1 lands the fields, the feature compiles and the jobs auto-fire. - ci/proxy/ configs are kept — consumed by the proxy job once the feature compiles. - docs/migration-plan.md §7 gains a "Proxy + TLS E2E coverage (v0.1)" entry naming the four-step kernel work that unblocks this: flesh ProxyConfig, flesh TlsConfig, plumb both through client/http.rs, flip the feature default. What's deleted (only files genuinely tied to vectors the kernel no longer offers): .github/workflows/rust_test_pr.yaml (broken — replaced) .github/workflows/rust_coverage_report.yaml (dead — replaced) ci/test_package.py (ADBC vector gone; PyO3 in PR #13) manifest.toml (ADBC discovery file; the kernel isn't an ADBC driver) Other: - deny.toml — license + advisory allowlist for cargo-deny. Mirrors the prior about.toml allowlist plus a few standard permissive licenses cargo-deny encounters in the dep tree. - .ratignore — globs Apache RAT should skip (Cargo.lock, markdown, target/, LICENSE, etc.). - .gitignore — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - CLAUDE.md — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at deny.toml (not about.toml); "License headers" mentions .ratignore. All workflows run on the `databricks-protected-runner-group / linux-ubuntu-latest` pool, matching peer repos. Action versions SHA-pinned per the convention in the peer repos. Verified locally: - cargo build (clean) - cargo test --lib (366 passing) - cargo clippy --all-targets -- -D warnings (clean) - cargo check --features proxy_tls_e2e --tests fails with a precise error pointing at the missing ProxyConfig/TlsConfig fields — the rust-e2e.yml precondition handles this cleanly - All 9 workflow YAML files parse Co-authored-by: Isaac Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-5 review fixes: - pyo3-checks.yml: add precondition step that checks for pyo3/Cargo.toml and gates every subsequent step. The workflow's paths: filter still fires on root Cargo.toml/Cargo.lock changes (kernel deps can affect pyo3) but the pyo3/ sub-crate itself lands in PR #13. Until then, the job skips cleanly with a ::notice:: instead of red-lighting kernel-only PRs. - pr-checks.yml: tighten the cargo-test comment to be explicit about which suites run (unit + doc + wiremock integration) and which don't (v0_*_e2e — #[ignore]'d, run by rust-e2e.yml). - apache-rat.yml: remove `|| echo "0"` silent-failure fallback in the UNAPPROVED parse. If RAT changes report format, CI now fails loud with a clear error rather than passing with 0. Added a follow-up note pointing at --output-style xml + xmlstarlet as the proper future-proof fix. - .ratignore: remove dangling comment block about CI files; add .ratignore itself to the ignore list. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-6 review fixes: - rust-e2e.yml proxy job: drop the job-level `services: squid` block and launch the unauthenticated proxy inline via `docker run`. The services block starts the container before any step runs — even when the precondition gate trips — and pays setup cost on every PR until v0.1. Inline matches the `tls` job's approach: zero boot on a skipped job, single cleanup step tears down both proxies. - pyo3-checks.yml: split the file-existence check into its own precondition job; the matrix `build-and-test` job declares `needs: precondition` + `if: needs.precondition.outputs.ready == 'true'` so the matrix doesn't expand (no runner boot, no checkout, no toolchain install for 3.9 / 3.12) when pyo3/ doesn't exist. - apache-rat.yml: validate the parsed UNAPPROVED is a bare integer with `[[ "${UNAPPROVED}" =~ ^[0-9]+$ ]]` before the `-gt` comparison. If a future RAT release adds a unit suffix (e.g. "5 files"), CI now fails with a precise error instead of bash arithmetic blowing up with "integer expression expected". - coverage.yml: tighten the Codecov OIDC comment to flag the silent-failure mode — `use_oidc: true` requires repo enrolment in Codecov's GitHub App + OIDC enabled; otherwise the action falls back to anonymous upload that Codecov rate-limits and may drop. `fail_ci_if_error: false` is the right call (don't red- light unrelated PRs on a Codecov outage) but it does mean the first few PRs must be visually inspected for the Codecov check to confirm uploads are flowing. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-7 review fix: - Drop `apache-rat.yml` and `.ratignore`; remove the "License headers" section from CLAUDE.md and the RAT row from the CI table. Reviewer asked "do we need this?" and the answer turned out to be no: none of the peer Databricks SQL driver repos (databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, databricks-sql-python) run Apache RAT or any equivalent header check, and none of them carry per-file Apache-2.0 headers on source files — they rely on the repo-root LICENSE + NOTICE to cover the Apache-2.0 grant. The kernel was the only fleet outlier. Matching the fleet convention. The headers already in files stay (harmless) but the CI gate and the mandate are gone. Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
Rebuild the kernel's CI/CD from a half-broken adbc-drivers/databricks inheritance into a working pipeline that mirrors the conventions in databricks/databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, and databricks-sql-python. What was wrong: - rust_test_pr.yaml called a reusable workflow (`rust_test.yaml`) that was never ported from adbc-drivers/databricks. Its own TODO comment said it would fail. - rust_coverage_report.yaml waited for a workflow named "Rust Test" that doesn't exist locally — it would never fire. - ci/test_package.py imported adbc_driver_manager; the legacy ADBC layer was removed in PR 7 (#11). The kernel is no longer an ADBC driver; the smoke test it implemented exercises a delivery vector the kernel no longer offers. PyO3 smoke testing comes via PR #13. - manifest.toml was the ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI." - The "proxy" and "tls" jobs in rust-e2e.yml referenced tests/proxy_e2e.rs / tls_e2e.rs, both #![cfg(feature = "legacy-adbc")]-gated and deleted alongside ADBC in PR #11. What's added (.github/workflows/): pr-checks.yml cargo fmt --check + clippy -D warnings + cargo test --workspace on every PR. Replaces the broken rust_test_pr.yaml. dco-check.yml Verbatim port of databricks-sql-go's dco-check.yml. CLAUDE.md mandates `git commit -s`; this enforces it. coverage.yml cargo llvm-cov → Codecov via OIDC. Standalone — no longer waits on a missing "Rust Test" workflow. license-check.yml cargo-deny against deny.toml. Replaces the cargo-about reference in CLAUDE.md; cargo-deny is the standard Rust-ecosystem gate (handles licenses + advisories + bans). apache-rat.yml Java-based Apache RAT against the source tree. CLAUDE.md claimed this ran but no workflow existed. Files to skip live in .ratignore. close-stale.yml 30-day stale + 7-day close window. Direct port from databricks-jdbc. release.yml Triggers on `v*.*.*` tag push: tag-version vs Cargo.toml version check → fmt → clippy → test → dry-run publish → real publish. workflow_dispatch with dry_run input for manual rehearsals. pyo3-checks.yml Maturin build + cargo test for the pyo3/ sub-crate. Path-gated on pyo3/** so this workflow only fires after PR #13 lands the Python wrapper. rust-e2e.yml Reworked: kept the live-workspace v0 E2E job (Session::open, execute, submit, await_result, metadata). Proxy + TLS jobs are kept and ported to the v0 surface — see "Proxy / TLS port" below. Proxy / TLS port (replaces dropping the jobs): - tests/proxy_e2e.rs and tests/tls_e2e.rs are restored with v0 bodies: they call SessionBuilder::proxy(ProxyConfig { url, username, password, bypass_hosts }) and SessionBuilder::tls(TlsConfig { trusted_certificate_path, allow_self_signed, allow_hostname_mismatch }). These fields don't exist yet in src/config.rs (both structs are #[non_exhaustive] placeholders); the test files are #![cfg(feature = "proxy_tls_e2e")]-gated so they're excluded from the default build. - Cargo.toml gains a `proxy_tls_e2e = []` feature. - rust-e2e.yml's proxy and tls jobs run a `cargo check --features proxy_tls_e2e --tests` precondition; if it doesn't compile (the v0.1 ProxyConfig/TlsConfig work isn't done), the job emits a clear ::warning and short-circuits cleanly. When v0.1 lands the fields, the feature compiles and the jobs auto-fire. - ci/proxy/ configs are kept — consumed by the proxy job once the feature compiles. - docs/migration-plan.md §7 gains a "Proxy + TLS E2E coverage (v0.1)" entry naming the four-step kernel work that unblocks this: flesh ProxyConfig, flesh TlsConfig, plumb both through client/http.rs, flip the feature default. What's deleted (only files genuinely tied to vectors the kernel no longer offers): .github/workflows/rust_test_pr.yaml (broken — replaced) .github/workflows/rust_coverage_report.yaml (dead — replaced) ci/test_package.py (ADBC vector gone; PyO3 in PR #13) manifest.toml (ADBC discovery file; the kernel isn't an ADBC driver) Other: - deny.toml — license + advisory allowlist for cargo-deny. Mirrors the prior about.toml allowlist plus a few standard permissive licenses cargo-deny encounters in the dep tree. - .ratignore — globs Apache RAT should skip (Cargo.lock, markdown, target/, LICENSE, etc.). - .gitignore — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - CLAUDE.md — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at deny.toml (not about.toml); "License headers" mentions .ratignore. All workflows run on the `databricks-protected-runner-group / linux-ubuntu-latest` pool, matching peer repos. Action versions SHA-pinned per the convention in the peer repos. Verified locally: - cargo build (clean) - cargo test --lib (366 passing) - cargo clippy --all-targets -- -D warnings (clean) - cargo check --features proxy_tls_e2e --tests fails with a precise error pointing at the missing ProxyConfig/TlsConfig fields — the rust-e2e.yml precondition handles this cleanly - All 9 workflow YAML files parse Co-authored-by: Isaac Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-5 review fixes: - pyo3-checks.yml: add precondition step that checks for pyo3/Cargo.toml and gates every subsequent step. The workflow's paths: filter still fires on root Cargo.toml/Cargo.lock changes (kernel deps can affect pyo3) but the pyo3/ sub-crate itself lands in PR #13. Until then, the job skips cleanly with a ::notice:: instead of red-lighting kernel-only PRs. - pr-checks.yml: tighten the cargo-test comment to be explicit about which suites run (unit + doc + wiremock integration) and which don't (v0_*_e2e — #[ignore]'d, run by rust-e2e.yml). - apache-rat.yml: remove `|| echo "0"` silent-failure fallback in the UNAPPROVED parse. If RAT changes report format, CI now fails loud with a clear error rather than passing with 0. Added a follow-up note pointing at --output-style xml + xmlstarlet as the proper future-proof fix. - .ratignore: remove dangling comment block about CI files; add .ratignore itself to the ignore list. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-6 review fixes: - rust-e2e.yml proxy job: drop the job-level `services: squid` block and launch the unauthenticated proxy inline via `docker run`. The services block starts the container before any step runs — even when the precondition gate trips — and pays setup cost on every PR until v0.1. Inline matches the `tls` job's approach: zero boot on a skipped job, single cleanup step tears down both proxies. - pyo3-checks.yml: split the file-existence check into its own precondition job; the matrix `build-and-test` job declares `needs: precondition` + `if: needs.precondition.outputs.ready == 'true'` so the matrix doesn't expand (no runner boot, no checkout, no toolchain install for 3.9 / 3.12) when pyo3/ doesn't exist. - apache-rat.yml: validate the parsed UNAPPROVED is a bare integer with `[[ "${UNAPPROVED}" =~ ^[0-9]+$ ]]` before the `-gt` comparison. If a future RAT release adds a unit suffix (e.g. "5 files"), CI now fails with a precise error instead of bash arithmetic blowing up with "integer expression expected". - coverage.yml: tighten the Codecov OIDC comment to flag the silent-failure mode — `use_oidc: true` requires repo enrolment in Codecov's GitHub App + OIDC enabled; otherwise the action falls back to anonymous upload that Codecov rate-limits and may drop. `fail_ci_if_error: false` is the right call (don't red- light unrelated PRs on a Codecov outage) but it does mean the first few PRs must be visually inspected for the Codecov check to confirm uploads are flowing. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-7 review fix: - Drop `apache-rat.yml` and `.ratignore`; remove the "License headers" section from CLAUDE.md and the RAT row from the CI table. Reviewer asked "do we need this?" and the answer turned out to be no: none of the peer Databricks SQL driver repos (databricks-jdbc, databricks-sql-go, databricks-sql-nodejs, databricks-sql-python) run Apache RAT or any equivalent header check, and none of them carry per-file Apache-2.0 headers on source files — they rely on the repo-root LICENSE + NOTICE to cover the Apache-2.0 grant. The kernel was the only fleet outlier. Matching the fleet convention. The headers already in files stay (harmless) but the CI gate and the mandate are gone. Signed-off-by: Gopal Lal <gopal.lal@databricks.com> Round-8 review fixes: - Drop `release.yml` per maintainer direction (release will be cut from a central repo). Removes the F7 `cargo pkgid` parse problem along with it. - Drop `tests/proxy_e2e.rs`, `tests/tls_e2e.rs`, the `proxy_tls_e2e` cargo feature, and the `proxy` + `tls` jobs from `rust-e2e.yml`. The kernel-side `ProxyConfig` / `TlsConfig` fields don't exist yet, so the v0-shaped tests didn't compile and the CI jobs short-circuited on every PR. Carrying broken-by-design tests in tree was reviewer-flagged clutter; v0.1 will port them fresh against the new struct shape (the ADBC-era versions in git history are the reference). `ci/proxy/` preserved on disk for reuse. `docs/migration-plan.md` §7 updated to describe the new v0.1 plan (single PR off main, includes test port + CI job re-add). - Wire pyo3 live pytest suite. `pyo3-checks.yml` swaps `maturin build --release` (built but never installed) for `maturin develop` (builds + installs into the runner Python in one step). Adds `pytest -v` step. Job gains `environment: azure-prod` + the three DATABRICKS_* secrets so the `@live` test tier runs against the configured warehouse on repo PRs; the no-network tier (test_module.py + test_auth.py) runs unconditionally and the `@live` tests auto-skip on fork PRs without approval. - Remove the "CI" section from CLAUDE.md. Workflows are self-documenting via `.github/workflows/*.yml`; the table was duplicate context with a maintenance burden. - Trim historical context from coverage.yml's header comment (the "replaces the dead rust_coverage_report.yaml" block belongs in git log, not the running workflow file). - Fix codecov-action SHA. The original `b9fd7d16...` was fabricated; first-pass reviewer-suggested `4650159d...` was a v5.4.3 *tag object* SHA, not a commit SHA (GitHub returns 404 for `git/commits/{sha}` on tag objects even though the action runner accepts them). Correct commit SHA for v5.4.3 is `18283e04ce6e62d37312384ff67231eb8fd56d24`. Verified via `gh api repos/codecov/codecov-action/git/refs/tags/v5.4.3` → tag object → resolve to commit. - Fix taiki-e/install-action comment. SHA `a416ddee...` is real and works, but the `# v2.49.32` comment was wrong — that SHA is actually tagged `v2.57.1`. Two callsites corrected (coverage.yml, license-check.yml). Verifier note: every action pin in `.github/workflows/` was audited end-to-end against the GitHub API — each SHA exists as a real commit and each commit is the actual target of the documented tag. Script lives in commit context only (not committed); rerunnable by walking `grep -rhnE "uses: [^/]+/[^@]+@[a-f0-9]{40}" .github/workflows/`. Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
## Summary Rebuild the kernel's CI/CD into a working pipeline. Before this PR, the only functioning workflow was `rust-e2e.yml`'s proxy + tls jobs — and those referenced test files that were deleted with the ADBC layer in PR #11. The unit-test gate (`rust_test_pr.yaml`) called a reusable workflow that was never ported from `adbc-drivers/databricks`, and the coverage workflow waited for a workflow that doesn't exist locally. This PR replaces the broken pieces with a 9-workflow pipeline that mirrors the conventions in the other Databricks OSS SQL driver repos (`databricks/databricks-jdbc`, `databricks-sql-go`, `databricks-sql-nodejs`, `databricks-sql-python`). ## What's added | Workflow | Purpose | Modeled after | |---|---|---| | `pr-checks.yml` | `cargo fmt --check`, `cargo clippy -D warnings`, `cargo test --workspace` on every PR | `databricks-jdbc/prCheck.yml`, `databricks-sql-python/code-quality-checks.yml` | | `dco-check.yml` | DCO sign-off enforcement | `databricks-sql-go/dco-check.yml` (verbatim port) | | `coverage.yml` | `cargo llvm-cov` → Codecov via OIDC | `databricks-sql-python/code-coverage.yml` | | `license-check.yml` | `cargo deny check` (licenses + advisories) | — | | `apache-rat.yml` | Apache-2.0 header check across the source tree | `databricks-jdbc` convention | | `close-stale.yml` | Daily cron, 30-day stale + 7-day close | `databricks-jdbc/closeStale.yml` | | `release.yml` | `cargo publish` on `v*.*.*` tag push (dry-run-safe `workflow_dispatch` available) | — | | `pyo3-checks.yml` | Maturin build + cargo test, path-gated on `pyo3/**` | Skeleton for PR #13 | | `rust-e2e.yml` | Reworked: kept v0 live-workspace E2E job; dropped proxy + tls jobs whose test files were deleted with ADBC | — | ## What's deleted - `.github/workflows/rust_test_pr.yaml` — referenced a reusable workflow that doesn't exist locally - `.github/workflows/rust_coverage_report.yaml` — waited for a workflow named "Rust Test" that doesn't exist - `ci/test_package.py` — imported `adbc_driver_manager`; ADBC was removed in PR #11 - `ci/proxy/{htpasswd, squid-auth.conf}` — consumed only by the proxy E2E job that ran tests deleted with ADBC - `manifest.toml` — ADBC driver-manager discovery file; its own comment said "Remove this once the kernel surfaces its own non-ADBC FFI" ## What's also new (supporting files) - `deny.toml` — `cargo-deny` config (licenses + advisories + bans + sources). Mirrors the prior `about.toml` allowlist plus a few standard permissive licenses. - `.ratignore` — globs Apache RAT should skip (`Cargo.lock`, markdown, `target/`, `LICENSE`, etc.). - `.gitignore` — tighten `coverage.*` to specific extensions so `.github/workflows/coverage.yml` isn't silently ignored. - `CLAUDE.md` — new "CI" section listing the workflows; "Adding Cargo dependencies" now points at `deny.toml`; "License headers" mentions `.ratignore`. ## Design decisions - **Runner pool:** `databricks-protected-runner-group / linux-ubuntu-latest`. Matches all four peer repos. - **`cargo-deny` over `cargo-about`:** CLAUDE.md previously said cargo-about, but cargo-about is for generating attribution pages, not for gating on an allowlist. `cargo-deny check` is the standard ecosystem tool for "fail on unapproved license" and bundles RustSec advisory checks. `about.toml` is preserved for when an attribution page is needed. - **No MSRV matrix today.** The peer repos test against multiple language versions (JDK 11/17/21, Python 3.9–3.14, Go 1.20.x). The kernel doesn't pin an MSRV yet, so the matrix is single-cell. Easy to add later. - **PyO3 wheel publishing deferred:** `release.yml` only handles `cargo publish` to crates.io. PyO3 wheels need a separate maturin-based release workflow that lands after PR #13. - **v0 proxy/tls live-network suite is a tracked follow-up:** the kernel has `ProxyConfig` / `TlsConfig` and wiremock coverage for the HTTP plumbing, but no v0 live-network proxy/tls E2E tests exist (the legacy ADBC ones were deleted with ADBC). The full proxy/tls integration story can be added without touching this CI change. ## Test plan - [x] All 9 workflow YAML files parse cleanly (`ruby -ryaml`) - [x] `cargo build` — clean - [x] `cargo test --lib` — 366 passing - [x] Branched off `origin/main`, DCO-signed commit - [ ] Workflows actually run on this PR (visible once GitHub picks it up) - [ ] Secrets confirmed present in repo settings (`DATABRICKS_HOST`, `DATABRICKS_TOKEN`, `TEST_PECO_WAREHOUSE_HTTP_PATH`, `DATABRICKS_TEST_CLIENT_ID`, `DATABRICKS_TEST_CLIENT_SECRET`, `CARGO_TOKEN` for release) - [ ] Codecov OIDC integration enabled at the org level This pull request and its description were written by Isaac. Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
Surfaces the kernel's positional-param API to Python. Lifts the
NotSupportedError the connector backend currently raises for
parametrized queries — the biggest functional gap for use_sea=True
users.
PyO3 surface:
stmt.bind_param(ordinal: int, value_str: Optional[str], sql_type: str)
`(ordinal, value_str, sql_type)` matches the shape the connector
already produces in `TSparkParameter` — value is string-serialized,
type carries the SQL intent (`"INT"`, `"DECIMAL(10,2)"`,
`"TIMESTAMP"`, etc.). Re-parsing into a native Python type just to
re-encode into a kernel `TypedValue` would be a lossy round-trip,
so the kernel binding takes the string directly.
Implementation:
- New `params.rs` module owns the `(sql_type, value_str) -> TypedValue`
parser. Free function so it's unit-testable in pure Rust.
- Handles: BOOLEAN, TINYINT/SMALLINT/INT/BIGINT, FLOAT/DOUBLE,
STRING/VARCHAR/CHAR, DATE, TIMESTAMP (with and without sub-second
precision, ISO-8601 T-separator), INTERVAL, DECIMAL(p,s),
VOID/None.
- Rejects: BINARY (SEA wire limitation kernel-side), compound types
(ARRAY/MAP/STRUCT — own follow-up), named-binding mode (kernel
v0 rejects at execute time anyway).
- Errors map to `KernelError(code='InvalidArgument', ...)` —
surfaces at bind time, before execute, with a clear message.
Tests:
- 16 Rust unit tests in `params.rs` covering each type variant,
error paths, casing tolerance. Visible to `cargo test -p` thanks
to the `rlib` crate-type addition from PR #13's C1.
- 4 new live pytests against dogfood:
- all-types round-trip in one SELECT (INT, BIGINT, STRING, BOOL,
DOUBLE, DECIMAL(10,2), DATE, TIMESTAMP, NULL)
- VOID-as-null
- compound type rejection
- bad literal at bind time
Total pyo3 pytest count: 35/35 pass (was 31).
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Surfaces the kernel's positional-param API to Python. Lifts the
NotSupportedError the connector backend currently raises for
parametrized queries — the biggest functional gap for use_sea=True
users.
PyO3 surface:
stmt.bind_param(ordinal: int, value_str: Optional[str], sql_type: str)
`(ordinal, value_str, sql_type)` matches the shape the connector
already produces in `TSparkParameter` — value is string-serialized,
type carries the SQL intent (`"INT"`, `"DECIMAL(10,2)"`,
`"TIMESTAMP"`, etc.). Re-parsing into a native Python type just to
re-encode into a kernel `TypedValue` would be a lossy round-trip,
so the kernel binding takes the string directly.
Implementation:
- New `params.rs` module owns the `(sql_type, value_str) -> TypedValue`
parser. Free function so it's unit-testable in pure Rust.
- Handles: BOOLEAN, TINYINT/SMALLINT/INT/BIGINT, FLOAT/DOUBLE,
STRING/VARCHAR/CHAR, DATE, TIMESTAMP (with and without sub-second
precision, ISO-8601 T-separator), INTERVAL, DECIMAL(p,s),
VOID/None.
- Rejects: BINARY (SEA wire limitation kernel-side), compound types
(ARRAY/MAP/STRUCT — own follow-up), named-binding mode (kernel
v0 rejects at execute time anyway).
- Errors map to `KernelError(code='InvalidArgument', ...)` —
surfaces at bind time, before execute, with a clear message.
Tests:
- 16 Rust unit tests in `params.rs` covering each type variant,
error paths, casing tolerance. Visible to `cargo test -p` thanks
to the `rlib` crate-type addition from PR #13's C1.
- 4 new live pytests against dogfood:
- all-types round-trip in one SELECT (INT, BIGINT, STRING, BOOL,
DOUBLE, DECIMAL(10,2), DATE, TIMESTAMP, NULL)
- VOID-as-null
- compound type rejection
- bad literal at bind time
Total pyo3 pytest count: 35/35 pass (was 31).
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
## Summary Phase 2 follow-up to [#13](#13). Adds positional-parameter binding to the PyO3 `Statement` surface — the biggest functional gap for `use_sea=True` users. ## What it adds \`\`\`python stmt = session.statement() stmt.set_sql("SELECT * FROM t WHERE id = ? AND name = ? AND created_at > ?") stmt.bind_param(1, "42", "INT") stmt.bind_param(2, "alice", "STRING") stmt.bind_param(3, "2026-01-01", "DATE") exec_ = stmt.execute() \`\`\` \`(ordinal, value_str, sql_type)\` matches the shape the connector already produces in \`TSparkParameter\` — value is string-serialized, type carries the SQL intent. Re-parsing into a native Python type just to re-encode into a kernel \`TypedValue\` would be a lossy round-trip, so the kernel binding takes the string directly. ## Type coverage | Supported | SQL type names | TypedValue variant | |---|---|---| | ✅ | \`BOOLEAN\` / \`BOOL\` | \`Bool\` | | ✅ | \`TINYINT\` / \`SMALLINT\` / \`INT\` / \`INTEGER\` / \`BIGINT\` / \`LONG\` | \`Int8/16/32/64\` | | ✅ | \`FLOAT\` / \`DOUBLE\` | \`Float32/64\` | | ✅ | \`STRING\` / \`VARCHAR\` / \`CHAR\` | \`String\` | | ✅ | \`DATE\` | \`Date\` (parsed \`%Y-%m-%d\`) | | ✅ | \`TIMESTAMP\` / \`TIMESTAMP_NTZ\` | \`Timestamp\` (accepts naive with/without sub-second precision, ISO-8601 \`T\` separator) | | ✅ | \`DECIMAL(p,s)\` | \`Decimal { value, precision, scale }\` — parses parenthesised form | | ✅ | \`INTERVAL\` | \`Interval\` | | ✅ | \`VOID\` / \`None\` value | \`Null\` | | ❌ | \`BINARY\` | rejected — SEA wire limitation kernel-side (workaround: hex-encode + \`unhex(?)\` in SQL) | | ❌ | \`ARRAY\` / \`MAP\` / \`STRUCT\` | rejected — compound types are a follow-up | | ❌ | named bindings | not yet — kernel v0 rejects at execute time anyway | Bad literals (\`bind_param(1, "not-a-number", "INT")\`) surface as \`KernelError(code='InvalidArgument', ...)\` at bind time, before execute, with a pointed message. ## Implementation - New \`params.rs\` module owns the \`(sql_type, value_str) -> TypedValue\` parser. Pure Rust, free-function form so it's unit-testable without the GIL. - One new method on the \`Statement\` pyclass that calls the parser then \`spec().param(ordinal, ...)\`. ## Test plan - [x] \`cargo test -p databricks-sql-kernel-pyo3\` — **16 new Rust unit tests** covering each type variant, error paths, casing tolerance, decimal precision/scale extraction. Visible to \`cargo test\` thanks to the \`rlib\` crate-type addition that landed in #13. - [x] \`cargo build --workspace\` / \`cargo clippy --workspace --all-targets -- -D warnings\` / \`cargo +stable fmt --all -- --check\` - [x] \`cargo test --workspace\` clean - [x] **Live pytest against dogfood** — 4 new tests in \`pyo3/tests/test_execute.py\`: - \`test_bind_param_positional_round_trips_all_simple_types\`: single SELECT binds INT, BIGINT, STRING, BOOLEAN, DOUBLE, DECIMAL(10,2), DATE, TIMESTAMP, NULL; server echoes all values back. - \`test_bind_param_void_treated_as_null\`: \`VOID\` SQL type → SQL NULL. - \`test_bind_param_compound_type_rejected\`: \`ARRAY<INT>\` → \`KernelError(InvalidArgument)\`. - \`test_bind_param_invalid_value_surfaces_error\`: bad INT literal → \`KernelError(InvalidArgument)\` at bind time, not execute. Total pyo3 pytest count: **35/35 pass** (was 31). This pull request and its description were written by Isaac. Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
…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>
Summary
Phase 1 of the PySQL × kernel integration plan (design, doc PR #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
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:
Each executed handle owns its own `Arc`, so it outlives the parent `Statement` cleanly and its own Drop hits the wire. Documented in the `Statement.close()` docstring in `da7a0c8`.
Known gaps (will be follow-ups)
Test plan
This pull request and its description were written by Isaac.