Repository navigation
feat(c-abi): configurable HTTP retry / backoff policy - #178
Conversation
Add kernel_session_config_set_retry_config(min_wait_ms, max_wait_ms, max_retries, overall_timeout_ms) so a C-ABI host can make its own RetryWaitMin / RetryWaitMax / RetryMax / retry-budget policy authoritative instead of the kernel's built-in default. The crate already has exponential backoff with jitter and configurable HttpConfig::retry_* fields, but the C-ABI open path hardcoded ..HttpConfig::default(), so a host's retry surface was silently ignored. - New RetrySpec on KernelSessionConfig, merged into HttpConfig in build_session (co-exists with custom_headers; every other HTTP default is preserved). max_retries == 0 disables retries; overall_timeout_ms == 0 keeps the kernel default 900s budget (non-zero overrides it, matching the pyo3/napi retry_overall_timeout knob). - Rejects min_wait_ms == 0 and max_wait_ms < min_wait_ms as InvalidArgument (a degenerate range must not reach the HTTP client). - Clamps max_retries to u32::MAX - 1 so the client's max_retries + 1 total-attempts computation can't overflow (the napi/pyo3 bindings feed this via saturating_sub(1); the C ABI is the only path that could hand the client a raw u32). Caught by Isaac Review. Benefits ODBC too. Header decl + NEXT_CHANGELOG + C smoke asserts + unit tests (records-knobs incl. the u32::MAX clamp, and bad-range rejection). make check clean (fmt + clippy -D warnings + full suite + C smoke). Co-authored-by: Isaac <isaac@databricks.com> Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
The kernel holds cloudfetch_max_chunks_in_memory (default 16) decompressed CloudFetch chunks in memory at once, bounding download parallelism and peak RSS. On large decimal-heavy result sets that default drives ~1.2 GB peak RSS (each chunk ~75 MB); lowering it trades a little throughput for a large RSS reduction (e.g. chunks=4 -> ~+449 MB). The field already exists on ResultConfig and feeds the CloudFetch pipeline, but the C ABI exposed no way to set it — a Go/ODBC consumer could not tune it. Expose it as a client-only session_conf key rather than a new C-ABI symbol, so the existing kernel_session_config_set_session_conf entry point carries it: - apply_client_result_overrides(&mut config) runs at the top of Session::open, reads cloudfetch_max_chunks_in_memory from session_conf, folds a valid positive value into config.result, and removes the key from session_conf so it can never reach the SEA wire. - Absent key keeps the ResultConfig default (16); a non-numeric or non-positive value is ignored (default preserved) with a warning rather than failing session creation — a best-effort tuning knob must not turn a typo into a connect error. - The key is deliberately NOT in SESSION_CONF_ALLOWLIST, so even without the strip step filter_session_conf would drop it; a test pins that invariant so a future allowlist edit can't promote it to a server SET param. Matched case-insensitively, consistent with the rest of the session_conf handling. 5 unit tests (apply / case-insensitive / absent-default / invalid-ignored-but-stripped / not-server-allowlisted). make check clean; full suite (798 tests) green. Co-authored-by: Isaac <isaac@databricks.com> Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Code Review Squad — ReviewScore: 87/100 — MODERATE RISK Two additive tuning knobs: a typed, validated Low FindingsLow findings (7) — click to expandF3 — Sibling knobs use opposite mechanisms + error contracts (architecture + devils-advocate) · Retry is a typed C-ABI symbol that hard-fails bad input ( F4 — Client override parsed in core
F5 —
F6 — Cloudfetch tests use Every cloudfetch test builds a
F7 — Production parses
F8 — No log breadcrumb when a custom retry policy is applied (ops) · When
F9 — Default values duplicated across 5 doc sites (devils-advocate) · The "900s / 5 retries / 1s..60s" kernel defaults are hardcoded in the header comment, the changelog, and three Rust doc comments — none tied to |
Addresses the two Medium findings from the /full-review pass on this PR. - F1: extract the RetrySpec→HttpConfig merge out of build_session into a pure merge_http_config() helper and unit-test it (field-for-field mapping, None overall_timeout keeps the 900s default, retry-only and headers-only configs). The merge is what actually configures live retries and previously had zero coverage. - F2: clamp cloudfetch_max_chunks_in_memory to CLOUDFETCH_MAX_CHUNKS_CEILING (256) with a warn!, mirroring the retry setter's clamp discipline, so a fat-fingered value can't drive peak RSS toward OOM (no downstream guard exists). Adds a boundary test. make check green (fmt + clippy -D warnings + 698 lib tests + C smoke). Co-authored-by: Isaac <isaac@databricks.com> Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
| * surface override the kernel's built-in policy (default 5 retries, 1s..60s, | ||
| * 900s budget) when this setter is not called. `min_wait_ms == 0` or | ||
| * `max_wait_ms < min_wait_ms` returns InvalidArgument. Benefits ODBC too. */ | ||
| KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* config, |
There was a problem hiding this comment.
CloudFetch client knob is undiscoverable at the API boundary
The retry knob ships a typed header symbol + a NEXT_CHANGELOG.md entry. The cloudfetch_max_chunks_in_memory client knob ships neither — it lives only in Rust source comments (src/session.rs). For a C ABI whose header is the contract, an external host (the ODBC/Go consumers the changelog courts with "Benefits ODBC too") has no way to learn the key exists or what values it accepts. The two error contracts also diverge: retry rejects bad input with InvalidArgument; cloudfetch silently warns-and-ignores.
Live verification: built at this SHA and tested against a real warehouse — the knob mechanism works end-to-end (range(100000) streamed back with max_chunks=4; an invalid value was ignored without failing connect). So this is purely a documentation/discoverability gap, not a functional bug — but a shipped-but-undocumented tunable is effectively dead to the very consumers it targets.
Suggested fix
Add a NEXT_CHANGELOG.md entry and a header comment near set_session_conf enumerating recognized client-only session_conf keys and their accepted values. Longer term, document a single rule for "typed C-ABI symbol vs client session_conf key" so the choice is principled rather than decided per-PR.
Reviewers: architecture. Confidence: 82.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed in c887904.
- Added a
NEXT_CHANGELOG.mdentry for thecloudfetch_max_chunks_in_memoryclient-only key (accepted values, 256 ceiling / clamp, warn-and-ignore on bad input, never reaches the wire). - Added a header comment near
set_session_confdocumenting the client-only-vs-server-SET distinction and enumerating the recognized client key + its accepted values, so a C host reading the contract can discover it.
On the divergent error contracts (retry InvalidArgument vs cloudfetch warn-and-ignore): kept deliberately. A retry range is structurally invalid (a degenerate range must not reach the client), whereas the chunk knob is a best-effort perf tuning where a typo should not turn into a connect failure — so it clamps/ignores with a warning instead. Both behaviors are now documented at the boundary.
| // path that could otherwise hand the client an unclamped u32. | ||
| max_retries: max_retries.min(u32::MAX - 1), | ||
| // 0 => keep the kernel default budget; any non-zero value overrides it. | ||
| overall_timeout: (overall_timeout_ms != 0) |
There was a problem hiding this comment.
overall_timeout_ms == 0 overloads "keep 900s default" — silently caps explicitly-configured retries
0 means "keep the kernel's 900s budget," so there is no sentinel for "no overall budget." A host that sets a high max_retries but leaves overall_timeout_ms = 0 is silently held to 900s — exponential backoff can sum past 900s and the explicitly-requested attempts never run, with no signal to the caller.
Verified: src/client/http.rs:872 / :925 do enforce the budget around sleeps (if elapsed + wait > config.overall_timeout { stop }), so the consequence is real at the code level. Reachability caveat: no Go or ODBC consumer calls kernel_session_config_set_retry_config yet (confirmed against the driver checkouts), so this is not triggerable through a shipped driver today — worth fixing before a driver adopts the symbol, not a live blocker now.
Suggested fix
Document the 0 = default budget overload prominently in the header, or reserve a distinct sentinel (e.g. u64::MAX) for "no overall budget" so a host can express unbounded retries. At minimum, note in the header that a large max_retries is still bounded by the 900s default budget unless overall_timeout_ms is raised.
Reviewers: devils-advocate. Confidence: 84.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed (doc-only) in c887904.
Kept 0 = keep default budget as-is (no u64::MAX-style unbounded sentinel) — the kernel budget is always bounded, and pyo3/napi have no unbounded escape hatch either, so adding one only in the C ABI would diverge the surfaces. Instead documented the cap prominently in both the C header and the Rust setter doc:
The retry budget is ALWAYS bounded — there is no "unlimited" value. A large
max_retriesis still capped by the (default or overridden) budget: if the exponential backoff sums pastoverall_timeout_msthe remaining attempts do not run, so raiseoverall_timeout_msalongside a largemax_retriesif you want them all to fire.
One correction to the reachability caveat: this symbol is now called by a shipping consumer — the Go driver forwards WithRetries → kernel_session_config_set_retry_config (databricks/databricks-sql-go#412), with overall_timeout carried by WithKernelRetryOverallTimeout. So the doc is worth having in place before adoption spreads; the Go side leaves overall_timeout=0 (kernel default) unless the caller sets WithKernelRetryOverallTimeout, which is exactly the case the new docs describe.
| overall_timeout_ms: u64, | ||
| ) -> KernelStatusCode { | ||
| set_on_config(config, |c| { | ||
| if min_wait_ms == 0 { |
There was a problem hiding this comment.
No validation of backoff bounds against a non-zero retry budget — a too-small budget silently disables all retries
The setter validates only min_wait_ms > 0 and max_wait_ms >= min_wait_ms. It never checks min_wait_ms against a non-zero overall_timeout_ms, so a budget smaller than the first backoff wait is accepted as valid. Example: set_retry_config(min=10000, max=60000, max_retries=5, overall_timeout_ms=5000) returns Success, but the first ~10s backoff already exceeds the 5s budget, so zero retries execute despite max_retries=5. The host believes retries are on; they are silently off.
Verified: budget enforcement confirmed at src/client/http.rs:872. Live-tested the happy path against a real warehouse — the degenerate budget(5s) < backoff(10s) config is accepted and a healthy warehouse still connects (no retry fires when none is needed); the silent-disable manifests only on an actual transport failure. Same reachability caveat as F1 (no driver calls the symbol yet).
Suggested fix
When overall_timeout_ms != 0, reject (or warn!) if overall_timeout_ms < min_wait_ms, since that combination guarantees zero retries — mirroring the existing degenerate-range rejection.
Reviewers: devils-advocate. Confidence: 82.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed in c887904 (warn, not reject).
The setter now warns when overall_timeout_ms != 0 && overall_timeout_ms < min_wait_ms:
retry overall_timeout_ms is below min_wait_ms; the retry budget is
exhausted before the first backoff, so no retries will run
Chose warn over InvalidArgument deliberately: unlike the degenerate range (min==0 / max<min), which is structurally nonsense and must never reach the client, budget < min_wait still produces a coherent single-attempt request — hard-rejecting it would fail an otherwise-valid host connect. The warning surfaces the "retries you asked for cannot fire" footgun without turning it into a connect error. New test set_retry_config_small_budget_is_accepted pins that it is accepted + recorded verbatim; budget enforcement itself is already covered at src/client/http.rs:872.
| /// default budget (900s) — pass a non-zero value to override it (matching the | ||
| /// pyo3/napi `retry_overall_timeout` knob). When this setter is not called the | ||
| /// kernel keeps its default policy (5 retries, 1s..60s, 900s budget). | ||
| /// `min_wait_ms == 0` and `max_wait_ms < min_wait_ms` are rejected as |
There was a problem hiding this comment.
Retry-policy defaults (900s, 5 retries, 1s..60s) and rationale duplicated verbatim across ~5 sites
The same policy prose — "keeps the kernel default 900s budget", "default 5 retries, 1s..60s, 900s budget", "matching the pyo3/napi retry_overall_timeout knob" — is hand-copied into NEXT_CHANGELOG.md, the C header (include/databricks_kernel.h), the retry field doc, the RetrySpec doc, and this setter doc. The concrete numbers are not derived from HttpConfig::default(); they are literal prose in ≥5 places.
When HttpConfig::default() changes (e.g. the 900s budget), every copy silently becomes a lying comment across a public C-ABI header + changelog + three Rust docs, with nothing forcing them to move together.
Suggested fix
State the numeric defaults once (the header comment is the host-facing contract) and have the Rust docs say "the kernel default (see HttpConfig::default())" without re-listing values. Collapse the repeated "matching the pyo3/napi…" clause to a single site.
Reviewers: maintainability. Confidence: 84.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed in c887904.
Collapsed to a single source of truth per audience:
- Numeric defaults (
900s / 5 / 1s..60s) now stated once, in the host-facing C header (the actual contract for a C consumer). The three Rust doc sites (RetrySpecdoc, theretryfield doc, the inline merge comment) now say "seeHttpConfig::default()" instead of re-listing the values. - The "matching the pyo3/napi
retry_overall_timeout" clause now appears once (the Rust setter doc, where a kernel dev cross-references the sibling bindings); dropped from theRetrySpecdoc, the header, and the changelog.
So HttpConfig::default() remains the only place the numbers live in code, and a future change to the 900s budget no longer silently strands stale copies.
| let key = config | ||
| .session_conf | ||
| .keys() | ||
| .find(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)) |
There was a problem hiding this comment.
Duplicate case-variant cloudfetch_max_chunks_in_memory keys → nondeterministic value applied
session_conf.keys().find(|k| k.eq_ignore_ascii_case(...)) returns the first key in HashMap iteration order (unordered), then only that one key is removed. If a host sets two keys differing only in ASCII case (e.g. cloudfetch_max_chunks_in_memory=8 and CloudFetch_Max_Chunks_In_Memory=200), which value wins is nondeterministic across runs.
Live verification: tested with both case-variants set against a real warehouse — the session opens cleanly and neither key leaks to the SEA wire (the un-chosen key is dropped by the non-allowlisted filter). So there is no correctness/security leak; the only defect is nondeterministic tuning of peak RSS.
Suggested fix
Collect all case-insensitive matches, remove every one, and apply a deterministic rule (last-write-wins or reject-on-conflict) rather than picking an arbitrary single key.
Reviewers: devils-advocate. Confidence: 80.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed in c887904.
apply_client_result_overrides now collects every case-insensitive match, sorts them, applies the lexicographically-last spelling deterministically, and removes all variants (so nothing leaks to the wire regardless). A warn! fires when >1 variant is present. New test cloudfetch_max_chunks_duplicate_case_variants_are_deterministic sets CloudFetch_...=8 + cloudfetch_...=200 + a benign ansi_mode=true, and asserts: 200 wins (deterministic), every client-key variant is stripped, and the unrelated server param survives untouched — which also covers the over-removal concern from the earlier F6 (the test no longer relies on is_empty()).
| // kernel's full HttpConfig::default() applies untouched. The merge | ||
| // itself is a pure helper (`merge_http_config`) so it can be | ||
| // unit-tested without a live session — it is the code that actually | ||
| // configures live retries. |
There was a problem hiding this comment.
merge_http_config rationale duplicated between its doc comment and its call-site inline comment
The doc comment on merge_http_config (line ~665: "it is a pure helper kept unit-testable without a live session … the code that actually configures live retries") is repeated near-verbatim as the inline comment at this build_session call site. Both also restate the "start from defaults, set only populated fields" logic the code already shows, and the inline block is a WHAT-comment for the if !custom_headers.is_empty() || retry.is_some() guard directly below it.
Suggested fix
Keep the rationale on the function; reduce the call-site comment to one line on the guard's intent (skip .http() so HttpConfig::default() applies untouched).
Reviewers: maintainability. Confidence: 82.
/full-review · feedback: #code-review-squad-feedback
There was a problem hiding this comment.
Fixed in c887904. Kept the rationale on the merge_http_config doc and reduced the build_session call-site comment to a single line on the guard's intent:
// Skip `.http()` when neither headers nor a retry spec was set, so
// the kernel's full `HttpConfig::default()` applies untouched.
if !custom_headers.is_empty() || retry.is_some() {
Code Review Squad — ReviewScore: 83/100 — MODERATE RISK Two well-scoped C-ABI tuning knobs. The retry path is idiomatic, range-validated, and thoroughly unit-tested; security found nothing. Findings were verified empirically — the kernel was built at this PR's SHA and tested against a live warehouse (5/5 live tests passed). Key context from that verification: the new Medium FindingsF2 — Every unit test drives Live verification: I built at this SHA and opened a retry-only session against a real warehouse — the gate fires and the session opens, so the path is functionally correct today. This is purely a missing test, not a live defect.
Reviewers: test, devils-advocate. Confidence: 80. |
… deterministic case-variants, gate test Addresses Madhavendra's /full-review findings on #178: - Document the client-only `cloudfetch_max_chunks_in_memory` session_conf key at the C-ABI boundary (header comment near set_session_conf + NEXT_CHANGELOG entry) so the ODBC/Go consumers can discover it. - Retry setter: warn (not reject) when a non-zero overall_timeout_ms is below min_wait_ms — the budget is exhausted before the first backoff so no retries run, but a coherent single-attempt config must not hard-fail a host connect. Document that the retry budget is always bounded (no unbounded sentinel; a large max_retries is still capped by it). - apply_client_result_overrides: collect ALL case-insensitive spellings of the chunk key, apply the lexicographically-last deterministically, and strip every variant — was nondeterministic across HashMap iteration order. - De-duplicate the retry defaults prose: state 900s/5/1s..60s once in the host-facing header; Rust docs now point at HttpConfig::default(). Drop the repeated "matching the pyo3/napi" clause and the merge_http_config call-site comment that restated its own doc. - Add an end-to-end build_session test: a retry-only config with retries disabled must fail its lone attempt against a 503, proving the retry spec reaches the client (a gate regression to headers-only would retry and open). Add a small-budget acceptance test. make check green (fmt + clippy -D warnings + full suite + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur <mani.mathur@databricks.com>
Review follow-up — all findings addressed in c887904Thanks @msrathore-db. Fixes pushed:
Note: the reachability caveat is now stale — this symbol is consumed by the Go driver via |
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>
Two related C-ABI / session-config changes that let a C-ABI host (the Go SEA-via-kernel driver, and ODBC) tune HTTP retry policy and CloudFetch memory that the kernel previously kept internal.
1. Configurable HTTP retry / backoff policy
Exposes the crate's existing HTTP retry / backoff knobs over the C ABI so a host can make its own retry policy authoritative instead of the kernel default.
Why
The crate already has exponential backoff with jitter and configurable
HttpConfig::retry_*fields, but the C-ABI open path hardcoded..HttpConfig::default()— so a host'sRetryWaitMin/RetryWaitMax/RetryMaxsurface was silently ignored, and the disable form couldn't be honored at all. This adds the one setter that surface needs.What
kernel_session_config_set_retry_config(config, min_wait_ms, max_wait_ms, max_retries, overall_timeout_ms):RetrySpeconKernelSessionConfig, merged intoHttpConfiginbuild_session(co-exists withcustom_headers; every other HTTP default — per-request timeout, pool size — is preserved).max_retries == 0disables retries (single attempt).overall_timeout_ms == 0keeps the kernel's default 900s budget; a non-zero value overrides it, matching the pyo3/napiretry_overall_timeoutknob.min_wait_ms == 0andmax_wait_ms < min_wait_msasInvalidArgument(a degenerate range must not reach the HTTP client).max_retriestou32::MAX - 1so the client'smax_retries + 1total-attempts computation (src/client/http.rs) can't overflow — a debug build would panic, a release build would wrap to 0 and silently disable all retries. The napi/pyo3 bindings feed this field viasaturating_sub(1); the C ABI is the only path that could otherwise hand the client a rawu32. (Surfaced by Isaac Review.)Benefits ODBC too (same C ABI).
2. Tune
cloudfetch_max_chunks_in_memoryviasession_confLets a host bound how many decompressed CloudFetch chunks the kernel holds in memory at once (peak RSS on large result sets).
Why
ResultConfig::cloudfetch_max_chunks_in_memory(default 16) already feeds the CloudFetch pipeline and bounds download parallelism + peak RSS, but the C ABI exposed no way to set it — a Go/ODBC consumer could not tune it. On large decimal-heavy results the default drives ~1.2 GB peak (each chunk ~75 MB); lowering it trades a little throughput for a large RSS reduction (the Go driver measures ~265 MB @ chunks=4 vs ~856 MB @ chunks=32 on a 3M-row query).What
Rather than a new C-ABI symbol, expose it as a client-only
session_confkey carried by the existingkernel_session_config_set_session_confsetter:apply_client_result_overrides(&mut config)runs at the top ofSession::open, readscloudfetch_max_chunks_in_memoryfromsession_conf, folds a valid positive value intoconfig.result, and removes the key fromsession_confso it can never reach the SEA wire.ResultConfigdefault (16); a non-numeric or non-positive value is ignored (default preserved) with a warning rather than failing session creation — a best-effort tuning knob must not turn a typo into a connect error.SESSION_CONF_ALLOWLIST, so even without the strip stepfilter_session_confwould drop it; a test pins that invariant so a future allowlist edit can't promote it to a server SET param.session_confhandling.No new C-ABI symbol. Benefits ODBC too (same setter).
Testing
make checkclean (fmt + clippy-D warnings+ full suite + C smoke).u32::MAXclamp) and bad-range rejection; C-smoke asserts for valid / disable / non-zero-budget /min==0/max<min.Full suite (798 tests) green.
This pull request and its description were written by Isaac.