Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ changes go in their respective binding's NEXT_CHANGELOG.
### Added

- Add a C ABI setter for the maximum idle HTTP connections retained per host.
- C ABI: `kernel_statement_set_query_tags()` attaches per-statement query tags
(serialized `key:value` wire form) to a statement's execution, letting C ABI
consumers (ODBC, Go's kernel backend) reach parity with the Rust/PyO3/napi
`query_tags` surface.

### Changed

Expand Down
16 changes: 16 additions & 0 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,22 @@ KernelStatusCode kernel_statement_bind_parameter(kernel_statement_t* stmt,
const char* sql_type,
const char* value);

/*
* Set per-statement query tags — key/value annotations sent with this
* statement's execution for cost attribution and tracking. `query_tags` is the
* serialized wire form: comma-separated `key:value` pairs, with a bare `key`
* (no colon) for a valueless tag, e.g. "team:eng,job:etl,production"; backslash
* escapes the separators in a value ("\:", "\,", "\\"). This is the same string
* a host already builds for the Thrift `confOverlay` path (Go/Node connectors),
* so it is passed through unchanged and re-parsed into the native SEA query_tags
* array at execute time. A non-empty value replaces the statement's tags; an
* empty string clears any previously-set tags (they otherwise persist across
* kernel_statement_set_sql, so pass "" to reset a reused statement handle).
* `query_tags` must be a NUL-terminated UTF-8 string.
*/
KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt,
const char* query_tags);

