Skip to content

feat(pyo3): Phase 1 — PyO3 binding for the Databricks SQL Kernel - #13

Merged
vikrantpuppala merged 9 commits into
mainfrom
feat/pyo3-scaffold
May 15, 2026
Merged

vikrantpuppala merged 9 commits into
mainfrom
feat/pyo3-scaffold

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

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

Commit What it adds
`b41acc0` Scaffold — `Session`, `Statement`, `ExecutedStatement`, `KernelError`. PAT auth, sync `execute()`
`6bc3ecd` `Metadata` + `ResultStream` — all 10 metadata methods, shared fetch helpers
`0bd898f` Async statement — `Statement.submit() -> ExecutedAsyncStatement` with `status / await_result / fetch_result / cancel / close`
`c58710d` (Reverted in 4847a07) External auth POC
`294730a` Address first-round review — typed errors, `run_kernel!` macros, pytest harness
`b60166a` Wire `session_conf` through `Session(...)`
`4847a07` Drop External auth. Phase 1 ships PAT-only; OAuth decision deferred
`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`, 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)

  • 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) 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` is a possible later refactor when measured pressure justifies it.

Test plan

  • `cargo build --workspace`
  • `cargo clippy --workspace --all-targets -- -D warnings`
  • `cargo +stable fmt --all -- --check`
  • `cargo test --workspace` — kernel suite unchanged
  • 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.

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>
@vikrantpuppala vikrantpuppala changed the title feat(pyo3): scaffold PyO3 sub-crate feat(pyo3): Phase 1 — PyO3 binding for the Databricks SQL Kernel May 13, 2026
}
}

#[pyclass(name = "ExecutedAsyncStatement", unsendable)]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread pyo3/src/errors.rs Outdated
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()))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@gopalldb

Copy link
Copy Markdown
Collaborator
  1. Idempotent close() is open-coded 5 times (low — pattern is fine, helper would be cleaner)

Session, Statement, ExecutedStatement, ExecutedAsyncStatement, ResultStream all implement the same pattern:

let Some(inner) = self.inner.take() else { return Ok(()); };
// drop inner, do nothing else

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
this. Not blocking — take() is already cheap, and Rust readers see the pattern immediately. But it'll grow to 6× / 7× / 8× as new handle types land.

  1. Use-after-close guard repeated ~25 times across methods (medium — should be a helper now)

Every method that touches inner starts with:

let inner = self.inner.as_ref()
.ok_or_else(|| KernelError::new_err("X is closed"))?;

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,
or — better — define a trait MayBeClosed and impl once. ~15-line refactor that cuts ~75 lines of boilerplate. Worth doing now because every new method on these handles will add another 3 lines otherwise.

  1. py.detach(|| runtime.block_on(...)).map_err(|e| to_py_err(py, e)) boilerplate, ~25 sites (medium — macro it)

Every kernel call is wrapped with the same three steps:

  1. py.detach(...) to drop the GIL,
  2. runtime.block_on(...) to bridge async → sync,
  3. .map_err(|e| to_py_err(py, e)) to map kernel errors.

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
PyO3; pure local hygiene.

  1. 10 metadata methods are 80% identical (high — macro it before Phase 2)

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
/ Option (good news: opt_identifier() / opt_pattern() are already factored — but the calls are inlined), (c) py.detach + block_on + map_err (item 3 above), (d) wrap the returned ResultStream.
Steps (a), (c), (d) are character-identical across all 10.

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
methods and the same 10 macro expansions can be re-applied.

  1. smoke.py is 353 lines of print() + check() (medium — convert to pytest)

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 surface area. Convert to pytest with one test_* per scenario before Phase 2. Reasons:

  • Selective runs (pytest -k metadata)
  • Real per-test failure output instead of "section 12 failed: KernelError(...)" mid-script
  • CI parallelism
  • Test discovery (no more manual section listing)

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
exactly right — don't refactor.

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
Error::unauthenticated() with text preserved, rejects non-string and empty-string returns. Send + Sync bound is correct (Py is Send + Sync).

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
never go through Session::open(). That's a real coverage gap — the integration test in smoke.py only verifies that the kernel rejects External, not that the trampoline actually serves a token end-to-end.
Track explicitly that the kernel-side follow-up PR must add a real integration test (probably wiremock-based).

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
own caching / refresh" — fair, but worth documenting prominently in the public-facing PyO3 docstring so wrapper authors don't accidentally write a callback that does a network round-trip per call.

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
could let the kernel reuse the host's runtime, but that's its own design decision — defer.

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
libpython, enabling unit tests. This is the idiomatic setup. ✓

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
the first wheel publish.

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:

  1. Add a run_kernel! macro to collapse the py.detach + block_on + map_err 25-site pattern (item 3).
  2. Add alive() / alive_mut() helpers to every wrapper and use them consistently (item 2).
  3. Verify PyPI name databricks-sql-kernel is available and the right call.

Worth doing now, before Phase 2:
4. Macro-ise the 10 metadata methods (item 4). Highest payoff because napi-rs duplicates it next.
5. Convert smoke.py to pytest (item 5).

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>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

@gopalldb thanks for the thorough review — addressed the bulk of the feedback in 294730a. Summary:

Addressed

# Item What I did
inline:errors.rs KernelError as pyclass with #[pyo3(get)] Wanted to do exactly this, but #[pyclass(extends=PyException)] is rejected at compile time under abi3 ("with the abi3 feature enabled, PyO3 does not support subclassing native types"). Kept create_exception! and attached the structured fields via setattr on the exception value — Python now reads err.code / err.sql_state / err.query_id directly as attributes, same ergonomics, abi3 preserved. ExecutedAsyncStatement.status() returns (state, Optional[KernelError]) — the exception value itself, not a dict — so callers branch on failure.code.
#3 run_kernel! macro Three macros in pyo3/src/macros.rs: run_kernel!(py, runtime, future), run_kernel_block!(py, runtime, { ... }), run_sync_kernel!(py, sync_call). Applied across ~25 sites. Single source of truth for py.detach + block_on + error mapping.
#2 alive! / alive_mut! consistency Macros that expand to the close-guard pattern; closed_err("X") builds an InvalidStatementHandle-coded KernelError once. Applied across every wrapper.
#4 Metadata methods Outer scaffolding macro'd via run_kernel_block!; inner conversions stay explicit. The 10 methods are now ~6 lines each. Going further would need a tiny DSL that I think hurts readability more than it helps — happy to revisit if you'd prefer the all-the-way version.
#5 pytest harness smoke.py (353 lines) gone. Replaced by pyo3/tests/ — 6 modules, 30 tests, module-scoped session fixture, env-var gating, pytest.ini for conftest discovery. All 30 pass against dogfood in ~19s. Live tests skip cleanly when creds aren't set.
Other — token caching docstring Added prominent note on Session.__new__ that the external callback fires once per HTTP request and MUST be cheap (in-process cache lookup is the right pattern; network round-trip will multiply request latency).
Other — PyPI name Verified via Databricks JFrog proxy: 404 for databricks-sql-kernel, 200 for databricks-sql-connector (sanity). Name is free to claim.

Deferred (acknowledged, follow-up tracked)

# Item Why deferred
inline:executed_async.rs pyo3-async-runtimes (Python awaitables) Fundamental shape change to every method on every class. Doesn't unblock Phase 2 — the connector's DatabricksClient contract is sync, and any awaitable returned would be loop.run_until_complete'd by the connector anyway. Worth a separate design conversation about exposing both a sync and an async surface.
#1 PyClose trait for 5× idempotent close Reviewer marked not-blocking. The 25-line repetition that mattered (#2 + #3) is gone; the remaining 5×3-line pattern is fine for now.
Other — auth trampoline integration test Belongs in the kernel-side AuthConfig::External enablement PR (which will need wiremock + a real Session::open exercising External). The PyO3 trampoline is fully unit-tested in pyo3/src/auth.rs::tests; the kernel side is where the missing coverage is.

Net diff in the new commit: +262 / -594 (-332 lines). All checks green: workspace cargo build / clippy --workspace --all-targets -- -D warnings / fmt --check / test, plus the 30 pytests against dogfood.

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>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Folded in one more small commit (b60166a) — wires session_conf (the SEA session_configuration map) through Session(...). Was a known gap from Phase 2 planning; cheap enough to land here since Phase 2 will need it day-1 for the connector's session_configuration kwarg.

Live test added: Session(session_conf={'ANSI_MODE': 'false'}) + SET ANSI_MODE confirms the map reaches the server. 31/31 pytests pass; cargo clippy/fmt/test green.

gopalldb added a commit that referenced this pull request May 14, 2026
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>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

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:

  • auth.rs::PythonTokenProvider trampoline + 4 Rust unit tests
  • token_callback kwarg on Session.__new__
  • The extension-module Cargo feature gymnastics (only existed for the trampoline tests)
  • async-trait dep

What stays: everything else. Surface is now Session(host, http_path, *, access_token=..., catalog=..., schema=..., session_conf=...). Anything else for auth_type raises ValueError at construction.

29 pyo3/tests still pass. -249 lines net.

gopalldb added a commit that referenced this pull request May 14, 2026
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>
@gopalldb

Copy link
Copy Markdown
Collaborator

Review — PyO3 Phase 1

Verified locally against 4847a07 (the live PR HEAD): cargo +stable fmt --check, cargo clippy --workspace --all-targets -- -D warnings, and cargo test --workspace all clean. 22 files, +2211 / -0.

Architecture is sound and the design choices line up with the kernel:

  • One tokio runtime per Session, Arc-cloned into children.
  • py.detach(...) around every kernel I/O via the run_kernel! / run_kernel_block! / run_sync_kernel! macros.
  • alive! / alive_mut! + Option<Inner> for idempotent close + use-after-close → KernelError(code='InvalidStatementHandle').
  • KernelError built via create_exception! so abi3 stays clean; structured fields ride on setattr.
  • Schema cached on ExecutedStatement / ResultStream so arrow_schema() works after close().
  • exhausted: bool short-circuit on streams.
  • All metadata methods are kwarg-only.
  • arrow-pyarrow = "57" pinned to match the kernel for zero-copy batch handoff.
  • session_conf round-trip is verified live (ANSI_MODE=false).

Required before merge

C1. crate-type = ["cdylib"] makes Rust unit tests silently unreachable.
cargo test -p databricks-sql-kernel-pyo3 reports running 0 tests / ok even though the tests/ dir compiles. Any future #[cfg(test)] Rust test in pyo3/src/** will be a no-op without a warning. Fix: crate-type = ["cdylib", "rlib"]. Verified locally — clippy stays green. ~1 LOC.

C2. PR description is stale.
Body references External auth, PythonTokenProvider, and "4 trampoline unit tests pass" — all dropped in 4847a07. Reviewers shouldn't have to diff the description against the diff to know what's actually in the PR. Rewrite the Summary + Test plan to match the live PAT-only state.

C3. test_session_conf_round_trips is missing @live.
pyo3/tests/test_session.py:50-79 does os.environ["DATABRICKS_HOST"] unconditionally. Crashes in CI / offline with KeyError. Add the @live decorator like the other live tests.

C4. Drop the unused async-trait dep.
pyo3/Cargo.toml:46 declares async-trait = "0.1". After the External refactor, no #[async_trait] or async_trait:: appears anywhere under pyo3/src/** — dead dependency.

Important — decide now or document

Statement.close() is a no-op on the server, but users expect it to send CloseStatement.
Current pyo3 impl just drops self.inner. The kernel Statement itself has no server-side close — the closeable thing is each ExecutedStatement (via ExecutedStatementHandle::close). That's internally consistent with the kernel's four-type split, but it surprises every JDBC / ODBC / PySQL user, who expects cursor.close() / stmt.close() to release server-side resources for the currently-bound execution.

Two options:

  • (a) Add Statement::close(&mut self) -> Result<()> on the kernel side that explicitly fires CancelStatement + CloseStatement against last_statement_id if tracked. Wire it from the pyo3 binding. Matches user mental model; doesn't rely on Drop semantics (which are unreliable when Python GC happens off a tokio runtime thread).
  • (b) Keep the current shape, but document loudly that the cursor-close semantic lives on the executed handle, and have the PySQL connector backend always close the executed handle before the statement.

I'd take (a) — the kernel split is consistent but leaks through the close semantics; wrapping it in a user-friendly Statement::close() is the right ergonomic.

Phase 2 / follow-up (not blocking)

  • Parameter binding. Statement exposes only set_sql today; no bind_param / bind_param_named / statement_conf. PR description should be explicit that Phase 1 ships SQL-literals only.
  • Drop-on-GC safety. Verify the kernel's Drop for ExecutedStatement / ExecutedAsyncStatement / Session is graceful when GC happens off the tokio runtime context (Handle::try_current().map(...) vs raw tokio::spawn). If it relies on a current runtime, the pyo3 layer needs explicit synchronous cleanup on Drop.
  • unsendable pyclasses. Documented as required by the tokio runtime ownership. Worth a follow-up to move the runtime to process-global OnceLock<Runtime> so PySQL's thread-per-request shape isn't constrained.
  • Tokio feature flags in pyo3/Cargo.toml rely on transitive features = ["full"] from the kernel. Make explicit or comment.
  • KernelError.code vs error_code — two similarly-named string fields. Rename to disambiguate (server_error_code or similar).
  • Python ↔ Rust boundary tests with a mock HTTP server (e.g. pytest-httpserver) would cover the kernel-error → Python-exception attribute mapping path without requiring creds.
  • Kernel-side list_tables.table_types: Option<&[&str]> forces a per-call Vec<&str> allocation in the wrapper. Worth a kernel-side signature change later.

The architecture is right. After C1-C4 land and a decision on Statement.close(), ship.

— Isaac (AI-assisted review)

gopalldb added a commit that referenced this pull request May 14, 2026
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>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks @gopalldb — taking C1–C4 now. Wanted to push back on the Statement.close() framing first.

Drop already fires CloseStatement

Walked the three Drop impls. The kernel's lifecycle story is actually correct end-to-end:

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_id is left as-is. By construction it is only set immediately before ExecutedStatement::new wraps it; if the caller still holds an ExecutedStatement, that handle owns the close-on-drop responsibility. If the caller dropped the handle before this Statement, the handle's own Drop already 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 alive

If 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 in pyo3/src/** aren't silent.
  • C2: PR description rewrite to match the PAT-only state (External / trampoline references gone).
  • C3: test_session_conf_round_trips gated by @live.
  • C4: Drop the dead async-trait dep.

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>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Walking back my earlier reply — you were right, taking option (a).

The "rip exec_ out from under the caller" framing I led with was a strawman. If a caller is still actively using exec_, they wouldn't be calling stmt.close() anyway; when they do call it, they're explicitly opting out of further use, which matches what JDBC / ODBC / PySQL users already expect. And the kernel had the underlying mechanism the whole time — invalidate_prior (already called by execute() / submit() before re-use) fires CancelStatement + CloseStatement against the tracked last_statement_id and flips the validity flag. Statement::close just needed to expose that capability.

Landed in 7ffd2cb:

  • Kernel: pub async fn close(mut self) -> Result<()> on Statement. Symmetric with Session::close(self). Routes to invalidate_prior.
  • PyO3: Statement.close() rewritten from self.inner = None to drive the kernel's close() via run_kernel!. Idempotent via Option::take.
  • Tests:
    • Wiremock (statement_close_cancels_and_closes_outstanding_executed_handle) — confirms the held ExecutedStatement.cancel() short-circuits to InvalidStatementHandle after stmt.close().
    • pytest (test_statement_close_invalidates_held_executed_statement + test_statement_close_is_idempotent).
  • Docstrings updated on both sides.

One subtlety the pytest documents: fetch_next_batch() on the held handle still works after stmt.close(). The fetch path operates on already-buffered Arrow batches and doesn't go through the validity flag — same as JDBC, where rows already in the client buffer aren't unfetched by close(). The server-side state is what Statement::close actually releases. The wire-touching paths (cancel/close/async status/await_result/fetch_result) all check validity.

31/31 pyo3 pytests pass; cargo build/clippy/fmt/test workspace-wide clean. With C1/C3 from the previous push (crate-type = ["cdylib", "rlib"] + the @live body cleanup) and the PR description rewrite, I think C1–C4 + the Statement.close decision are all resolved.

— Isaac

@gopalldb gopalldb left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

gopalldb added a commit that referenced this pull request May 15, 2026
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>
@vikrantpuppala
vikrantpuppala merged commit f3e3798 into main May 15, 2026
gopalldb added a commit that referenced this pull request May 15, 2026
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>
gopalldb added a commit that referenced this pull request May 15, 2026
## 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>
vikrantpuppala added a commit that referenced this pull request May 18, 2026
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>
vikrantpuppala added a commit that referenced this pull request May 18, 2026
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>
vikrantpuppala added a commit that referenced this pull request May 18, 2026
## 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>
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants