Skip to content

[PECOBLR-2096] C ABI: expose OAuth U2M, custom headers, session validity, logging init - #162

Merged
vikrantpuppala merged 3 commits into
mainfrom
pecoblr-2096-c-abi-auth-headers-logging
Jul 10, 2026
Merged

vikrantpuppala merged 3 commits into
mainfrom
pecoblr-2096-c-abi-auth-headers-logging

Conversation

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Adds four C ABI entry points for capabilities the kernel already implements natively but did not surface over the C ABI — the biggest Private Preview unblock for the ODBC (and Go) consumers. Each is a thin "wire it through" over existing native code, following the established set_on_config / AuthSpec / header patterns.

New C ABI functions

Function Purpose Native backing
kernel_session_config_set_auth_u2m(client_id?, redirect_port, scopes?) OAuth U2M (auth code + PKCE, browser flow) + transparent token caching/refresh AuthConfig::oauth_u2m
kernel_session_config_set_custom_header(name, value) Append an HTTP header sent on every request HttpConfig.custom_headers
kernel_session_is_valid(session, *bool) Local liveness check (backs SQL_ATTR_CONNECTION_DEAD) new Session::is_valid
kernel_init_logging(level, file_path) Process-wide, once — route kernel tracing into a host log file existing init_logging

Details

  • U2M: new AuthSpec::OAuthU2M variant → build_session maps to the ready native AuthConfig::oauth_u2m. All args optional (NULL client_id → databricks-cli, port 0 → 8020, NULL scopes → all-apis+offline_access; offline_access yields a cached, auto-refreshed refresh token). Interactive: opening the session starts a localhost listener + opens the browser (documented in the header).
  • Custom headers: accumulated on the config (one pair per call, order preserved), applied via a fresh HttpConfig { custom_headers, ..default } so all other HTTP defaults (timeouts/pool/retry) are preserved.
  • is_valid: local-only (no server round-trip); reports whether the session's delete has been initiated. Header states the exact semantics so consumers don't expect dead-link detection.
  • init_logging: wraps the existing OnceLock-guarded init_logging; first call wins, later calls are safe no-ops. Always returns Success (bad path → stderr, matching the layer's best-effort contract).

Tests

C smoke tests cover all four — valid input, NULL-arg rejection where required, idempotent init. No behavior change to existing paths.

cargo fmt / clippy --all-targets clean; 673 lib tests + C smoke pass. Committed with DCO sign-off.

Unblocks the paired ODBC PR (U2M Auth_Flow=2, custom headers, connection validation, unified logging).

This pull request and its description were written by Isaac.

…ity, logging init

Adds four C ABI entry points for capabilities the kernel already
implements natively but did not surface over the C ABI — the biggest
Private Preview unblock for the ODBC (and Go) consumers.

- kernel_session_config_set_auth_u2m(client_id?, redirect_port, scopes?)
  — OAuth U2M (auth code + PKCE, browser flow) + transparent token
  caching/refresh. New AuthSpec::OAuthU2M variant maps to the existing
  native AuthConfig::oauth_u2m; all args optional (NULL client_id →
  databricks-cli, port 0 → 8020, NULL scopes → all-apis+offline_access).
- kernel_session_config_set_custom_header(name, value) — append an HTTP
  header sent on every request; accumulated on the config and applied via
  HttpConfig.custom_headers in build_session.
- kernel_session_is_valid(session, *bool) — local liveness check (session
  not closed / delete not initiated); no server round-trip. Backs
  SQLGetConnectAttr(SQL_ATTR_CONNECTION_DEAD). Adds Session::is_valid.
- kernel_init_logging(level, file_path) — process-wide, once (OnceLock);
  wraps the existing init_logging so a host can route kernel `tracing`
  logs into its own log file.

Header declarations with contracts (U2M is interactive; is_valid is
local-only; init_logging is once-per-process). C smoke tests cover all
four (valid input, NULL-arg rejection, idempotent init). No behavior
change to existing paths.

cargo fmt / clippy --all-targets clean; 673 lib tests + C smoke pass.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Comment thread src/session.rs Outdated
/// already-deleted session. It does not detect a server-side idle
/// timeout or a dropped network link. Used by the C ABI's
/// `kernel_session_is_valid`.
pub(crate) fn is_valid(&self) -> bool {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Session::is_valid() returns !self.inner.closed. Over the C ABI, the only entry point that flips closed to true is kernel_session_close (src/c_abi/session.rs:674), which calls initiate_delete() and frees the handle in the same call (Box::from_raw + drop) — after which probing is_valid is use-after-free (and the Safety contract forbids it). The async Session::close() that flips closed after a successful server delete (src/session.rs:501) is not exposed over the C ABI.

So every legal, non-UB call to kernel_session_is_valid observes closed == false and writes true. The false result — the entire reason the function exists — is unreachable. The ODBC layer wires this into SQLGetConnectAttr(SQL_ATTR_CONNECTION_DEAD); that gate can never fire, so the dominant real-world dead-connection case (server idle-timeout) is never detected.

Verified against kernel_session_close, initiate_delete, and Session::close at the head SHA. The behavior is honestly documented as a "local liveness" check, but the name/contract over-promises relative to what it can compute. Consider renaming to is_open/is_closed, or backing it with a real transport-outcome signal (a flag set when an RPC returns session-not-found).


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread tests/c/session_smoke.c
kernel_session_config_free(config);
}

/* U2M + custom-header setters accept valid input; header requires args. */

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The C smoke tests call the setters and then free the config — they never open a session, so the real transformation logic in build_session (comma-splitting scopes with trim + non-empty filter, collapsing an all-empty scope string to None, projecting custom_headers into a fresh HttpConfig preserving other defaults) never runs. There is also no Rust #[cfg(test)] module for c_abi/session.rs.

A regression in the scope parser or a header name/value swap would ship silently. Verified against src/c_abi/session.rs at the head SHA.

Suggested fix: add a Rust unit test (the crate already tests config projection without a network in src/session.rs) asserting scopes = "a, ,b," yields ["a","b"] and that two pushed headers survive in order with defaults intact.


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread tests/c/session_smoke.c
}

