Skip to content

feat(c-abi): mTLS client-certificate setter + ABI-version handshake - #169

Closed
mani-mathur-arch wants to merge 16 commits into
mainfrom
mani/c-abi-log-callback
Closed

mani-mathur-arch wants to merge 16 commits into
mainfrom
mani/c-abi-log-callback

Conversation

@mani-mathur-arch

@mani-mathur-arch mani-mathur-arch commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

What

Two purely-additive C-ABI symbols so C-ABI hosts (ODBC / Go) reach kernel
capabilities the direct-Rust and pyo3/napi consumers already have. No existing
symbol's layout or meaning changes.

mTLS client certificate

  • kernel_session_config_set_tls_client_certificate() — exposes the crate's
    existing mTLS client cert/key (TlsConfig::client_cert_pem /
    client_key_pem) as a single paired setter. Both halves are required
    together, so cert-without-key is unrepresentable at the ABI; the private key
    is never logged (TlsConfig Debug redacts it). Already implemented and
    wired in the crate (build_mtls_identity → builder.identity(...), both the
    tls-native and tls-rustls backends); Python (pyo3 tls_client_cert),
    Node (napi client_cert_pem), and JDBC (SSLKeyStore) already expose the
    equivalent — this brings the C ABI to parity.

ABI-version handshake

  • kernel_abi_version() + the DATABRICKS_KERNEL_ABI_VERSION header macro. A
    consumer that links a prebuilt library compares the two once at load time and
    refuses to run on a mismatch, guarding against stale-header / .a layout
    drift. Coarse pre-1.0 handshake — bumped in lockstep on any layout/meaning
    change, not per additive symbol; the Rust↔header lockstep assertion in the C
    smoke test gates any mismatch.

Scope note

This PR was scoped down during review (thanks @vikrantpuppala). The earlier
revision batched several more C-ABI symbols; all were purely additive with no
merged consumer on any driver branch, so they were removed and deferred rather
than shipped ahead of need:

  • Cooperative cancel token + *_cancellable entry points (open / next_batch
    / close_blocking) — Gap 6/7 (PECOBLR-3645 / PECOBLR-3646). Re-add when the Go
    driver actually honors ctx deadlines on connect/fetch; the CloudFetch
    download already has its own ~60s read-timeout, so the gap is a
    deadline-shorter-than-60s nicety, not an unbounded hang.
  • kernel_session_close_blocking — no Go consumer; the driver stays
    fire-and-forget.
  • kernel_session_config_set_cloudfetch_enabled — a real warehouse gates
    can_cloud_download (CONFIG_NOT_AVAILABLE / 42K0I), so there's no working
    e2e path until SEA inline-Arrow (go/inline-arrow-sea) ships server-side.
  • kernel_set_log_callback / kernel_logging_stats — kernel_init_logging
    (stderr, or a host log file) already covers C-ABI hosts; the reverse-call
    sink is an ergonomics upgrade (unified/structured log stream), not required.

How we know it works / safety

  • Additive by construction: both symbols are new surface; the default path
    and every existing symbol are byte-for-byte unchanged.
  • mTLS is live, not plumbed-but-inert: verified end-to-end against an
    openssl s_server -Verify 1 (client-cert-required) — with the identity the
    handshake completes and the server logs verify … CN=test-client; without it
    the same server rejects with tlsv13 alert certificate required. (No live
    e2e against a warehouse: no Databricks endpoint demands a client cert, so the
    handshake can only be exercised against a local client-cert-requiring server.)
  • The private key never hits logs (TlsConfig Debug redaction), and the
    paired setter makes cert-without-key unrepresentable.

Tests

make check (fmt + clippy + cargo test + C smoke) green.

  • Unit — session.rs: mTLS store/reject + forwarding through
    build_session; abi-version constant matches.
  • C smoke — tests/c/session_smoke.c: set_tls_client_certificate
    both-halves success + null-guards, and the kernel_abi_version() ↔
    DATABRICKS_KERNEL_ABI_VERSION lockstep assertion.

Closes PECOBLR-3654.

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

@mani-mathur-arch

mani-mathur-arch commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

One issue I noticed in the C ABI callback level resolution:

level_from_rust_log returns the first databricks* directive it sees, which does not fully match tracing_subscriber::EnvFilter precedence when RUST_LOG contains multiple matching directives. For example, RUST_LOG=databricks=warn,databricks::sql::kernel=debug would resolve the callback threshold to warn, while the kernel_init_logging path should honor the more specific databricks::sql::kernel=debug directive.

That breaks the documented contract that the callback path mirrors kernel_init_logging / EnvFilter precedence. I’d add coverage for broad + specific databricks* directives in both orders, and update the resolver to apply EnvFilter-equivalent specificity/order behavior rather than first-match-wins.