/*
* Wait-for-result execution. On success, `*out` holds an executed handle
* released with `kernel_executed_statement_close`.
Expand Down
65 changes: 65 additions & 0 deletions src/c_abi/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,59 @@ fn check_ordinal(ordinal: usize) -> Result<(), Error> {
Ok(())
}

/// Set per-statement query tags — key/value annotations sent with this
/// statement's execution for cost attribution and tracking. `query_tags` is the
/// serialized wire form: comma-separated `key:value` pairs, with a bare `key`
/// (no colon) for a valueless tag, e.g. `team:eng,job:etl,production`; backslash
/// escapes the separators in a value (`\:`, `\,`, `\\`). This is the same string
/// [`crate::statement::spec::serialize_query_tags`] produces, so a host that

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low — The doc comment on the public FFI function kernel_statement_set_query_tags contains an intra-doc link to [crate::statement::spec::serialize_query_tags], but serialize_query_tags is a private (non-pub) function in spec.rs. A public item linking to a private item triggers rustdoc's private_intra_doc_links lint (warn-by-default), so cargo doc (and anything running with RUSTDOCFLAGS=-D warnings) will warn/fail. This won't be caught by the documented CI gates (cargo fmt / cargo clippy / cargo test), since intra-doc link resolution happens during cargo doc, not doc-test compilation. Consider dropping the link to plain code font, or linking a public anchor instead.

/// already serializes tags for the Thrift `confOverlay` path (e.g. the Go/Node
/// connectors) passes it through unchanged. The kernel re-parses it into the
/// native SEA `query_tags` array at execute time (see
/// [`crate::statement::mutable`]).
///
/// A non-empty value **replaces** the statement's query tags; an **empty string
/// clears** any previously-set tags. Clearing matters because query tags persist
/// across [`kernel_statement_set_sql`] (which resets bound parameters but not the
/// statement conf), so a reused statement handle would otherwise carry an earlier
/// query's tags into later executions — passing `""` before re-executing resets
/// them. (This is a deliberate divergence from the typed
/// [`crate::statement::spec::StatementSpec::query_tags`], whose empty **map** is a
/// no-op: this single C entry point makes empty = clear so the C surface can both
/// set and reset without a second function.)
///
/// # Safety
/// `stmt` must be a live statement handle; `query_tags` must be a NUL-terminated
/// UTF-8 C string.
#[no_mangle]
pub unsafe extern "C" fn kernel_statement_set_query_tags(
stmt: *mut kernel_statement_t,
query_tags: *const c_char,
) -> KernelStatusCode {
with_statement(stmt, |stmt| {
if query_tags.is_null() {
return Err(Error::invalid_argument().message("query_tags must not be null"));
}
let tags = CStr::from_ptr(query_tags)
.to_str()
.map_err(|_| Error::invalid_argument().message("query_tags is not valid UTF-8"))?;
// Empty → clear. statement_conf survives set_sql, so a reused handle would
// otherwise leak a prior query's tags; an explicit empty string is the C
// ABI's way to reset them before re-executing.
if tags.is_empty() {
stmt.spec().statement_conf.remove("query_tags");
return Ok(());
}
// The value is already in the wire form the SEA execute path reads back
// from `statement_conf["query_tags"]`, so store it verbatim rather than
// round-tripping through the typed `query_tags(map)` builder.
stmt.spec()
.statement_conf
.insert("query_tags".to_string(), tags.to_string());
Ok(())
})
}

// ─── Execute (sync) ──────────────────────────────────────────────────────────

/// Wait-for-result execution. Auto-cancels + closes any prior executed
Expand Down Expand Up @@ -801,6 +854,18 @@ mod tests {
// crash. The success + concurrent-cancel-during-execute paths are covered by
// tests/v0_c_abi_canceller_wiremock.rs, which drives these entry points
// against a mock SEA server.
#[test]
fn set_query_tags_null_handle_returns_invalid_argument() {
// A null statement handle is rejected before the tags are read, so this
// never crashes. (The happy path — a live handle — is covered where the
// serialized string reaches the wire array: see the
// `build_execute_params_reads_raw_query_tags_conf` test in
// `statement::mutable`.)
let rc =
unsafe { kernel_statement_set_query_tags(std::ptr::null_mut(), c"team:eng".as_ptr()) };
assert_eq!(rc, KernelStatusCode::InvalidArgument);
}

#[test]
fn canceller_null_guards_return_invalid_argument() {
let mut out: *mut kernel_statement_canceller_t = std::ptr::null_mut();
Expand Down
52 changes: 52 additions & 0 deletions src/statement/mutable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,58 @@ mod tests {
assert!(params.query_tags.is_empty());
}

#[test]
fn build_execute_params_reads_raw_query_tags_conf() {
// The C ABI `kernel_statement_set_query_tags` stores the pre-serialized
// wire string directly under `statement_conf["query_tags"]` (rather than
// going through the typed `Statement::query_tags` builder). It must reach
// `ExecuteParams.query_tags` as the native array just the same — this is
// the seam the C ABI relies on. Includes a bare key (None value) and an
// escaped colon in a value.
use std::collections::{HashMap, HashSet};
let mut spec = StatementSpec::new();
spec.sql("SELECT 1");
spec.statement_conf(HashMap::from([(
"query_tags".to_string(),
"team:eng,prod,url:http\\://h".to_string(),
)]));

let (_sql, params) = build_execute_params(&spec, None).unwrap();
let got: HashSet<(String, Option<String>)> = params
.query_tags
.iter()
.map(|t| (t.key.clone(), t.value.clone()))
.collect();
let expected: HashSet<(String, Option<String>)> = [
("team".to_string(), Some("eng".to_string())),
("prod".to_string(), None),
("url".to_string(), Some("http://h".to_string())),
]
.into_iter()
.collect();
assert_eq!(got, expected);
}

#[test]
fn build_execute_params_clears_query_tags_when_conf_removed() {
// The C ABI `kernel_statement_set_query_tags(stmt, "")` clears tags by
// removing statement_conf["query_tags"] — needed because the conf survives
// set_sql, so a reused handle would otherwise leak a prior query's tags.
// After removal, no query_tags reach the wire.
use std::collections::HashMap;
let mut spec = StatementSpec::new();
spec.sql("SELECT 1");
spec.statement_conf(HashMap::from([(
"query_tags".to_string(),
"team:eng".to_string(),
)]));
// Simulate the empty-string clear path.
spec.statement_conf.remove("query_tags");

let (_sql, params) = build_execute_params(&spec, None).unwrap();
assert!(params.query_tags.is_empty());
}

#[test]
fn build_execute_params_binds_positional_params_one_based() {
let mut spec = StatementSpec::new();
Expand Down
3 changes: 3 additions & 0 deletions tests/c/session_smoke.c
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ static void test_null_guards(void) {
rc = kernel_statement_close(NULL);
CHECK(rc == KernelStatusCode_InvalidArgument, "statement_close(NULL) → InvalidArgument");

rc = kernel_statement_set_query_tags(NULL, "team:eng");
CHECK(rc == KernelStatusCode_InvalidArgument, "statement_set_query_tags(NULL) → InvalidArgument");

rc = kernel_result_stream_close(NULL);
CHECK(rc == KernelStatusCode_InvalidArgument, "result_stream_close(NULL) → InvalidArgument");

Expand Down
Loading