/* kernel_init_logging is idempotent and null-tolerant. */
static void test_init_logging(void) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The only is_valid test passes a NULL session and asserts InvalidArgument. The actual behavior (return true for a live session, false after close) is never asserted, so an inverted or hardcoded-true is_valid would pass every test. Verified against src/session.rs:385 and src/c_abi/session.rs:712.

Suggested fix: a Rust unit test that constructs a Session, asserts is_valid()==true, calls initiate_delete(), then asserts false.


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread src/c_abi/session.rs
/// # Safety
/// `level` / `file_path`, if non-null, must be NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn kernel_init_logging(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

On file-open failure the only signal is an eprintln! (typically discarded by a GUI/BI host with no console); the C ABI returns Success. The ODBC caller therefore believes kernel logs are flowing to its file. Combined with the OnceLock-poisoning issue, there is no eventual recovery and no error anywhere. Verified against src/c_abi/session.rs and src/logging.rs at the head SHA.

Suggested fix: surface a non-Success/distinct status from init_logging/kernel_init_logging so the caller can log the failure or fall back deliberately.


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread tests/c/session_smoke.c
bool valid = true;
KernelStatusCode rc = kernel_session_is_valid(NULL, &valid);
CHECK(rc == KernelStatusCode_InvalidArgument, "is_valid(NULL session) → InvalidArgument");
/* A non-null-but-bogus session pointer is UB per the contract, so we only

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The test calls kernel_init_logging twice and asserts both return Success — but the function returns Success unconditionally on every path, so the assertion is true by construction and cannot distinguish idempotent from broken. The documented "first call wins" behavior and the non-UTF-8-level branch are never observed. Add a real idempotency test in logging.rs's #[cfg(test)] module (init with file A, re-init with file B, assert B stays empty).


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

Comment thread tests/c/session_smoke.c
KernelStatusCode rc = kernel_session_config_set_auth_u2m(config, NULL, 0, NULL);
CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (all defaults) succeeds");
rc = kernel_session_config_set_auth_u2m(config, "my-client", 8020, "all-apis,offline_access");
CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (explicit) succeeds");

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The header contract is append-with-order-preserved (a Vec), deliberately unlike set_session_conf's overwrite (HashMap). The test sets exactly one header, so a refactor to a dedup'ing HashMap would silently drop repeated headers and still pass. Add a test pushing ("X-A","1"),("X-B","2"),("X-A","3") and asserting the projected HttpConfig.custom_headers equals that exact ordered list.


Posted by code-review-squad · /full-review · feedback: #code-review-squad-feedback

@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Code Review Squad — Review

Score: 31/100 — CRITICAL RISK

Four thin C ABI wire-throughs, but two don't work as advertised. kernel_init_logging is a silent no-op: the EnvFilter targets databricks_sql_kernel while every kernel event is emitted with target databricks::sql::kernel (per klog.rs), so no kernel log ever passes the filter. kernel_session_is_valid can only ever return true over the C ABI (the only path that sets closed also frees the handle). New behavior (scope-split, header projection, is_valid) has no unit coverage — the C smoke tests touch only setters and null guards. 6/6 reviewers delivered; security clean.


Could not post inline comments for: F1, F5, F9, F10 — see body below.

Critical & High Findings

F1 — Critical — src/logging.rs:L86

init_logging builds EnvFilter::new(format!("databricks_sql_kernel={}", ...)) (and the fallback at line 90), but every kernel log macro emits with target: KERNEL_LOG_TARGET = "databricks::sql::kernel" (klog.rs:59). EnvFilter matches directives against the target by ::-delimited segment prefix, and the single token databricks_sql_kernel is not a prefix of databricks::sql::kernel (which splits into databricks, sql, kernel). So zero kernel events pass the filter, regardless of the configured level.

This is the headline of the PR — routing the kernel's logs into the ODBC/host log file — and it produces an empty log for events. A partner debugging an auth/TLS/retry failure with LogLevel=DEBUG gets nothing.

Verified against src/logging.rs and src/klog.rs at the head SHA, plus the documented behavior of EnvFilter::new on tracing-subscriber 0.3.23 (it lossily ignores invalid directives / defaults to ERROR — it does not panic, so a bad level is not a crash, but the target is simply never matched).

  • Suggested fix: build the filter from the shared constant — EnvFilter::new(format!("{}={}", crate::klog::KERNEL_LOG_TARGET, level.to_lowercase())) and the fallback "{}=warn". Add a test that installs the subscriber, emits a klog::debug!, and asserts the line reaches the writer.

Medium Findings

F5 — Medium — src/logging.rs:L100

init_logging runs inside LOGGING_INITIALIZED.get_or_init(...). On a file-open error the closure eprintln!s and returns (lines 100-106); when the first level is OFF it returns early too (lines 79-83). In both cases get_or_init still stores (), marking logging permanently initialized with no subscriber installed. Per the documented "first call wins," every later kernel_init_logging — even with a valid path — is a permanent no-op for the process.

Independently flagged by three reviewers. A host that opens a first connection with an unwritable LogFile (or LogLevel=OFF) locks out all later logging. Verified against src/logging.rs at the head SHA.

  • Suggested fix: only commit the OnceLock on a successful try_init(), or fall back to stderr within the same call so logging still works.

Low Findings

Low findings (2) — click to expand

F9 — Low — src/c_abi/session.rs:L17

The module doc (lines 17-21) still states "Auth in the v0 C ABI is PAT + OAuth M2M only; OAuth U2M ... not yet exposed over the C ABI in v0" — directly beneath the new kernel_session_config_set_auth_u2m in the same file. The header was updated correctly; the module doc is now stale and misleading. Verified at the head SHA.

F10 — Low — src/c_abi/session.rs:L572

When no auth is set, the InvalidArgument message reads "session config requires auth (set_auth_pat or set_auth_m2m)" — but set_auth_u2m is now equally valid. The text is surfaced verbatim through kernel_get_last_error, so a partner debugging a U2M config gets a misleading hint. Verified at the head SHA. Fix: "...requires auth (set_auth_pat, set_auth_m2m, or set_auth_u2m)".

…pen, add tests

Addresses the self-review (Code Review Squad) findings on this PR.

[F1 Critical] Logging filter never matched. init_logging built the
EnvFilter as `databricks_sql_kernel=<level>`, but every kernel log macro
emits with target `databricks::sql::kernel` (klog::KERNEL_LOG_TARGET).
EnvFilter matches by `::`-delimited prefix, so the underscore token
matched nothing and ZERO kernel events passed — the feature was a silent
no-op. Now build the directive from KERNEL_LOG_TARGET.

[F5] First-call-wins locked out logging on a bad first config. A
file-open failure (or level=OFF) committed the OnceLock with no subscriber
installed, permanently disabling logging. Now on file-open failure we fall
back to stderr within the same call (so logging still works), and
init_logging returns a bool; kernel_init_logging maps false → Internal
(with a stored error) so a host that can't see stderr learns the requested
file wasn't honoured.

[is_valid → is_open] Renamed kernel_session_is_valid → kernel_session_is_open
(and Session::is_valid → is_open). Over the C ABI the only path that sets
`closed` also frees the handle, so a legal probe of a live handle always
saw not-closed → the old name over-promised "validity". The honest
contract: a LOCAL not-closed check that does not detect a server
idle-timeout; the header tells a SQL_ATTR_CONNECTION_DEAD consumer to read
true as "not known-dead".

[F9/F10] Updated the stale module doc (U2M is now exposed) and the
no-auth error message (now lists set_auth_u2m).

Tests: extracted parse_scopes (unit-tested: "a, ,b," → [a,b], blanks →
None); custom-header ordered/duplicate accumulation; is_open==true on a
freshly-opened session (wiremock); init_logging return signal +
idempotency; a pin that the filter target is `::`-delimited.

cargo fmt / clippy --all-targets clean; 677 lib tests + C smoke + wiremock
pass.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Addressed the self-review findings in 4aeccce:

  • [F1 Critical] logging filter never matched — the EnvFilter used databricks_sql_kernel= but kernel events emit with target databricks::sql::kernel (KERNEL_LOG_TARGET); EnvFilter matches by ::-delimited prefix, so the underscore token dropped every event. Now built from KERNEL_LOG_TARGET. Added a test pinning the target is ::-delimited.
  • [F5] first-call-wins lockout — a file-open failure (or OFF) used to commit the OnceLock with no subscriber. Now on file-open failure we fall back to stderr within the same call, and init_logging returns a bool → kernel_init_logging maps false → Internal (with a stored error) so a host that can't see stderr learns the file wasn't honoured.
  • is_valid → is_open — renamed (and Session::is_valid→is_open). Over the C ABI a live handle always reads not-closed, so the old name over-promised "validity"; the honest contract is a local not-closed check that does not detect server idle-timeout (header tells a CONNECTION_DEAD consumer to read true as "not known-dead").
  • [F9/F10] stale module doc (U2M now exposed) + no-auth message (now lists set_auth_u2m).
  • Test gaps — extracted parse_scopes (unit-tested "a, ,b,"→[a,b]); custom-header ordered/duplicate accumulation test; is_open==true on a fresh session (wiremock); init_logging return + idempotency.

cargo fmt/clippy --all-targets clean; 677 lib tests + C smoke + wiremock pass.

@gopalldb

gopalldb commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

⚠️ [MAJOR] · bug · tests/v0_c_abi_session_close_wiremock.rs:99

is_open false/closed path is untested; comments falsely claim coverage

Closed-session path of is_open has zero test coverage while comments claim it is covered. The only assertion on the new Session::is_open / kernel_session_is_open (added this PR) is assert!(is_open, ...) on a freshly-opened session at tests/v0_c_abi_session_close_wiremock.rs:99. A repo-wide search confirms no test builds a session, closes it, and asserts is_open() (or the C wrapper) reports false: the mod tests in src/session.rs (lines 914-1010) covers only retry/proxy/timeout. Yet the comment at wiremock.rs:94-97 says the false case is "covered by the crate-internal Session::is_open path" and session_smoke.c:202-203 says "The true→false behavior is covered by a Rust unit test" — no such test exists. Consequently an inverted atomic load or a hardcoded true return would pass the entire suite undetected, and the misleading comments would lead a maintainer to believe the branch is guarded. This matters because hosts back SQL_ATTR_CONNECTION_DEAD on this value.


💡 [MINOR] · bug · src/c_abi/session.rs:351

Non-UTF-8 log file_path silently dropped, returning Success instead of the documented Internal error

Non-UTF-8 file_path is silently swallowed, violating the documented error contract. In kernel_init_logging (src/c_abi/session.rs:352) the file path is parsed with optional_str(file_path, "log file path").ok().flatten(). optional_str returns Err(invalid_argument("... is not valid UTF-8")) for a non-UTF-8 C string (session.rs:389-397), but .ok().flatten() collapses that Err to None. The function then initializes stderr logging and returns KernelStatusCode::Success with no stored last-error. This contradicts the header (databricks_kernel.h:250-253) and the Rust docstring (session.rs:335-339), which promise Internal plus a stored last-error when the requested file_path cannot be honoured — so a GUI/BI host that cannot observe stderr is told logging is flowing to its file when the path was actually dropped.


💡 [MINOR] · bug · src/logging.rs:125

kernel_init_logging return value reflects the first call, not the current call's file outcome

Stale per-call return from OnceLock-cached logging init. init_logging (src/logging.rs:88) computes file_requested_ok inside a get_or_init closure that runs only on the first invocation (line 89); the stored bool is dereferenced on every later call. So a subsequent kernel_init_logging call whose file_path genuinely fails to open still returns the first call's true → KernelStatusCode::Success, and conversely a later call with a valid file returns a cached false → Internal even though a stderr subscriber is installed and logging works. The C header (include/databricks_kernel.h:251-253) documents Internal as "the requested file_path could not be opened", which is untrue for any caller after the first. A host that opens many connections and calls this each time cannot rely on the return code to describe its own file argument.


💡 [MINOR] · bug · src/logging.rs:137

try_init failure swallowed — kernel_init_logging reports Success when no subscriber was installed

Swallowed subscriber-install failure misreported as Success. In init_logging (src/logging.rs:137-138 / 148-149) the try_init() result is discarded with .ok(). tracing_subscriber::try_init returns Err when a global default subscriber has already been installed by another component in the process. Because the returned file_requested_ok (line 125) is computed only from whether the log file opened — never from try_init's result — init_logging returns true and kernel_init_logging (src/c_abi/session.rs:353-355) returns KernelStatusCode::Success even though no kernel subscriber was installed and no kernel logs will flow. A host relying on the Success code to confirm its logs are wired up is silently misled.

…ging return contract

Addresses gopalldb's review on #162.

[MAJOR] is_open false path untested; comments falsely claimed coverage.
The only assertion was is_open==true on a fresh session; the true→false
branch had no test, yet comments claimed a Rust unit test covered it (none
existed). An inverted/hardcoded-true is_open would have passed. Added an
in-crate wiremock test
(session::is_open_tests::is_open_flips_true_to_false_on_delete) that opens
a session, asserts is_open()==true, calls initiate_delete(), asserts
false — the false path is only reachable in-crate (the C ABI frees the
handle on close). Corrected the misleading comments in the wiremock test
and session_smoke.c to point at it.

[MINOR] Non-UTF-8 log file_path was swallowed to Success. kernel_init_logging
used optional_str(file_path).ok().flatten(), collapsing the UTF-8 error to
None and returning Success while dropping the path. Now a non-UTF-8
file_path returns InvalidArgument (with a stored error); level stays
best-effort.

[MINOR] try_init failure was swallowed. init_logging discarded try_init()
with .ok(), so if a global subscriber was already installed (no kernel
subscriber installed) it still returned true → Success. try_init's result
now folds into the returned bool.

[MINOR] Return-value semantics clarified. The bool is computed in the
get_or_init closure, so it necessarily reflects the FIRST (installing)
call — a later call's level/file have no effect. Docs (header + Rust) now
state this explicitly rather than implying the return describes the current
call's file argument.

cargo fmt / clippy --all-targets clean; 678 lib tests + C smoke + wiremock
pass.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks @gopalldb — all four addressed in 4f95cb1:

[MAJOR] is_open false path untested + false coverage claims. You're right, no test existed and the comments lied. Added an in-crate wiremock test session::is_open_tests::is_open_flips_true_to_false_on_delete that opens a session, asserts is_open()==true, calls initiate_delete(), then asserts false. It has to be in-crate — the C ABI frees the handle on close, and is_open/initiate_delete are pub(crate). Fixed the misleading comments in the wiremock test and session_smoke.c to point at it.

[MINOR] non-UTF-8 file_path swallowed to Success. kernel_init_logging used optional_str(file_path).ok().flatten(), collapsing the UTF-8 error. A non-UTF-8 file_path now returns InvalidArgument (with a stored error); level stays best-effort.

[MINOR] try_init failure swallowed. init_logging discarded try_init() with .ok(), so an already-installed global subscriber still returned Success. try_init's result now folds into the returned bool (installed && file_requested_ok).

[MINOR] return reflects the first call, not the current one. Correct — the bool is computed inside get_or_init, so it necessarily describes the first (installing) call. Rather than change that (the subscriber genuinely installs once), the header + Rust docs now state explicitly that the result reflects the first call and a later call's level/file have no effect and aren't described by its return.

cargo fmt / clippy --all-targets clean; 678 lib tests + C smoke + wiremock pass.

@vikrantpuppala
vikrantpuppala added this pull request to the merge queue Jul 10, 2026
Merged via the queue into main with commit c5b20be Jul 10, 2026
15 of 16 checks passed
mani-mathur-arch added a commit that referenced this pull request Jul 10, 2026
Pull in #162 (C ABI: OAuth U2M, custom headers, session validity, logging
init). No conflicts; both PRs append to include/databricks_kernel.h in
distinct sections and touch disjoint source (this branch: statement.rs
canceller; #162: session.rs / logging.rs / c_abi/session.rs). Build,
clippy -D warnings, canceller + session-close wiremock, and full lib
tests all green on the merged tree.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>

This branch was previously deployed

1 inactive deployment
azure-prod — 4f95cb15 Deployed Jul 9, 2026 by vikrantpuppala via v0 E2E surface #197
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