@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Good catch, fixed in cf2d533.

level_from_rust_log no longer takes the first databricks* directive it sees. It now resolves the level the way EnvFilter would:

  • Prefix-match gating: a target directive is only considered if its target is a prefix of a canonical kernel target root (databricks::sql::kernel / databricks_sql_kernel), via the new directive_targets_kernel helper — mirroring EnvFilter's event_target.starts_with(directive_target). This also drops non-matching databricks-prefixed siblings (databricksfoo=warn) and over-specific extensions that match no emitted event (databricks::sql::kernel::foo=trace), so they can't outrank a real databricks= directive or a bare global level.
  • Most-specific wins, order-independent: among matching directives the longest target wins regardless of order, with equal-length ties going last-writer-wins (EnvFilter's dedup behavior).

So RUST_LOG=databricks=warn,databricks::sql::kernel=debug now resolves to debug (and identically in the reverse order), matching the kernel_init_logging / EnvFilter path.

One documented approximation: since the callback resolves a single scalar for the whole bridge, a directive naming a sub-module deeper than a root (e.g. databricks_sql_kernel::session=trace) is treated as non-selecting; the dominant klog! target databricks::sql::kernel is resolved exactly.

Added coverage for broad + specific directives in both orders, the non-matching-sibling cases, and directive_targets_kernel prefix behavior.

@mani-mathur-arch

mani-mathur-arch commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

I re-reviewed the updated PR at cf2d533. The original broad-vs-specific RUST_LOG first-match issue looks fixed: the new resolver handles the databricks=warn,databricks::sql::kernel=debug case in both orders and ignores non-matching databricks* siblings.

I found a few remaining issues worth addressing:

  1. High: the Rust end-to-end delivery test can pass without proving delivery.
    In tests/v0_c_abi_log_callback.rs, the test accepts KernelStatusCode::Internal and returns early. That means a regression where kernel_set_log_callback never succeeds in the dedicated integration-test binary would still leave CI green. Since this is the only Rust success-path callback delivery test, I’d make this test require KernelStatusCode::Success and fail on Internal; keep the mutual-exclusion Internal case covered by the C smoke test or a separate isolated test.

  2. Medium: the end-to-end test does not prove the level argument filters anything.
    The test installs with "trace" and emits a WARN event, which would still pass if the level parameter were ignored and the default WARN threshold stayed active. I’d add a restrictive-level test, e.g. install at ERROR, emit a kernel WARN/INFO event and assert it is not delivered, then separately verify permissive delivery.

  3. Medium: the callback filter enables spans that the layer never consumes.
    KernelFilter admits databricks* callsites by target/level, including spans, but KernelLogLayer only implements on_event. So callback logging at INFO/DEBUG/TRACE can pay span creation/enter/exit overhead in hot paths such as instrumented next_batch() without producing callback output. If this bridge is event-only, consider gating on event metadata in callsite_enabled/enabled so spans cache off unless the layer starts consuming span data.

@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Thanks for the second pass — all three addressed in 54b7a87.

1. (High) E2E delivery test could pass without proving delivery.
tests/v0_c_abi_log_callback.rs now requires KernelStatusCode::Success on install instead of accepting Internal and returning early. This is the sole success-path binary (nothing else installs a global subscriber), so a regression where kernel_set_log_callback never installs now fails CI.

2. (Medium) Test didn't prove the level argument filters.
Replaced the trace+WARN shape (which cleared the default WARN anyway) with gating in both directions:

  • Install at ERROR, emit a WARN event and assert it is not delivered. The negative assertion is deterministic, not a sleep-and-hope: the single FIFO drain thread also delivers a subsequent ERROR barrier, and once the barrier lands the earlier WARN would already be present if it had passed.
  • Re-register at trace, emit a DEBUG event (below the default WARN) and assert it is delivered — proving the level also loosens.

3. (Medium) Filter enabled spans the layer never consumes.
Made KernelFilter event-only: callsite_interest_for now takes is_event and returns Interest::never() for all span callsites (even kernel targets), and enabled gates on meta.is_event(). So the kernel's own databricks* spans (Session's info_span!, the #[instrument] on next_batch) become no-op disabled spans and pay no create/enter/exit in the registry at INFO/DEBUG/TRACE for output the event-only layer never produces.

To be safe about the obvious follow-up worry — does disabling those spans suppress events emitted inside them? — I added a guard test that enters a (now-disabled) kernel span and emits a kernel event within it, asserting the callback still receives it. tracing evaluates span and event callsites independently, so in-span events are unaffected; the test locks that in. Also added a unit test that span callsites cache off.

make check green.

@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Thanks — all four confirmed valid and fixed in 99952bb.

1. (High) Install ordering leaves the subscriber occupied on spawn failure.
Reordered INSTALL.call_once: the drain thread is now spawned before set_global_default. A spawn failure (EAGAIN/ENOMEM) now returns Internal without claiming the global subscriber, so the host can still fall back to kernel_init_logging. If the subscriber race is lost instead, the sender is dropped so the freshly-spawned drain thread's recv() errors and it exits cleanly (no idle-thread leak); SENDER stays unset so on_event short-circuits.

2. (Medium) Re-registration undone by an old in-flight callback.
Added a monotonic sink generation (Sink::gen, bumped under the SINK lock on every registration). drain_loop captures (cb, ctx, gen), and the new poison_sink_if_current(gen) only sets SINK_POISONED if that generation is still installed — compared under the same lock the setter holds while it swaps the sink and clears the poison. So an old callback unwinding after the host registered a replacement can no longer kill the new sink.

3. (Medium) dropped didn't count the record whose callback unwinds.
The failing invoke_callback now increments DROPPED for the undelivered record (both the primary and the drop-notice paths) before poisoning, so kernel_logging_stats reflects the first lost record instead of only later ones.

4. (Medium) RUST_LOG submodule directives ignored despite being forwarded.
directive_targets_kernel now accepts extensions of the module-path root (databricks_sql_kernel::session) — those events are forwarded by is_kernel_target, so a host targeting a submodule raises the threshold instead of silently staying at the default WARN. Extensions of the fixed-depth klog target (databricks::sql::kernel::foo, which the kernel never emits deeper than) and unrelated siblings (databricksfoo) remain rejected.

Tests: unit test for the generation guard; an end-to-end step asserting an unwinding callback is counted as a drop and poisons the sink (installed=false); and submodule-directive coverage in the resolver + directive_targets_kernel tests. make check green (708 lib + all integration/doc tests).

(FYI, I still can't run isaac review reliably in this sandbox for the delivery-path tests, but cargo test / clippy / fmt all pass locally.)

@mani-mathur-arch
mani-mathur-arch force-pushed the mani/c-abi-tier2-features branch from b79e1ec to 9ada264 Compare July 19, 2026 08:58
@mani-mathur-arch
mani-mathur-arch force-pushed the mani/c-abi-log-callback branch from fef8758 to 3763576 Compare July 19, 2026 08:59
Add kernel_cancel_token_t plus cancellable variants of the connect and
result-fetch entry points, so a C-ABI host can interrupt an otherwise
uninterruptible blocking call by a caller deadline:

  - kernel_session_open_cancellable
  - kernel_result_stream_next_batch_cancellable

block_on_ffi_cancellable races the operation future against the token via a
biased tokio::select!; a fire drops the in-flight future, aborting the
underlying reqwest request (the crate's documented cancellation model), and
yields a typed Cancelled. A NULL token routes to the identical plain-path
behavior, so the default path and existing symbols are byte-for-byte
unchanged. Token firing is purely local (no RPC), safe to call from another
thread — modeled on the existing statement canceller. tokio_util's
CancellationToken is already a crate dependency, so no new cargo-deny entry.

Additive only — no existing symbol's layout or meaning changes, ABI unchanged.

Tests: cancel unit tests (incl. the is_cancelled accessor), wiremock
integration tests proving a mid-connect cancel returns Cancelled in under 5s
against a 10s stalled server (plus NULL-token parity and pre-fired
short-circuit), and C-smoke lifecycle + pre-fired short-circuit. make check
green.

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

Add four additive C-ABI symbols requested by the C-ABI host drivers, each
purely additive (no existing symbol's layout or meaning changes):

  - kernel_abi_version() + the DATABRICKS_KERNEL_ABI_VERSION header macro:
    a host that links a prebuilt library compares the two once at load time
    and refuses to run on a mismatch, guarding stale-header/.a layout drift.
  - kernel_session_close_blocking(): close and block until the server-side
    DeleteSession completes (reusing Session::close().await), the parity path
    for a host that wants close to behave like the synchronous DeleteSession
    RPC the direct-Rust / pyo3 / napi consumers get. Consumes the handle like
    the fire-and-forget kernel_session_close.
  - kernel_session_config_set_tls_client_certificate(): expose the crate's
    existing mTLS client cert/key (TlsConfig::client_cert_pem/client_key_pem)
    as a single paired setter. Both halves required together, so
    cert-without-key is unrepresentable at the ABI; the private key is never
    logged (TlsConfig Debug redacts it).
  - kernel_session_config_set_cloudfetch_enabled(): toggle CloudFetch (maps to
    ResultConfig::cloudfetch_enabled); false forces the inline-Arrow path for
    all result sizes. Unset keeps the kernel default (on).

Tests: unit (abi-version, mTLS store/reject, cloudfetch toggle), wiremock
(blocking close observes DELETE synchronously; cloudfetch-disabled sends
can_cloud_download=false), C-smoke lifecycle for each. make check green.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
@mani-mathur-arch
mani-mathur-arch force-pushed the mani/c-abi-tier2-features branch from 9ada264 to 0669be8 Compare July 19, 2026 09:08
@mani-mathur-arch
mani-mathur-arch force-pushed the mani/c-abi-log-callback branch from 3763576 to 92f0415 Compare July 19, 2026 09:08
@mani-mathur-arch
mani-mathur-arch marked this pull request as ready for review July 19, 2026 09:19
@mani-mathur-arch
mani-mathur-arch changed the base branch from mani/c-abi-tier2-features to main July 19, 2026 09:42
Close the Rust↔header ABI-version lockstep loop by comparing
kernel_abi_version() to DATABRICKS_KERNEL_ABI_VERSION in the C smoke
test, catching future header/library drift.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Add kernel_set_log_callback(cb, ctx, level) + the kernel_log_callback typedef so
a C-ABI host (ODBC / Go) that can't install a Rust tracing subscriber still
receives the kernel's databricks*-targeted log events, routed into the host's own
logger instead of only reaching stderr via kernel_init_logging.

A process-global KernelLogLayer captures kernel events, filters foreign targets
(hyper/rustls cache off; kernel callsites re-evaluate for the dynamic level),
formats message+fields, and enqueues onto a bounded channel (drop-on-full — logs
are advisory and never back-pressure a kernel hot path). A dedicated drain thread
delivers each record to the callback with borrowed C strings, off the tokio
workers so a slow host callback can't stall query execution.

The level parameter mirrors kernel_init_logging's precedence — an explicit
recognised level wins, else RUST_LOG, else the warn default — so a host that maps
its own logger level (Go's DATABRICKS_LOG_LEVEL) filters on that one knob rather
than only RUST_LOG.

Robustness: the callback pointer uses the C-unwind ABI and the drain thread wraps
each invocation in catch_unwind, so a panicking host callback poisons the sink
(delivery stops) instead of aborting the process at the boundary. Drop-on-full
loss is observable — a DROPPED counter plus a synthetic 'N dropped' line emitted
through the callback on recovery, and a kernel_logging_stats(installed, dropped)
accessor (parity with the napi bridge). Install attempts set_global_default first
and only spawns the drain thread if it wins the one global subscriber, so losing
the mutual-exclusion race to kernel_init_logging never leaks an idle thread; a
drain-thread spawn failure is reported distinctly from the benign already-installed
case.

Mutually exclusive with kernel_init_logging (one process-global subscriber,
first-writer-wins; the other returns Internal); a NULL callback is rejected with
InvalidArgument.

Tests: logging unit tests (severity ordering, level gating, RUST_LOG/explicit
precedence, target-prefix drift guard, field rendering, catch_unwind containment);
an end-to-end integration binary (tests/v0_c_abi_log_callback.rs) that emits a real
tracing event and asserts the callback received it with message + fields, the ctx
pointer round-trips verbatim, and stats report installed/zero-dropped — kept a
separate binary so its process-global subscriber doesn't perturb the klog unit
tests; and C smoke cases (NULL-cb rejection, strict Internal mutual-exclusion
assert, NULL-safe stats).

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
The callback path's `level_from_rust_log` took the first `databricks*`
directive it saw, diverging from `kernel_init_logging`'s `EnvFilter` when
`RUST_LOG` carried multiple matching directives (e.g.
`databricks=warn,databricks::sql::kernel=debug` resolved to `warn`
instead of the more-specific `debug`).

Resolve the level as `EnvFilter` would: only consider directives whose
target is a prefix of a canonical kernel target root (new
`directive_targets_kernel`), then let the most specific (longest) match
win, order-independently. This rejects non-matching `databricks`-prefixed
siblings (`databricksfoo=warn`, `databricks::sql::kernel::foo=trace`) that
match no kernel event, so they no longer outrank a real `databricks=`
directive or a bare global level.

Adds coverage for broad + specific directives in both orders and the
non-matching-sibling cases.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Addresses second-pass review on the reverse-call log bridge:

- The end-to-end delivery test accepted `Internal` and returned early, so
  a regression where `kernel_set_log_callback` never installs would stay
  green. It's the sole success-path binary (nothing else installs a
  global subscriber), so require `Success`.

- The test installed at `trace` and emitted `WARN`, which clears the
  default `WARN` threshold too — so it passed even if `level` were
  ignored. Prove gating in both directions: install at `ERROR` and assert
  a `WARN` event is filtered (using the FIFO drain thread + an `ERROR`
  barrier for a deterministic negative assertion), then re-register at
  `trace` and assert a `DEBUG` event (below the default) is delivered.

- Make `KernelFilter` event-only: span callsites now cache off even on
  kernel targets (`callsite_interest_for` takes `is_event`; `enabled`
  gates on `meta.is_event()`). The kernel's own `databricks*` spans
  (`Session`'s `info_span!`, the `#[instrument]` on `next_batch`) no
  longer pay span create/enter/exit in the registry for output the
  event-only layer never produces. Adds a guard test proving an event
  emitted inside a now-disabled kernel span is still delivered (span and
  event callsites are evaluated independently), plus a unit test that
  span callsites cache off.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
…_LOG submodule matching

Addresses the third-pass review on the reverse-call log bridge:

- Install ordering (High): spawn the drain thread BEFORE claiming the
  global subscriber. Previously `set_global_default` ran first, so if the
  drain-thread spawn then failed the process-global subscriber slot was
  left occupied by a `SENDER`-less layer — every kernel event
  short-circuited and the host could never fall back to
  `kernel_init_logging`. Now a spawn failure bails out before touching the
  subscriber (slot stays free), and a lost subscriber race drops the
  sender so the freshly-spawned drain thread exits cleanly.

- Re-registration race (Medium): add a monotonic sink generation. The
  drain thread captures `(cb, ctx, gen)` and, via `poison_sink_if_current`,
  only poisons on an unwind if that generation is still installed — so an
  old, slow callback that unwinds after the host registered a replacement
  can no longer kill the new sink.

- Drop undercount (Medium): count the record whose callback unwinds. Only
  later records were counted while poisoned, so the first lost record was
  invisible to `kernel_logging_stats`; both the primary and the
  drop-notice failure paths now increment `DROPPED`.

- RUST_LOG submodule directives (Medium): `directive_targets_kernel` now
  accepts extensions of the module-path root (`databricks_sql_kernel::session`),
  which the bridge forwards via `is_kernel_target`, instead of silently
  keeping the default WARN threshold. Extensions of the fixed-depth klog
  target (`databricks::sql::kernel::foo`) and unrelated siblings are still
  rejected.

Adds a unit test for the generation guard and an end-to-end step asserting
an unwinding callback is counted as a drop and poisons the sink, plus
submodule-directive coverage.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
… callback

Address remaining log-callback review findings:

- Per-target RUST_LOG filtering: replace the single-scalar level with
  per-target EnvFilter precedence (most-specific prefix wins) evaluated
  per event. A submodule directive
  (databricks_sql_kernel::reader::inline=trace) no longer widens the
  canonical klog! target (databricks::sql::kernel=error), which
  EnvFilter keeps at its own directive's level. An explicit one-knob
  level still applies uniformly (no per-target directives) and stays on
  the lock-free fast path.
- Retryable install: replace the install `Once` (consumed on first
  attempt) with a serialized, retryable guard so a transient drain-thread
  spawn failure (EAGAIN/ENOMEM) no longer permanently disables callback
  logging. set_global_default is still attempted at most once.
- kernel_logging_stats now clears the thread-local last-error on entry,
  matching every other C-ABI entry point, so a poll between a failed call
  and reading the error can't observe a stale error.
- on_event short-circuits before field formatting / enqueue when the sink
  is poisoned, still counting the loss so kernel_logging_stats stays
  accurate (each dropped record counted exactly once).
- Tests: per-target precedence + parse_rust_log unit tests, and an
  end-to-end Step 5 that re-registers a good callback after poison and
  asserts installed flips back to true and delivery resumes.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
…stall window

Address the follow-up log-callback review findings:

- Target-only RUST_LOG directives: parse_rust_log now reads a bare kernel
  target (`databricks::sql::kernel`, no `=level`) as that target at TRACE,
  mirroring EnvFilter — previously it was ignored, leaving the callback at
  WARN where kernel_init_logging emits debug/trace.
- Silent-drop window on install: the delivery channel sender now lives in
  the KernelLogLayer instance instead of a separately-published global, so
  set_global_default publishes the subscriber and its sender atomically.
  A concurrent kernel log can no longer reach on_event after the subscriber
  is visible but before the sender exists (which dropped it uncounted).
- Runtime target routing: is_kernel_target now matches on `::` segment
  boundaries (exact roots + submodules) instead of a raw
  starts_with("databricks"), so unrelated databricks-prefixed host/library
  targets (databricksfoo, another databricks_* crate) aren't routed into
  the kernel callback.
- Tests: target-only directive parsing, is_kernel_target segment-boundary
  matching, and a C-ABI test that seeds a stale last-error and asserts
  kernel_logging_stats clears it on entry.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
…ive matching and throttle drop notices

The log-callback bridge added exported symbols (kernel_set_log_callback,
kernel_logging_stats, kernel_log_callback) without bumping the C-ABI
version, so a consumer built against the new header could link an older
library missing them and fail only at load/run time. Bump
KERNEL_ABI_VERSION and DATABRICKS_KERNEL_ABI_VERSION to 2 in lockstep,
widen the bump policy to cover symbol-set changes, and add the
version-lockstep assertion to the C smoke tests (the Rust doc claimed it
existed but no C check did).

Also:
- directive_targets_kernel now uses the same segment-boundary helper as
  is_kernel_target, so a module-root sibling (databricks_sql_kernel_ext)
  no longer raw-prefix-matches and needlessly raises MAX_LEVEL / takes the
  directive scan path.
- Throttle the drain thread's synthetic "dropped N" notice to at most one
  per second, so sustained channel overflow can't double callback
  invocations and amplify the backlog; kernel_logging_stats still carries
  the exact cumulative count.
- Add tests/c/log_callback_smoke.c: a standalone C binary that installs a
  callback with no prior init_logging, so it exercises the success path
  (install -> Success, logging_stats installed=true) and catches
  header/cdylib callback ABI drift, complementing session_smoke.c's
  mutual-exclusion-only coverage.

Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Collapse the per-target RUST_LOG EnvFilter machinery to a single resolved
level and drop the synthetic drop-notice, keeping the reverse-call bridge's
behavior (explicit level > RUST_LOG > warn default; drop count still surfaced
via kernel_logging_stats) while removing ~240 lines of accreted complexity:

- parse_rust_log now returns one Option<u8> (most-verbose kernel-applicable
  level); should_emit reads a single atomic LEVEL with no per-event lock. A
  mixed RUST_LOG resolves to a superset threshold; a host wanting exact
  per-target control uses kernel_init_logging. Removes DIRECTIVES/RwLock,
  HAS_DIRECTIVES, MAX_LEVEL, threshold_for_target, resolve_threshold,
  ResolvedFilter.
- drain_loop no longer emits a throttled "N dropped" record through the
  callback; the exact cumulative count stays available via kernel_logging_stats.

Also revert the per-PR ABI-version bump (KERNEL_ABI_VERSION and
DATABRICKS_KERNEL_ABI_VERSION back to 1) with a coarse pre-1.0 handshake
policy, keeping the C-smoke lockstep assertion; and trim verbose doc/comment
blocks across logging.rs and the header. Sink generations and the retryable
install are kept. make check green.

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
@mani-mathur-arch
mani-mathur-arch force-pushed the mani/c-abi-log-callback branch from 92f0415 to f0465b1 Compare July 19, 2026 09:48
@mani-mathur-arch mani-mathur-arch changed the title feat(c-abi): reverse-call log callback for C-ABI consumers feat(c-abi): cancel token, ABI-version handshake, blocking close, mTLS + CloudFetch setters, log callback Jul 19, 2026
Comment thread include/databricks_kernel.h Resolved
Comment thread src/c_abi/session.rs Resolved
Comment thread src/c_abi/session.rs Resolved
Comment thread tests/v0_c_abi_cancel_token_wiremock.rs Resolved
@mani-mathur-arch

Copy link
Copy Markdown
Contributor Author

Thanks for the review — addressed the findings in f952044. Quick rundown:

  • F1 / F2 / F9 — docs. Cancel-token wording (stops the caller's wait, not the background download; real abort only on connect), close_blocking Success-means-attempted, and the RUST_LOG "collapsed, not per-target" line all corrected.
  • F10 — spawn failure now returns ResourceExhausted (retryable) vs terminal Internal, so the distinction is machine-readable.
  • F12 — added a KernelLogLevel header enum + pub Rust constants.
  • F8 — extracted a shared ffi_prepare_runtime() + added a reentrancy test for the cancellable path.
  • F4 / F5 / F6 — new tests: mid-flight fetch cancel returns Cancelled promptly, drop-on-full overflow is counted without blocking the emitter, and both mTLS halves are forwarded through build_session.
  • F3 / F7 — no change. close_blocking and the metadata entry points have no consumer today (the Go driver uses fire-and-forget close and no metadata path), so threading a cancel token through them now would be speculative; will add if a host adopts them.
  • F11 — left as-is. The bare install bodies are panic-free by construction (no reachable UB), and running bare matches the other sync setters rather than deviating from a convention; tracking the catch_unwind hardening separately.

make check green (fmt + clippy + Rust suite + C smoke).

…ument metadata exemption (F7)

Follow-up on the review's cancellation-surface findings.

F3: kernel_session_close_blocking had no cancel path, so a wedged/partitioned
CloseSession could pin the calling host thread up to the retry ceiling (~900s)
with no cooperative escape — the exact stall class the cancel token was
introduced to bound, and the third `_cancellable` twin the ctx-cancel plan
called for (open + next_batch already had theirs). It's also the symbol the Go
driver's CloseSession comment defers blocking-close adoption on.

- Refactor close_blocking into a shared session_close_blocking_inner taking
  Option<&CancellationToken>; add kernel_session_close_blocking_cancellable
  routed through the existing null-transparent block_on_ffi_cancellable.
- Session::close awaits delete_session inline, so a fired token drops the
  in-flight DeleteSession (a real abort) and the boxed session; SessionInner's
  Drop then fires a best-effort fire-and-forget delete. Documented: the handle
  is consumed on EVERY path including Cancelled.
- Wiremock tests: fire mid-close against a 30s-stalled DELETE returns Cancelled
  in <5s; a NULL token awaits the DELETE like the plain blocking close.

F7: document (in the cancel-token header comment) that the metadata entry
points have no `_cancellable` twin by design — no host consumer needs a caller
deadline yet, they stay bounded by transport timeouts, and twins can be added
the same additive way if a host adopts them. Also corrected the
close_blocking header doc to the F2 "Success = attempted, not confirmed" wording
(the Rust doc was already fixed; the header block had been missed).

make check green (fmt + clippy + Rust suite + C smoke).

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

Copy link
Copy Markdown
Contributor Author

Update on F3 and F7 (revisiting the earlier "no change" replies): decided to fix F3 rather than defer it — c19e5d1 adds kernel_session_close_blocking_cancellable, the third _cancellable twin the ctx-cancel plan called for and the symbol the Go driver defers blocking-close adoption on. It routes through the existing null-transparent block_on_ffi_cancellable; because Session::close awaits the DELETE inline, a fired token genuinely aborts the in-flight request (handle consumed on every path incl. Cancelled). Wiremock tests cover fire-mid-close (Cancelled <5s vs a 30s stall) and NULL-token parity.

For F7, closed the close-blocking half the same way and took the "document the exemption" option for metadata: the cancel-token header comment now states the kernel_metadata_* ops intentionally have no _cancellable twin (no host consumer yet; still bounded by transport timeouts; addable the same additive way later). Left metadata.rs untouched since it isn't otherwise in this PR.

make check green.

Comment thread include/databricks_kernel.h Outdated

typedef void (*kernel_log_callback)(void* ctx, int level, const char* target,
const char* message);
KernelStatusCode kernel_set_log_callback(kernel_log_callback cb, void* ctx,

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.

why are we doing callback?

@mani-mathur-arch mani-mathur-arch Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is added so that the logs flow to a unified stream with no interleaving of logs and consistent formatting. without this if we route both the go logs and the rust logs to the same file they might be interleaved and will not be of the zerolog json format. not a correctness fix, can drop it if not needed.

Comment thread include/databricks_kernel.h Outdated
* sizes (mirrors JDBC EnableQueryResultDownload=0). The kernel sets the
* `can_cloud_download` session conf internally — do NOT set that conf directly
* via set_session_conf (the server rejects it as not user-settable). */
KernelStatusCode kernel_session_config_set_cloudfetch_enabled(KernelSessionConfig* config,

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.

should not do this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

okay will drop it in the next batch of changes. I was not able to test it as no SEA server supported this config.

* across the tls-native and tls-rustls backends). Taking both at once makes
* cert-without-key unrepresentable. A null buffer or zero length for either
* half returns InvalidArgument. The private key is never rendered in logs. */
KernelStatusCode kernel_session_config_set_tls_client_certificate(KernelSessionConfig* config,

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.

did we add e2e tests for mtls?

@mani-mathur-arch mani-mathur-arch Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

e2e tests are not added as no warehouse accepts these. only unit tests are added

Comment thread include/databricks_kernel.h Outdated
* kernel_session_close (released on success and failure alike); the same
* "close the session LAST" teardown ordering applies.
*/
KernelStatusCode kernel_session_close_blocking(kernel_session_t* session);

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.

why is this needed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was added to allow the go closing to also be blocking similar to python and also honour the deadline on the close. Currently the go close fires the call and returns. Not a correctness bug and not yet wired in the go side so can be dropped.

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.

please remove - delete session should always be non blocking best effort

Comment thread include/databricks_kernel.h Outdated
* `cancel_token` is borrowed and safe to fire from another thread while this
* call is in flight (see kernel_session_open_cancellable).
*/
KernelStatusCode kernel_result_stream_next_batch_cancellable(

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.

why is this needed? anyway the cloud fetch download etc are async so they're not tied to next batch. i assume if you drop the result handler when you want to cancel - cloud fetch would be dropped as well

Comment thread src/c_abi/logging.rs Outdated

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.

other drivers dont do callback - why do we need to here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

other drivers (python and node) do not need this as they link the crate directly which go cannot do so this was thus added. Its not a correctness fix and can be dropped.

Comment thread src/c_abi/session.rs Outdated
/// `None` keeps the kernel default (CloudFetch on); `Some(false)`
/// forces the inline-Arrow result path (mirrors JDBC
/// `EnableQueryResultDownload=0`).
cloudfetch_enabled: Option<bool>,

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.

sea does not support inline arrow yet so we should not do this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

okay will drop this in the next change

Comment thread src/c_abi/session.rs
custom_ca_cert: tls.custom_ca_cert,
accept_self_signed: tls.accept_self_signed,
skip_hostname_verification: tls.skip_hostname_verification,
client_cert_pem: tls.client_cert_pem,

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.

does tlsconfig even use client_cert_pem? not sure if mtls is even implemented for us to be plumbing this through

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it is implemented but no warehouse requires a client cert so an e2e test is not feasible. Python and node driver already implement this so it is supported.

Scope this PR down to the two low-risk, parity/safety symbols and defer the
rest, per review (vikrantpuppala on #169): keep
kernel_session_config_set_tls_client_certificate (mTLS — already implemented
and wired in the crate; three sibling drivers already expose it) and
kernel_abi_version() + DATABRICKS_KERNEL_ABI_VERSION (drift handshake).

Remove — all purely additive, no merged consumer on any driver branch, so
nothing shipped depends on them:

- Cooperative cancel token + the *_cancellable entry points
  (kernel_cancel_token_new/_cancel/_is_cancelled/_free,
  kernel_session_open_cancellable, kernel_result_stream_next_batch_cancellable,
  kernel_session_close_blocking_cancellable) and block_on_ffi_cancellable.
  Gap 6/7 (PECOBLR-3645/3646) stay open; re-add when the Go driver actually
  honors ctx deadlines on connect/fetch.
- kernel_session_close_blocking — no Go consumer; Go stays fire-and-forget.
- kernel_session_config_set_cloudfetch_enabled — the server gates
  can_cloud_download (CONFIG_NOT_AVAILABLE / 42K0I); no working e2e path until
  SEA inline-Arrow (go/inline-arrow-sea) ships server-side.
- kernel_set_log_callback / kernel_logging_stats / kernel_log_callback /
  KernelLogLevel — kernel_init_logging (stderr/file) already covers C-ABI hosts;
  the reverse-call sink is an ergonomics upgrade, not required.

Deletes src/c_abi/cancel.rs, src/c_abi/logging.rs and the five dropped-surface
test files; prunes tests/c/session_smoke.c and the header/changelog. No core
kernel code touched. make check green (fmt + clippy + cargo test + C smoke).

Co-authored-by: Isaac
Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
@mani-mathur-arch mani-mathur-arch changed the title feat(c-abi): cancel token, ABI-version handshake, blocking close, mTLS + CloudFetch setters, log callback feat(c-abi): mTLS client-certificate setter + ABI-version handshake Jul 20, 2026
…untime

ffi_prepare_runtime() was extracted so block_on_ffi and
block_on_ffi_cancellable could share the clear-error / reentrancy-reject /
runtime-fetch preamble without drift. The cancellable path was dropped, so the
helper had a single caller and its doc still referenced the removed
block_on_ffi_cancellable. Fold the preamble back inline — block_on_ffi is now
byte-for-byte identical to its pre-cancel-token (main) form.

No behavior change. make check green.

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

mani-mathur-arch commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

I have removed all the features which do not have any precedent in any of the other drivers along with the log callback as that is not a correctness gate. this is now a focused pr with only the version check and the mtls setters

Bring the branch up to date with main after #178 (configurable HTTP
retry/backoff) landed. #178 and this branch both extend the same C-ABI
session surface, so the merge conflicted on the shared files; all conflicts
are additive-vs-additive and resolved by keeping both sides:

- NEXT_CHANGELOG.md — keep both Added blocks (retry-config + mTLS/ABI-version).
- include/databricks_kernel.h — keep both setters (set_retry_config,
  set_tls_client_certificate).
- src/c_abi/session.rs — de-interleave the test module: both branches appended
  #[test] fns sharing the same config-new boilerplate; split into complete
  separate functions, keeping every test from both.
- tests/c/session_smoke.c — keep both the retry-config and mTLS setter checks
  in test_proxy_and_tls_setters.

Verified: cargo fmt --check clean, clippy -D warnings clean, full suite green
(705 lib + all integration/C-smoke; live-warehouse E2E ignored as usual).

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

Copy link
Copy Markdown

This PR has been marked as Stale because it has been open for 30 days with no activity. If you would like the PR to remain open, please remove the stale label or comment on the PR.

@github-actions github-actions Bot added the Stale label Aug 20, 2026
@github-actions

Copy link
Copy Markdown

This PR was closed because it has been inactive for 7 days since being marked as stale.

@github-actions github-actions Bot closed this Aug 27, 2026

This branch was previously deployed

1 inactive deployment
azure-prod — 760625ba Deployed Jul 20, 2026 by mani-mathur-arch via v0 TLS (mitmproxy) #247
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants