diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 712ce5cb..9f15fa60 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -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 diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 6ea9bccb..525f2f8b 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -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`. diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 4ec007f1..8fe65d6f 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -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 +/// 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 @@ -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(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 1903cc5c..4f018300 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -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)> = params + .query_tags + .iter() + .map(|t| (t.key.clone(), t.value.clone())) + .collect(); + let expected: HashSet<(String, Option)> = [ + ("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(); diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 599f8798..0584d6ad 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -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");