From a56dccef1dabdfe6dc27f0a93bca1ca9a76efff2 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Tue, 22 Sep 2026 00:53:07 +0000 Subject: [PATCH 1/6] feat(feature-flags): add generic connector-backed resolver Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- NEXT_CHANGELOG.md | 2 + src/client/http.rs | 104 +++++- src/client/retry.rs | 6 +- src/feature_flags/cache.rs | 511 +++++++++++++++++++++++++ src/feature_flags/mod.rs | 747 +++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + 6 files changed, 1356 insertions(+), 16 deletions(-) create mode 100644 src/feature_flags/cache.rs create mode 100644 src/feature_flags/mod.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 31673499..efc49103 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -12,6 +12,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added - Added Thrift-native metadata routing with compatible public-schema casts and one-based `getColumns` ordinals. +- Add connector-service feature-flag resolution with authenticated requests, + JSON-serialized per-driver values, and bounded process-wide caching. ### Changed diff --git a/src/client/http.rs b/src/client/http.rs index cf290925..25284ee6 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -24,7 +24,7 @@ use crate::auth::AuthProvider; use crate::client::retry::{ - calculate_backoff, RequestCategory, RequestType, RetryConfig, RetryStrategy, + calculate_backoff, RequestCategory, RequestIdempotency, RequestType, RetryConfig, RetryStrategy, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -382,6 +382,42 @@ pub struct DatabricksHttpClient { config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, + feature_flags_retry: RetryConfig, +} + +#[derive(Clone, Copy)] +enum RequestKind { + Public(RequestType), + FeatureFlags, +} + +impl std::fmt::Debug for RequestKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Public(request_type) => request_type.fmt(f), + Self::FeatureFlags => f.write_str("FeatureFlags"), + } + } +} + +impl RequestKind { + fn idempotency(self) -> RequestIdempotency { + match self { + Self::Public(request_type) => request_type.idempotency(), + Self::FeatureFlags => RequestIdempotency::Idempotent, + } + } + + fn transport_error(self, source: &reqwest::Error) -> Error { + // Preserve timeout provenance for the feature-flag resolver so it can + // distinguish a slow endpoint from other caller-local transport + // failures. Keep the established public-request mapping unchanged. + if matches!(self, Self::FeatureFlags) && source.is_timeout() { + Error::timeout() + } else { + Error::network_error() + } + } } impl DatabricksHttpClient { @@ -394,6 +430,15 @@ impl DatabricksHttpClient { mut config: HttpClientConfig, retry_configs: HashMap, ) -> Result { + // Keep this endpoint's policy private and single-attempt so adding + // connector-service traffic does not add a variant to the stable + // public RequestType/RequestCategory enums. + let feature_flags_retry = RetryConfig { + overall_timeout: Duration::from_secs(5), + max_retries: 0, + ..RetryConfig::default() + }; + // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't // re-applied per-request. @@ -498,6 +543,7 @@ impl DatabricksHttpClient { config, auth_provider: OnceLock::new(), retry_configs, + feature_flags_retry, }) } @@ -763,7 +809,15 @@ impl DatabricksHttpClient { /// /// The `RequestType` determines which `RetryConfig` and `RetryStrategy` to use. pub async fn execute(&self, request: Request, request_type: RequestType) -> Result { - self.execute_impl(request, true, request_type).await + self.execute_impl(request, true, RequestKind::Public(request_type)) + .await + } + + /// Execute the connector-service feature-flag request with authentication + /// and the kernel's fixed single-attempt policy. + pub(crate) async fn execute_feature_flags(&self, request: Request) -> Result { + self.execute_impl(request, true, RequestKind::FeatureFlags) + .await } /// Execute a request without authentication (for CloudFetch, OAuth endpoints). @@ -774,7 +828,8 @@ impl DatabricksHttpClient { request: Request, request_type: RequestType, ) -> Result { - self.execute_impl(request, false, request_type).await + self.execute_impl(request, false, RequestKind::Public(request_type)) + .await } /// Issue a single unauthenticated GET to `url` WITHOUT following redirects @@ -817,10 +872,13 @@ impl DatabricksHttpClient { &self, request: Request, with_auth: bool, - request_type: RequestType, + request_kind: RequestKind, ) -> Result { - let config = self.retry_config(request_type.category()); - let strategy = RetryStrategy::for_request(request_type, config); + let config = match request_kind { + RequestKind::Public(request_type) => self.retry_config(request_type.category()), + RequestKind::FeatureFlags => &self.feature_flags_retry, + }; + let strategy = RetryStrategy::for_idempotency(request_kind.idempotency(), config); let max_attempts = config.max_retries + 1; let start_time = Instant::now(); @@ -916,7 +974,7 @@ impl DatabricksHttpClient { debug!( "{:?}: {} {} (attempt {}/{})", - request_type, method, url, attempts, max_attempts + request_kind, method, url, attempts, max_attempts ); match self.client.execute(request).await { @@ -927,7 +985,7 @@ impl DatabricksHttpClient { if attempts > 1 { debug!( "{:?}: completed after {} attempts in {:.1}s — success", - request_type, + request_kind, attempts, start_time.elapsed().as_secs_f64() ); @@ -955,7 +1013,7 @@ impl DatabricksHttpClient { let error_body = response.text().await.unwrap_or_default(); debug!( "{:?}: failed after {} attempts in {:.1}s — retry timeout exceeded", - request_type, + request_kind, attempts, elapsed.as_secs_f64() ); @@ -974,7 +1032,7 @@ impl DatabricksHttpClient { last_error = Some(format!("HTTP {}", status.as_u16())); warn!( "{:?}: HTTP {} (attempt {}/{}), waiting {:.1}s before retry", - request_type, + request_kind, status.as_u16(), attempts, max_attempts, @@ -988,7 +1046,7 @@ impl DatabricksHttpClient { let error_body = response.text().await.unwrap_or_default(); debug!( "{:?}: failed after {} attempts in {:.1}s — HTTP {}", - request_type, + request_kind, attempts, start_time.elapsed().as_secs_f64(), status.as_u16() @@ -1007,7 +1065,7 @@ impl DatabricksHttpClient { if elapsed + wait > config.overall_timeout { debug!( "{:?}: failed after {} attempts in {:.1}s — retry timeout exceeded", - request_type, + request_kind, attempts, elapsed.as_secs_f64() ); @@ -1022,7 +1080,7 @@ impl DatabricksHttpClient { last_error = Some(e.to_string()); warn!( "{:?}: error (attempt {}/{}): {}, waiting {:.1}s before retry", - request_type, + request_kind, attempts, max_attempts, e, @@ -1034,12 +1092,12 @@ impl DatabricksHttpClient { debug!( "{:?}: failed after {} attempts in {:.1}s — {}", - request_type, + request_kind, attempts, start_time.elapsed().as_secs_f64(), e ); - return Err(Error::network_error().message(format!( + return Err(request_kind.transport_error(&e).message(format!( "HTTP request failed after {} attempts: {}", attempts, last_error.unwrap_or_else(|| e.to_string()) @@ -1079,6 +1137,22 @@ mod tests { assert!(client.is_ok()); } + #[test] + fn feature_flags_use_a_private_single_attempt_policy() { + let mut configs = default_retry_configs(); + for config in configs.values_mut() { + config.max_retries = 42; + config.overall_timeout = Duration::from_secs(900); + } + let client = DatabricksHttpClient::new(HttpClientConfig::default(), configs).unwrap(); + + assert_eq!(client.feature_flags_retry.max_retries, 0); + assert_eq!( + client.feature_flags_retry.overall_timeout, + Duration::from_secs(5) + ); + } + #[tokio::test] async fn test_auth_header_after_set() { let config = HttpClientConfig::default(); diff --git a/src/client/retry.rs b/src/client/retry.rs index 8b9550ba..af59f650 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -204,8 +204,12 @@ pub struct RetryStrategy { impl RetryStrategy { /// Create a strategy for the given request type and config. pub fn for_request(request_type: RequestType, config: &RetryConfig) -> Self { + Self::for_idempotency(request_type.idempotency(), config) + } + + pub(crate) fn for_idempotency(idempotency: RequestIdempotency, config: &RetryConfig) -> Self { Self { - idempotency: request_type.idempotency(), + idempotency, override_codes: config.override_retryable_codes.clone(), } } diff --git a/src/feature_flags/cache.rs b/src/feature_flags/cache.rs new file mode 100644 index 00000000..044f6b67 --- /dev/null +++ b/src/feature_flags/cache.rs @@ -0,0 +1,511 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Process-wide feature-flag cache. +//! +//! This follows the kernel's existing cache patterns: a `OnceLock` owns the +//! process-global instance, a short `Mutex>` critical section +//! makes each compound state transition atomic, and an RAII refresh guard +//! publishes a fail-open result if the loading future is cancelled. The OAuth +//! token store uses the same fresh/stale/single-flight lifecycle and guard +//! pattern; this cache adds per-identity keys and async waiter notification. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +use rand::RngExt; +use tokio::sync::oneshot; + +use super::{ClientIdentity, FeatureFlagValues}; + +const DEFAULT_TTL: Duration = Duration::from_secs(15 * 60); +const MIN_TTL: Duration = Duration::from_secs(60); +const MAX_TTL: Duration = Duration::from_secs(60 * 60); +const NEGATIVE_TTL: Duration = Duration::from_secs(60); +const MAX_IDLE_CACHE_ENTRIES: usize = 256; +const MIN_JITTER_FACTOR: f64 = 0.9; +const MAX_JITTER_FACTOR: f64 = 1.0; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct CacheKey { + host: String, + org_id: Option, + identity: ClientIdentity, +} + +impl CacheKey { + pub(crate) fn new( + host: impl Into, + org_id: Option, + identity: ClientIdentity, + ) -> Self { + Self { + host: host.into(), + org_id, + identity, + } + } +} + +struct CacheEntry { + values: Option, + refresh_after: Instant, + refreshing: bool, + waiters: Vec>>, + last_access: u64, +} + +pub(crate) enum CacheLookup { + Fresh(FeatureFlagValues), + Stale { + values: FeatureFlagValues, + start_refresh: bool, + }, + Load, + /// `Some(values)` completes the shared load. `None` asks the waiter to + /// retry lookup because the leader failed for caller-local reasons or was + /// cancelled. + Wait(oneshot::Receiver>), +} + +pub(crate) struct FeatureFlagCache { + entries: Mutex>, + // Completed entries are kept within this bound. In-flight entries are + // never evicted because doing so would break their single-flight waiters, + // so concurrent cold loads may temporarily exceed it; each completion + // trims the least-recently-used idle entries back to capacity. + idle_capacity: usize, + access_sequence: AtomicU64, +} + +impl Default for FeatureFlagCache { + fn default() -> Self { + Self::with_idle_capacity(MAX_IDLE_CACHE_ENTRIES) + } +} + +impl FeatureFlagCache { + fn with_idle_capacity(idle_capacity: usize) -> Self { + Self { + entries: Mutex::new(HashMap::new()), + idle_capacity: idle_capacity.max(1), + access_sequence: AtomicU64::new(0), + } + } + + pub(crate) fn lookup(&self, key: &CacheKey) -> CacheLookup { + let now = Instant::now(); + let last_access = self.next_access(); + let mut entries = self.lock_entries(); + + if let Some(entry) = entries.get_mut(key) { + entry.last_access = last_access; + if let Some(values) = entry.values.clone() { + if now < entry.refresh_after { + return CacheLookup::Fresh(values); + } + let start_refresh = !entry.refreshing; + entry.refreshing = true; + return CacheLookup::Stale { + values, + start_refresh, + }; + } + + let (sender, receiver) = oneshot::channel(); + entry.waiters.push(sender); + return CacheLookup::Wait(receiver); + } + + self.trim_entries(&mut entries, self.idle_capacity.saturating_sub(1), None); + entries.insert( + key.clone(), + CacheEntry { + values: None, + refresh_after: now, + refreshing: true, + waiters: Vec::new(), + last_access, + }, + ); + CacheLookup::Load + } + + pub(crate) fn refresh_guard(self: &Arc, key: CacheKey) -> RefreshGuard { + RefreshGuard { + cache: self.clone(), + key: Some(key), + } + } + + fn complete_cached( + &self, + key: CacheKey, + result: Option<(FeatureFlagValues, Duration)>, + ) -> FeatureFlagValues { + let now = Instant::now(); + let last_access = self.next_access(); + let protected_key = key.clone(); + let mut entries = self.lock_entries(); + let entry = entries.entry(key).or_insert_with(|| CacheEntry { + values: None, + refresh_after: now, + refreshing: true, + waiters: Vec::new(), + last_access, + }); + entry.last_access = last_access; + + let values = match result { + Some((values, ttl)) => { + entry.values = Some(values.clone()); + entry.refresh_after = now + ttl; + values + } + None => { + let values = entry.values.clone().unwrap_or_default(); + entry.values = Some(values.clone()); + // Cache cold failures and back off stale refresh failures so a + // connector-service outage cannot create a connection storm. + entry.refresh_after = now + NEGATIVE_TTL; + values + } + }; + entry.refreshing = false; + let waiters = std::mem::take(&mut entry.waiters); + self.trim_entries(&mut entries, self.idle_capacity, Some(&protected_key)); + drop(entries); + + for waiter in waiters { + let _ = waiter.send(Some(values.clone())); + } + values + } + + /// Complete a caller-local failure without publishing a process-wide + /// negative result. Cold entries are removed and waiters retry so a bad + /// token, proxy, or cancelled leader cannot suppress a healthy session. + /// A stale entry keeps its last good values and becomes immediately + /// refreshable by the next caller. + fn complete_uncached_failure(&self, key: CacheKey) -> FeatureFlagValues { + let mut entries = self.lock_entries(); + let Some(mut entry) = entries.remove(&key) else { + return FeatureFlagValues::default(); + }; + let values = entry.values.clone().unwrap_or_default(); + let waiters = std::mem::take(&mut entry.waiters); + + if entry.values.is_some() { + entry.refreshing = false; + entry.last_access = self.next_access(); + entries.insert(key.clone(), entry); + self.trim_entries(&mut entries, self.idle_capacity, Some(&key)); + } + drop(entries); + + for waiter in waiters { + let _ = waiter.send(None); + } + values + } + + fn next_access(&self) -> u64 { + self.access_sequence.fetch_add(1, Ordering::Relaxed) + } + + fn trim_entries( + &self, + entries: &mut HashMap, + target_len: usize, + protected: Option<&CacheKey>, + ) { + while entries.len() > target_len { + let candidate = entries + .iter() + .filter(|(key, entry)| { + !entry.refreshing && protected.is_none_or(|protected| *key != protected) + }) + .min_by_key(|(_, entry)| entry.last_access) + .map(|(key, _)| key.clone()); + let Some(candidate) = candidate else { + break; + }; + entries.remove(&candidate); + } + } + + fn lock_entries(&self) -> MutexGuard<'_, HashMap> { + self.entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +pub(crate) struct RefreshGuard { + cache: Arc, + key: Option, +} + +impl RefreshGuard { + pub(crate) fn success(mut self, values: FeatureFlagValues, ttl: Duration) -> FeatureFlagValues { + self.cache.complete_cached( + self.key.take().expect("refresh guard is armed"), + Some((values, ttl)), + ) + } + + pub(crate) fn backoff(mut self) -> FeatureFlagValues { + self.cache + .complete_cached(self.key.take().expect("refresh guard is armed"), None) + } + + pub(crate) fn retry(mut self) -> FeatureFlagValues { + self.cache + .complete_uncached_failure(self.key.take().expect("refresh guard is armed")) + } +} + +impl Drop for RefreshGuard { + fn drop(&mut self) { + if let Some(key) = self.key.take() { + // Cancellation is local to the leader. Wake cold-miss followers + // and let one retry instead of poisoning the process-wide cache. + self.cache.complete_uncached_failure(key); + } + } +} + +pub(crate) fn global_cache() -> Arc { + static CACHE: OnceLock> = OnceLock::new(); + CACHE + .get_or_init(|| Arc::new(FeatureFlagCache::default())) + .clone() +} + +pub(crate) fn response_ttl(ttl_seconds: Option) -> Duration { + let seconds = ttl_seconds + .filter(|seconds| *seconds > 0) + .map(|seconds| seconds as f64) + .unwrap_or(DEFAULT_TTL.as_secs_f64()) + .clamp(MIN_TTL.as_secs_f64(), MAX_TTL.as_secs_f64()); + // Within the supported TTL band, refresh no later than the server's + // advertised TTL. Downward-only jitter spreads callers without extending + // a rollout or kill-switch lifetime; the clamps still protect the endpoint + // from pathological sub-minute or multi-hour values. + let jitter = rand::rng().random_range(MIN_JITTER_FACTOR..=MAX_JITTER_FACTOR); + Duration::from_secs_f64((seconds * jitter).clamp(MIN_TTL.as_secs_f64(), MAX_TTL.as_secs_f64())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::feature_flags::ClientType; + + fn key(name: &str) -> CacheKey { + CacheKey::new( + format!("https://{name}.example.com"), + None, + ClientIdentity::new(ClientType::Go, "1.0.0"), + ) + } + + fn values() -> FeatureFlagValues { + FeatureFlagValues::from_entries([("test.flag".to_string(), "test-value".to_string())]) + } + + #[tokio::test] + async fn cold_miss_is_single_flight_and_wakes_waiters() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("cold"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + let CacheLookup::Wait(waiter) = cache.lookup(&key) else { + panic!("concurrent cold miss should wait"); + }; + + cache + .refresh_guard(key) + .success(values(), Duration::from_secs(300)); + + assert_eq!( + waiter + .await + .unwrap() + .expect("successful load should publish values") + .get("test.flag"), + Some("test-value") + ); + } + + #[tokio::test] + async fn cancelled_cold_load_fails_open_and_wakes_waiters() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("cancelled"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + let CacheLookup::Wait(waiter) = cache.lookup(&key) else { + panic!("concurrent cold miss should wait"); + }; + + drop(cache.refresh_guard(key.clone())); + + assert!(waiter.await.unwrap().is_none()); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + } + + #[test] + fn fresh_hit_does_not_start_refresh() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("fresh"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + cache + .refresh_guard(key.clone()) + .success(values(), Duration::from_secs(300)); + + assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); + } + + #[test] + fn only_one_stale_reader_owns_background_refresh() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("stale"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + cache + .refresh_guard(key.clone()) + .success(values(), Duration::ZERO); + + assert!(matches!( + cache.lookup(&key), + CacheLookup::Stale { + start_refresh: true, + .. + } + )); + assert!(matches!( + cache.lookup(&key), + CacheLookup::Stale { + start_refresh: false, + .. + } + )); + + cache.refresh_guard(key).backoff(); + } + + #[test] + fn failed_stale_refresh_retains_last_values_and_backs_off() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("stale-failure"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + cache + .refresh_guard(key.clone()) + .success(values(), Duration::ZERO); + assert!(matches!( + cache.lookup(&key), + CacheLookup::Stale { + start_refresh: true, + .. + } + )); + + assert_eq!( + cache.refresh_guard(key.clone()).backoff().get("test.flag"), + Some("test-value") + ); + assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); + } + + #[test] + fn failed_cold_fetch_is_negatively_cached() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("failure"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + assert!(cache.refresh_guard(key.clone()).backoff().is_empty()); + assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); + } + + #[tokio::test] + async fn caller_local_failure_promotes_a_waiter_instead_of_caching_default() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("local-failure"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + let CacheLookup::Wait(waiter) = cache.lookup(&key) else { + panic!("concurrent cold miss should wait"); + }; + + assert!(cache.refresh_guard(key.clone()).retry().is_empty()); + assert!(waiter.await.unwrap().is_none()); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + } + + #[test] + fn cache_evicts_the_least_recently_used_idle_entry() { + let cache = Arc::new(FeatureFlagCache::with_idle_capacity(2)); + let first = key("first"); + let second = key("second"); + let third = key("third"); + + for key in [&first, &second] { + assert!(matches!(cache.lookup(key), CacheLookup::Load)); + cache + .refresh_guard(key.clone()) + .success(values(), Duration::from_secs(300)); + } + assert!(matches!(cache.lookup(&first), CacheLookup::Fresh(_))); + assert!(matches!(cache.lookup(&third), CacheLookup::Load)); + + let entries = cache.lock_entries(); + assert_eq!(entries.len(), 2); + assert!(entries.contains_key(&first)); + assert!(!entries.contains_key(&second)); + assert!(entries.contains_key(&third)); + } + + #[test] + fn in_flight_overflow_shrinks_to_idle_capacity_after_completion() { + let cache = Arc::new(FeatureFlagCache::with_idle_capacity(2)); + let keys = [key("first"), key("second"), key("third")]; + + for key in &keys { + assert!(matches!(cache.lookup(key), CacheLookup::Load)); + } + assert_eq!( + cache.lock_entries().len(), + 3, + "in-flight loads must not be evicted" + ); + + for key in keys { + cache + .refresh_guard(key) + .success(values(), Duration::from_secs(300)); + } + assert_eq!(cache.lock_entries().len(), 2); + } + + #[test] + fn response_ttl_defaults_clamps_and_jitters() { + for (supplied, upper_bound) in [ + (None, DEFAULT_TTL), + (Some(-1), DEFAULT_TTL), + (Some(1), MIN_TTL), + (Some(900), Duration::from_secs(900)), + (Some(86_400), MAX_TTL), + ] { + let ttl = response_ttl(supplied); + assert!(ttl >= MIN_TTL); + assert!(ttl <= upper_bound); + } + } +} diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs new file mode 100644 index 00000000..cb8fe29e --- /dev/null +++ b/src/feature_flags/mod.rs @@ -0,0 +1,747 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Fail-open feature flags supplied by connector-service. +//! +//! The resolver reuses the kernel's authenticated HTTP client and shares one +//! process-wide cache across sessions. A cold miss performs one blocking +//! request; fresh entries make no request; stale entries are returned +//! immediately while one background refresh runs. Values remain opaque until +//! an individual feature explicitly opts in to interpreting one. + +mod cache; + +use std::collections::HashMap; +use std::fmt; +use std::sync::Arc; +use std::time::Duration; + +use reqwest::Url; +use serde::Deserialize; + +use crate::client::DatabricksHttpClient; +use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::klog::warn; + +use cache::{global_cache, response_ttl, CacheKey, CacheLookup, FeatureFlagCache}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); + +/// Driver family understood by the connector-service feature-flag endpoint. +/// +/// The wire values intentionally mirror +/// `GetFeatureFlagsRequest.ClientType` in connector-service. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ClientType { + Go, + NodeJs, + Python, +} + +impl ClientType { + const fn as_endpoint_segment(self) -> &'static str { + match self { + Self::Go => "GOLANG", + Self::NodeJs => "NODEJS", + Self::Python => "PYTHON", + } + } +} + +impl fmt::Display for ClientType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_endpoint_segment()) + } +} + +/// Identity used when evaluating driver feature flags. +/// +/// The version is sent as one URL path segment and is also part of the +/// process-cache key, so different driver releases never share evaluations. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ClientIdentity { + client_type: ClientType, + version: String, +} + +impl ClientIdentity { + pub fn new(client_type: ClientType, version: impl Into) -> Self { + Self { + client_type, + version: version.into(), + } + } + + pub fn client_type(&self) -> ClientType { + self.client_type + } + + pub fn version(&self) -> &str { + &self.version + } +} + +/// Immutable name/value snapshot returned by feature-flag resolution. +/// +/// Connector-service is responsible for returning only flags that are safe for +/// the identified driver. The kernel deliberately does not interpret values at +/// this layer; each feature owns its flag name, parsing, and fallback policy. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FeatureFlagValues { + values: Arc>, +} + +impl FeatureFlagValues { + fn from_entries(entries: impl IntoIterator) -> Self { + Self { + values: Arc::new(entries.into_iter().collect()), + } + } + + /// Return the opaque value associated with `name` in this snapshot. + pub fn get(&self, name: &str) -> Option<&str> { + self.values.get(name).map(String::as_str) + } + + /// Iterate over all names and opaque values in this snapshot. + pub fn iter(&self) -> impl Iterator { + self.values + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + } + + /// Return the number of flags in this snapshot. + pub fn len(&self) -> usize { + self.values.len() + } + + /// Return whether this snapshot contains no flags. + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } +} + +/// Resolves allowlisted driver feature flags through connector-service. +/// +/// Resolution always fails open: request and response failures are logged and +/// produce defaults (or the last successfully cached values). +#[derive(Clone)] +pub struct FeatureFlagResolver { + host: String, + http_client: Arc, + cache: Arc, + org_id: Option, +} + +impl fmt::Debug for FeatureFlagResolver { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FeatureFlagResolver") + // Do not recursively render DatabricksHttpClient: its custom + // headers may contain caller-supplied secrets. + .field("host", &self.host) + .field("org_id", &self.org_id) + .finish_non_exhaustive() + } +} + +impl FeatureFlagResolver { + pub fn new(host: impl Into, http_client: Arc) -> Self { + Self::with_cache(host, http_client, global_cache()) + } + + fn with_cache( + host: impl Into, + http_client: Arc, + cache: Arc, + ) -> Self { + let org_id = http_client.config().org_id.clone(); + Self { + host: canonical_host(host.into()), + http_client, + cache, + org_id, + } + } + + pub async fn resolve(&self, identity: &ClientIdentity) -> FeatureFlagValues { + if identity.version().trim().is_empty() { + return FeatureFlagValues::default(); + } + + let key = CacheKey::new(&self.host, self.org_id.clone(), identity.clone()); + + loop { + match self.cache.lookup(&key) { + CacheLookup::Fresh(values) => return values, + CacheLookup::Wait(receiver) => match receiver.await { + Ok(Some(values)) => return values, + // The leader failed for caller-local reasons or was + // cancelled. Retry lookup so one healthy waiter becomes + // the next leader instead of accepting a poisoned default. + Ok(None) | Err(_) => continue, + }, + CacheLookup::Load => { + return self.fetch_and_complete(key.clone(), identity.clone()).await; + } + CacheLookup::Stale { + values, + start_refresh, + } => { + if start_refresh { + self.refresh_in_background(key.clone(), identity.clone()); + } + return values; + } + } + } + } + + async fn fetch_and_complete( + &self, + key: CacheKey, + identity: ClientIdentity, + ) -> FeatureFlagValues { + let guard = self.cache.refresh_guard(key); + match self.fetch(&identity).await { + Ok(result) => guard.success(result.values, response_ttl(result.ttl_seconds)), + Err(error) => { + warn!( + client_type = %identity.client_type(), + error = %error, + "feature-flag fetch failed; using defaults or stale values" + ); + if should_backoff(&error, self.request_timeout()) { + guard.backoff() + } else { + guard.retry() + } + } + } + } + + fn refresh_in_background(&self, key: CacheKey, identity: ClientIdentity) { + let resolver = self.clone(); + let guard = self.cache.refresh_guard(key); + tokio::spawn(async move { + match resolver.fetch(&identity).await { + Ok(result) => { + guard.success(result.values, response_ttl(result.ttl_seconds)); + } + Err(error) => { + warn!( + client_type = %identity.client_type(), + error = %error, + "background feature-flag refresh failed; retaining stale values" + ); + if should_backoff(&error, resolver.request_timeout()) { + guard.backoff(); + } else { + guard.retry(); + } + } + } + }); + } + + fn request_timeout(&self) -> Duration { + REQUEST_TIMEOUT.min(self.http_client.config().read_timeout) + } + + async fn fetch(&self, identity: &ClientIdentity) -> Result { + let url = build_endpoint(&self.host, identity)?; + let request = self + .http_client + .inner() + .get(url) + .timeout(self.request_timeout()) + .build() + .map_err(|error| { + Error::invalid_argument() + .message(format!("failed to build feature-flag request: {error}")) + })?; + + let response = self.http_client.execute_feature_flags(request).await?; + let response: FeatureFlagsResponse = response.json().await.map_err(|error| { + let kernel_error = if error.is_timeout() { + Error::timeout() + } else { + Error::data_loss() + }; + kernel_error.message(format!( + "failed to decode connector-service feature-flag response: {error}" + )) + })?; + + let entries = response.flags.into_iter().filter_map(|entry| { + let name = entry.name?; + let value = entry.value?; + (!name.is_empty()).then_some((name, value)) + }); + Ok(FetchResult { + values: FeatureFlagValues::from_entries(entries), + ttl_seconds: response.ttl_seconds, + }) + } +} + +/// Only endpoint-wide failures receive process-wide negative backoff. Auth, +/// network/proxy, configuration, and cancellation errors can differ between +/// sessions sharing the same host and must not poison healthy callers. A +/// timeout is shared only when the resolver reached its full endpoint cap; +/// shorter caller-configured deadlines remain local to that session. +fn should_backoff(error: &Error, request_timeout: Duration) -> bool { + match error.http_status { + Some(401 | 403) => false, + Some(_) => true, + None => match error.code { + ErrorCode::Timeout => request_timeout >= REQUEST_TIMEOUT, + ErrorCode::ResourceExhausted | ErrorCode::Unavailable => true, + _ => false, + }, + } +} + +fn canonical_host(host: String) -> String { + let Ok(mut url) = Url::parse(&host) else { + return host; + }; + url.set_path(""); + url.set_query(None); + url.set_fragment(None); + url.as_str().trim_end_matches('/').to_string() +} + +fn build_endpoint(host: &str, identity: &ClientIdentity) -> Result { + let mut url = Url::parse(host).map_err(|error| { + Error::invalid_argument().message(format!( + "invalid workspace host for feature-flag request: {error}" + )) + })?; + let mut path = url.path_segments_mut().map_err(|_| { + Error::invalid_argument() + .message("workspace host cannot be used as a base URL for feature-flag requests") + })?; + path.clear(); + path.extend([ + "api", + "2.0", + "connector-service", + "feature-flags", + identity.client_type().as_endpoint_segment(), + identity.version(), + ]); + drop(path); + Ok(url) +} + +struct FetchResult { + values: FeatureFlagValues, + ttl_seconds: Option, +} + +#[derive(Deserialize)] +struct FeatureFlagsResponse { + #[serde(default)] + flags: Vec, + ttl_seconds: Option, +} + +#[derive(Deserialize)] +struct FeatureFlagEntry { + name: Option, + value: Option, +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use serde_json::json; + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + use super::*; + use crate::auth::pat::PersonalAccessToken; + use crate::client::{build_retry_configs, HttpClientConfig, RetryConfig}; + + #[test] + fn connector_client_types_use_proto_wire_values() { + assert_eq!(ClientType::Go.to_string(), "GOLANG"); + assert_eq!(ClientType::NodeJs.to_string(), "NODEJS"); + assert_eq!(ClientType::Python.to_string(), "PYTHON"); + } + + #[test] + fn feature_flag_values_preserve_opaque_values() { + let values = FeatureFlagValues::from_entries([ + ("boolean-looking".to_string(), " TRUE ".to_string()), + ("json-looking".to_string(), "{\"enabled\":1}".to_string()), + ("boolean-looking".to_string(), "last-value".to_string()), + ]); + + assert_eq!(values.len(), 2); + assert_eq!(values.get("boolean-looking"), Some("last-value")); + assert_eq!(values.get("json-looking"), Some("{\"enabled\":1}")); + assert_eq!(values.get("missing"), None); + assert_eq!(values.iter().count(), 2); + } + + #[test] + fn endpoint_uses_api_prefix_and_encodes_version_as_one_segment() { + let identity = ClientIdentity::new(ClientType::Go, "1.2.3/beta"); + let url = build_endpoint("https://workspace.example.com", &identity).unwrap(); + + assert_eq!( + url.as_str(), + "https://workspace.example.com/api/2.0/connector-service/feature-flags/GOLANG/1.2.3%2Fbeta" + ); + } + + #[test] + fn canonicalizes_host_for_endpoint_and_cache_identity() { + assert_eq!( + canonical_host("https://workspace.example.com/old?o=42".to_string()), + "https://workspace.example.com" + ); + } + + #[test] + fn request_timeout_respects_a_shorter_client_timeout() { + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig { + read_timeout: Duration::from_millis(250), + ..HttpClientConfig::default() + }, + build_retry_configs(&RetryConfig::default(), &HashMap::new()), + ) + .unwrap(), + ); + let resolver = FeatureFlagResolver::with_cache( + "https://workspace.example.com", + http_client, + Arc::new(FeatureFlagCache::default()), + ); + + assert_eq!(resolver.request_timeout(), Duration::from_millis(250)); + } + + #[test] + fn shared_backoff_is_limited_to_endpoint_wide_failures() { + let timeout = Error::timeout(); + + assert!(should_backoff(&timeout, REQUEST_TIMEOUT)); + assert!(!should_backoff(&timeout, Duration::from_millis(250))); + assert!(!should_backoff(&Error::network_error(), REQUEST_TIMEOUT)); + assert!(!should_backoff(&Error::data_loss(), REQUEST_TIMEOUT)); + } + + #[tokio::test] + async fn feature_flag_transport_timeout_preserves_timeout_code() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3", + )) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(100))) + .expect(1) + .mount(&server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig { + read_timeout: Duration::from_millis(20), + ..HttpClientConfig::default() + }, + HashMap::new(), + ) + .unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + let resolver = FeatureFlagResolver::with_cache( + server.uri(), + http_client, + Arc::new(FeatureFlagCache::default()), + ); + + let error = resolver + .fetch(&ClientIdentity::new(ClientType::Go, "1.2.3")) + .await + .err() + .expect("delayed response should exceed the request timeout"); + assert_eq!(error.code, ErrorCode::Timeout); + assert!(!should_backoff(&error, resolver.request_timeout())); + } + + #[tokio::test] + async fn fetches_once_then_serves_the_process_cache() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3", + )) + .and(header("authorization", "Bearer test-token")) + .and(header("x-databricks-org-id", "42")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "flags": [{ + "name": "example.boolean-looking", + "value": " TRUE " + }, { + "name": "example.json-looking", + "value": "{\"enabled\":1}" + }, { + "name": "", + "value": "ignored" + }, { + "name": "example.missing-value" + }], + "ttl_seconds": 300 + }))) + .expect(1) + .mount(&server) + .await; + + let config = HttpClientConfig { + org_id: Some("42".to_string()), + ..HttpClientConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + config, + build_retry_configs(&RetryConfig::default(), &HashMap::new()), + ) + .unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + let resolver = FeatureFlagResolver::with_cache( + server.uri(), + http_client, + Arc::new(FeatureFlagCache::default()), + ); + let identity = ClientIdentity::new(ClientType::Go, "1.2.3"); + + for _ in 0..2 { + let values = resolver.resolve(&identity).await; + assert_eq!(values.len(), 2); + assert_eq!(values.get("example.boolean-looking"), Some(" TRUE ")); + assert_eq!(values.get("example.json-looking"), Some("{\"enabled\":1}")); + } + } + + #[tokio::test] + async fn stale_values_are_served_while_one_background_refresh_updates_cache() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3", + )) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_millis(50)) + .set_body_json(json!({ + "flags": [{"name": "example.flag", "value": "new"}], + "ttl_seconds": 300 + })), + ) + .expect(1) + .mount(&server) + .await; + + let identity = ClientIdentity::new(ClientType::Go, "1.2.3"); + let cache = Arc::new(FeatureFlagCache::default()); + let key = CacheKey::new(canonical_host(server.uri()), None, identity.clone()); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + cache.refresh_guard(key).success( + FeatureFlagValues::from_entries([("example.flag".to_string(), "stale".to_string())]), + Duration::ZERO, + ); + + let http_client = Arc::new( + DatabricksHttpClient::new(HttpClientConfig::default(), HashMap::new()).unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + let resolver = FeatureFlagResolver::with_cache(server.uri(), http_client, cache); + + let first = resolver.resolve(&identity).await; + assert_eq!(first.get("example.flag"), Some("stale")); + + // Readers arriving while the request is in flight keep receiving the + // stale snapshot without starting more background requests. + let (second, third) = + tokio::join!(resolver.resolve(&identity), resolver.resolve(&identity)); + assert_eq!(second.get("example.flag"), Some("stale")); + assert_eq!(third.get("example.flag"), Some("stale")); + + let refreshed = tokio::time::timeout(Duration::from_secs(2), async { + loop { + let values = resolver.resolve(&identity).await; + if values.get("example.flag") == Some("new") { + break values; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("background refresh should update the cached value"); + assert_eq!(refreshed.get("example.flag"), Some("new")); + server.verify().await; + } + + #[tokio::test] + async fn skips_connector_service_when_version_is_empty_or_blank() { + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&RetryConfig::default(), &HashMap::new()), + ) + .unwrap(), + ); + let resolver = FeatureFlagResolver::with_cache( + "not a URL", + http_client, + Arc::new(FeatureFlagCache::default()), + ); + + for version in ["", " \t"] { + assert!(resolver + .resolve(&ClientIdentity::new(ClientType::Go, version)) + .await + .is_empty()); + } + } + + #[tokio::test] + async fn connector_failure_is_not_retried_and_fails_open() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path( + "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3", + )) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount(&server) + .await; + + // A hand-built map remains safe: the connector-service policy is + // private and cannot be overridden through the public retry enums. + let http_client = Arc::new( + DatabricksHttpClient::new(HttpClientConfig::default(), HashMap::new()).unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + let resolver = FeatureFlagResolver::with_cache( + server.uri(), + http_client, + Arc::new(FeatureFlagCache::default()), + ); + + for _ in 0..2 { + assert!(resolver + .resolve(&ClientIdentity::new(ClientType::Go, "1.2.3")) + .await + .is_empty()); + } + } + + #[tokio::test] + async fn auth_failure_does_not_poison_a_healthy_session() { + let server = MockServer::start().await; + let endpoint = "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3"; + Mock::given(method("GET")) + .and(path(endpoint)) + .and(header("authorization", "Bearer expired-token")) + .respond_with(ResponseTemplate::new(401)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(endpoint)) + .and(header("authorization", "Bearer healthy-token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "flags": [{"name": "example.flag", "value": "opaque"}], + "ttl_seconds": 300 + }))) + .expect(1) + .mount(&server) + .await; + + let cache = Arc::new(FeatureFlagCache::default()); + let resolver = |token: &str| { + let http_client = Arc::new( + DatabricksHttpClient::new(HttpClientConfig::default(), HashMap::new()).unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new(token))); + FeatureFlagResolver::with_cache(server.uri(), http_client, Arc::clone(&cache)) + }; + let identity = ClientIdentity::new(ClientType::Go, "1.2.3"); + + assert!(resolver("expired-token") + .resolve(&identity) + .await + .is_empty()); + assert_eq!( + resolver("healthy-token") + .resolve(&identity) + .await + .get("example.flag"), + Some("opaque") + ); + } + + #[tokio::test] + async fn malformed_response_does_not_poison_a_healthy_session() { + let server = MockServer::start().await; + let endpoint = "/api/2.0/connector-service/feature-flags/GOLANG/1.2.3"; + Mock::given(method("GET")) + .and(path(endpoint)) + .and(header("authorization", "Bearer proxied-token")) + .respond_with(ResponseTemplate::new(200).set_body_string("not JSON")) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(endpoint)) + .and(header("authorization", "Bearer healthy-token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "flags": [{"name": "example.flag", "value": "opaque"}], + "ttl_seconds": 300 + }))) + .expect(1) + .mount(&server) + .await; + + let cache = Arc::new(FeatureFlagCache::default()); + let resolver = |token: &str| { + let http_client = Arc::new( + DatabricksHttpClient::new(HttpClientConfig::default(), HashMap::new()).unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new(token))); + FeatureFlagResolver::with_cache(server.uri(), http_client, Arc::clone(&cache)) + }; + let identity = ClientIdentity::new(ClientType::Go, "1.2.3"); + + assert!(resolver("proxied-token") + .resolve(&identity) + .await + .is_empty()); + assert_eq!( + resolver("healthy-token") + .resolve(&identity) + .await + .get("example.flag"), + Some("opaque") + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index b386628b..afd7a555 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,6 +115,7 @@ pub mod telemetry; pub mod types; pub mod config; +pub mod feature_flags; pub mod kernel_error; pub mod metadata_v0; pub mod result_stream; @@ -130,6 +131,7 @@ pub use config::{ AuthConfig, ConnectionConfig, DefaultOpts, HttpConfig, LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; +pub use feature_flags::{ClientIdentity, ClientType, FeatureFlagResolver, FeatureFlagValues}; pub use kernel_error::{Error, ErrorCode, Result}; /// The `tracing` target string stamped on every kernel log event. /// Binding crates (pyo3, napi) reference this constant directly so the From 5efbcc71f2fd9e7cfd7e678a18a001f6b0c098b0 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 23 Sep 2026 00:57:35 +0000 Subject: [PATCH 2/6] test(feature-flags): cover all SAFE value types Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/feature_flags/mod.rs | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index cb8fe29e..a5385d16 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -96,8 +96,10 @@ impl ClientIdentity { /// Immutable name/value snapshot returned by feature-flag resolution. /// /// Connector-service is responsible for returning only flags that are safe for -/// the identified driver. The kernel deliberately does not interpret values at -/// this layer; each feature owns its flag name, parsing, and fallback policy. +/// the identified driver. Each value is the JSON-serialized SAFE value (for +/// example, `true`, `42`, `"value"`, or `["a","b"]`). The kernel deliberately +/// preserves that JSON text without interpreting it; each feature owns its flag +/// name, expected type, parsing, and fallback policy. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FeatureFlagValues { values: Arc>, @@ -110,7 +112,7 @@ impl FeatureFlagValues { } } - /// Return the opaque value associated with `name` in this snapshot. + /// Return the JSON-serialized SAFE value associated with `name`. pub fn get(&self, name: &str) -> Option<&str> { self.values.get(name).map(String::as_str) } @@ -487,7 +489,7 @@ mod tests { } #[tokio::test] - async fn fetches_once_then_serves_the_process_cache() { + async fn fetches_all_safe_value_types_once_then_serves_the_process_cache() { let server = MockServer::start().await; Mock::given(method("GET")) .and(path( @@ -497,11 +499,23 @@ mod tests { .and(header("x-databricks-org-id", "42")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "flags": [{ - "name": "example.boolean-looking", - "value": " TRUE " + "name": "example.boolean", + "value": "true" }, { - "name": "example.json-looking", - "value": "{\"enabled\":1}" + "name": "example.int32", + "value": "-2147483648" + }, { + "name": "example.int64", + "value": "9223372036854775807" + }, { + "name": "example.double", + "value": "3.141592653589793" + }, { + "name": "example.string", + "value": "\"hello\"" + }, { + "name": "example.string-list", + "value": "[\"a\",\"b\"]" }, { "name": "", "value": "ignored" @@ -535,9 +549,13 @@ mod tests { for _ in 0..2 { let values = resolver.resolve(&identity).await; - assert_eq!(values.len(), 2); - assert_eq!(values.get("example.boolean-looking"), Some(" TRUE ")); - assert_eq!(values.get("example.json-looking"), Some("{\"enabled\":1}")); + assert_eq!(values.len(), 6); + assert_eq!(values.get("example.boolean"), Some("true")); + assert_eq!(values.get("example.int32"), Some("-2147483648")); + assert_eq!(values.get("example.int64"), Some("9223372036854775807")); + assert_eq!(values.get("example.double"), Some("3.141592653589793")); + assert_eq!(values.get("example.string"), Some("\"hello\"")); + assert_eq!(values.get("example.string-list"), Some("[\"a\",\"b\"]")); } } From 58bc42f105e687690b0c3a8b6695cb8b38538c50 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 24 Sep 2026 21:17:32 +0000 Subject: [PATCH 3/6] fix(feature-flags): align cache policy with design Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/feature_flags/cache.rs | 60 +++++++++++++++------------- src/feature_flags/mod.rs | 81 +++++++++++++++++++++++++------------- 2 files changed, 85 insertions(+), 56 deletions(-) diff --git a/src/feature_flags/cache.rs b/src/feature_flags/cache.rs index 044f6b67..9af2fdcc 100644 --- a/src/feature_flags/cache.rs +++ b/src/feature_flags/cache.rs @@ -32,9 +32,8 @@ use tokio::sync::oneshot; use super::{ClientIdentity, FeatureFlagValues}; const DEFAULT_TTL: Duration = Duration::from_secs(15 * 60); -const MIN_TTL: Duration = Duration::from_secs(60); -const MAX_TTL: Duration = Duration::from_secs(60 * 60); -const NEGATIVE_TTL: Duration = Duration::from_secs(60); +pub(crate) const NEGATIVE_TTL: Duration = Duration::from_secs(60); +pub(crate) const TRANSIENT_NEGATIVE_TTL: Duration = Duration::from_secs(5); const MAX_IDLE_CACHE_ENTRIES: usize = 256; const MIN_JITTER_FACTOR: f64 = 0.9; const MAX_JITTER_FACTOR: f64 = 1.0; @@ -68,6 +67,11 @@ struct CacheEntry { last_access: u64, } +enum CacheCompletion { + Success(FeatureFlagValues, Duration), + Backoff(Duration), +} + pub(crate) enum CacheLookup { Fresh(FeatureFlagValues), Stale { @@ -151,11 +155,7 @@ impl FeatureFlagCache { } } - fn complete_cached( - &self, - key: CacheKey, - result: Option<(FeatureFlagValues, Duration)>, - ) -> FeatureFlagValues { + fn complete_cached(&self, key: CacheKey, result: CacheCompletion) -> FeatureFlagValues { let now = Instant::now(); let last_access = self.next_access(); let protected_key = key.clone(); @@ -170,17 +170,17 @@ impl FeatureFlagCache { entry.last_access = last_access; let values = match result { - Some((values, ttl)) => { + CacheCompletion::Success(values, ttl) => { entry.values = Some(values.clone()); entry.refresh_after = now + ttl; values } - None => { + CacheCompletion::Backoff(ttl) => { let values = entry.values.clone().unwrap_or_default(); entry.values = Some(values.clone()); // Cache cold failures and back off stale refresh failures so a // connector-service outage cannot create a connection storm. - entry.refresh_after = now + NEGATIVE_TTL; + entry.refresh_after = now + ttl; values } }; @@ -263,13 +263,19 @@ impl RefreshGuard { pub(crate) fn success(mut self, values: FeatureFlagValues, ttl: Duration) -> FeatureFlagValues { self.cache.complete_cached( self.key.take().expect("refresh guard is armed"), - Some((values, ttl)), + CacheCompletion::Success(values, ttl), ) } - pub(crate) fn backoff(mut self) -> FeatureFlagValues { - self.cache - .complete_cached(self.key.take().expect("refresh guard is armed"), None) + pub(crate) fn backoff(self) -> FeatureFlagValues { + self.backoff_for(NEGATIVE_TTL) + } + + pub(crate) fn backoff_for(mut self, ttl: Duration) -> FeatureFlagValues { + self.cache.complete_cached( + self.key.take().expect("refresh guard is armed"), + CacheCompletion::Backoff(ttl), + ) } pub(crate) fn retry(mut self) -> FeatureFlagValues { @@ -299,14 +305,12 @@ pub(crate) fn response_ttl(ttl_seconds: Option) -> Duration { let seconds = ttl_seconds .filter(|seconds| *seconds > 0) .map(|seconds| seconds as f64) - .unwrap_or(DEFAULT_TTL.as_secs_f64()) - .clamp(MIN_TTL.as_secs_f64(), MAX_TTL.as_secs_f64()); - // Within the supported TTL band, refresh no later than the server's - // advertised TTL. Downward-only jitter spreads callers without extending - // a rollout or kill-switch lifetime; the clamps still protect the endpoint - // from pathological sub-minute or multi-hour values. + .unwrap_or(DEFAULT_TTL.as_secs_f64()); + // Refresh no later than the server's advertised TTL. Downward-only jitter + // spreads callers without extending a rollout or kill-switch lifetime. + // Missing and non-positive TTLs use the reference-driver default. let jitter = rand::rng().random_range(MIN_JITTER_FACTOR..=MAX_JITTER_FACTOR); - Duration::from_secs_f64((seconds * jitter).clamp(MIN_TTL.as_secs_f64(), MAX_TTL.as_secs_f64())) + Duration::from_secs_f64(seconds * jitter) } #[cfg(test)] @@ -495,17 +499,17 @@ mod tests { } #[test] - fn response_ttl_defaults_clamps_and_jitters() { - for (supplied, upper_bound) in [ + fn response_ttl_honors_server_values_with_downward_jitter() { + for (supplied, advertised) in [ (None, DEFAULT_TTL), (Some(-1), DEFAULT_TTL), - (Some(1), MIN_TTL), + (Some(1), Duration::from_secs(1)), (Some(900), Duration::from_secs(900)), - (Some(86_400), MAX_TTL), + (Some(86_400), Duration::from_secs(86_400)), ] { let ttl = response_ttl(supplied); - assert!(ttl >= MIN_TTL); - assert!(ttl <= upper_bound); + assert!(ttl >= advertised.mul_f64(MIN_JITTER_FACTOR)); + assert!(ttl <= advertised); } } } diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index a5385d16..70ed7fca 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -34,7 +34,10 @@ use crate::client::DatabricksHttpClient; use crate::kernel_error::{Error, ErrorCode, Result}; use crate::klog::warn; -use cache::{global_cache, response_ttl, CacheKey, CacheLookup, FeatureFlagCache}; +use cache::{ + global_cache, response_ttl, CacheKey, CacheLookup, FeatureFlagCache, NEGATIVE_TTL, + TRANSIENT_NEGATIVE_TTL, +}; const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); @@ -78,9 +81,10 @@ pub struct ClientIdentity { impl ClientIdentity { pub fn new(client_type: ClientType, version: impl Into) -> Self { + let version = version.into(); Self { client_type, - version: version.into(), + version: version.trim().to_owned(), } } @@ -224,10 +228,10 @@ impl FeatureFlagResolver { error = %error, "feature-flag fetch failed; using defaults or stale values" ); - if should_backoff(&error, self.request_timeout()) { - guard.backoff() - } else { - guard.retry() + match failure_backoff(&error, self.request_timeout()) { + Some(ttl) if ttl == NEGATIVE_TTL => guard.backoff(), + Some(ttl) => guard.backoff_for(ttl), + None => guard.retry(), } } } @@ -247,10 +251,16 @@ impl FeatureFlagResolver { error = %error, "background feature-flag refresh failed; retaining stale values" ); - if should_backoff(&error, resolver.request_timeout()) { - guard.backoff(); - } else { - guard.retry(); + match failure_backoff(&error, resolver.request_timeout()) { + Some(ttl) if ttl == NEGATIVE_TTL => { + guard.backoff(); + } + Some(ttl) => { + guard.backoff_for(ttl); + } + None => { + guard.retry(); + } } } } @@ -298,19 +308,21 @@ impl FeatureFlagResolver { } } -/// Only endpoint-wide failures receive process-wide negative backoff. Auth, -/// network/proxy, configuration, and cancellation errors can differ between -/// sessions sharing the same host and must not poison healthy callers. A -/// timeout is shared only when the resolver reached its full endpoint cap; -/// shorter caller-configured deadlines remain local to that session. -fn should_backoff(error: &Error, request_timeout: Duration) -> bool { +/// Endpoint failures receive the full negative-cache interval. Ambiguous +/// transport failures (DNS, TLS, proxy, connection refusal, or a shorter +/// caller timeout) receive a brief interval: this bounds request storms while +/// limiting how long one session's transport problem can affect another. +/// Auth, malformed-response, configuration, and cancellation failures remain +/// uncached because they are caller-local. +fn failure_backoff(error: &Error, request_timeout: Duration) -> Option { match error.http_status { - Some(401 | 403) => false, - Some(_) => true, + Some(401 | 403) => None, + Some(_) => Some(NEGATIVE_TTL), None => match error.code { - ErrorCode::Timeout => request_timeout >= REQUEST_TIMEOUT, - ErrorCode::ResourceExhausted | ErrorCode::Unavailable => true, - _ => false, + ErrorCode::Timeout if request_timeout >= REQUEST_TIMEOUT => Some(NEGATIVE_TTL), + ErrorCode::Timeout | ErrorCode::NetworkError => Some(TRANSIENT_NEGATIVE_TTL), + ErrorCode::ResourceExhausted | ErrorCode::Unavailable => Some(NEGATIVE_TTL), + _ => None, }, } } @@ -402,7 +414,8 @@ mod tests { #[test] fn endpoint_uses_api_prefix_and_encodes_version_as_one_segment() { - let identity = ClientIdentity::new(ClientType::Go, "1.2.3/beta"); + let identity = ClientIdentity::new(ClientType::Go, " 1.2.3/beta\t"); + assert_eq!(identity.version(), "1.2.3/beta"); let url = build_endpoint("https://workspace.example.com", &identity).unwrap(); assert_eq!( @@ -441,13 +454,22 @@ mod tests { } #[test] - fn shared_backoff_is_limited_to_endpoint_wide_failures() { + fn failure_backoff_distinguishes_endpoint_and_transport_failures() { let timeout = Error::timeout(); - assert!(should_backoff(&timeout, REQUEST_TIMEOUT)); - assert!(!should_backoff(&timeout, Duration::from_millis(250))); - assert!(!should_backoff(&Error::network_error(), REQUEST_TIMEOUT)); - assert!(!should_backoff(&Error::data_loss(), REQUEST_TIMEOUT)); + assert_eq!( + failure_backoff(&timeout, REQUEST_TIMEOUT), + Some(NEGATIVE_TTL) + ); + assert_eq!( + failure_backoff(&timeout, Duration::from_millis(250)), + Some(TRANSIENT_NEGATIVE_TTL) + ); + assert_eq!( + failure_backoff(&Error::network_error(), REQUEST_TIMEOUT), + Some(TRANSIENT_NEGATIVE_TTL) + ); + assert_eq!(failure_backoff(&Error::data_loss(), REQUEST_TIMEOUT), None); } #[tokio::test] @@ -485,7 +507,10 @@ mod tests { .err() .expect("delayed response should exceed the request timeout"); assert_eq!(error.code, ErrorCode::Timeout); - assert!(!should_backoff(&error, resolver.request_timeout())); + assert_eq!( + failure_backoff(&error, resolver.request_timeout()), + Some(TRANSIENT_NEGATIVE_TTL) + ); } #[tokio::test] From 09974299a8f2adf3ad7d77ed35ce8e9f9324aa44 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 24 Sep 2026 21:41:46 +0000 Subject: [PATCH 4/6] fix(feature-flags): back off stale local failures Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/feature_flags/cache.rs | 28 ++++++++++++++++++++++++++-- src/feature_flags/mod.rs | 5 +++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/feature_flags/cache.rs b/src/feature_flags/cache.rs index 9af2fdcc..e104b405 100644 --- a/src/feature_flags/cache.rs +++ b/src/feature_flags/cache.rs @@ -198,8 +198,8 @@ impl FeatureFlagCache { /// Complete a caller-local failure without publishing a process-wide /// negative result. Cold entries are removed and waiters retry so a bad /// token, proxy, or cancelled leader cannot suppress a healthy session. - /// A stale entry keeps its last good values and becomes immediately - /// refreshable by the next caller. + /// A stale entry keeps its last good values and briefly backs off so a + /// persistent caller-local failure cannot start a refresh on every read. fn complete_uncached_failure(&self, key: CacheKey) -> FeatureFlagValues { let mut entries = self.lock_entries(); let Some(mut entry) = entries.remove(&key) else { @@ -210,6 +210,7 @@ impl FeatureFlagCache { if entry.values.is_some() { entry.refreshing = false; + entry.refresh_after = Instant::now() + TRANSIENT_NEGATIVE_TTL; entry.last_access = self.next_access(); entries.insert(key.clone(), entry); self.trim_entries(&mut entries, self.idle_capacity, Some(&key)); @@ -453,6 +454,29 @@ mod tests { assert!(matches!(cache.lookup(&key), CacheLookup::Load)); } + #[test] + fn caller_local_stale_failure_retains_values_and_briefly_backs_off() { + let cache = Arc::new(FeatureFlagCache::default()); + let key = key("local-stale-failure"); + assert!(matches!(cache.lookup(&key), CacheLookup::Load)); + cache + .refresh_guard(key.clone()) + .success(values(), Duration::ZERO); + assert!(matches!( + cache.lookup(&key), + CacheLookup::Stale { + start_refresh: true, + .. + } + )); + + assert_eq!( + cache.refresh_guard(key.clone()).retry().get("test.flag"), + Some("test-value") + ); + assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); + } + #[test] fn cache_evicts_the_least_recently_used_idle_entry() { let cache = Arc::new(FeatureFlagCache::with_idle_capacity(2)); diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index 70ed7fca..97762482 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -312,8 +312,9 @@ impl FeatureFlagResolver { /// transport failures (DNS, TLS, proxy, connection refusal, or a shorter /// caller timeout) receive a brief interval: this bounds request storms while /// limiting how long one session's transport problem can affect another. -/// Auth, malformed-response, configuration, and cancellation failures remain -/// uncached because they are caller-local. +/// Auth, malformed-response, configuration, and cancellation failures do not +/// publish a cold negative result because they are caller-local. If a prior +/// value exists, the cache retains it with a brief stale-refresh cooldown. fn failure_backoff(error: &Error, request_timeout: Duration) -> Option { match error.http_status { Some(401 | 403) => None, From b6f9a1b66f07a80b70b2fd86093f6ec07303afca Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:04:03 +0000 Subject: [PATCH 5/6] refactor(feature-flags): simplify failure backoff Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/feature_flags/mod.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index 97762482..c8662ca8 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -229,7 +229,6 @@ impl FeatureFlagResolver { "feature-flag fetch failed; using defaults or stale values" ); match failure_backoff(&error, self.request_timeout()) { - Some(ttl) if ttl == NEGATIVE_TTL => guard.backoff(), Some(ttl) => guard.backoff_for(ttl), None => guard.retry(), } @@ -252,9 +251,6 @@ impl FeatureFlagResolver { "background feature-flag refresh failed; retaining stale values" ); match failure_backoff(&error, resolver.request_timeout()) { - Some(ttl) if ttl == NEGATIVE_TTL => { - guard.backoff(); - } Some(ttl) => { guard.backoff_for(ttl); } From b673a61ef69036a6431fa6f22476be2d054a354c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:08:17 +0000 Subject: [PATCH 6/6] fix(feature-flags): remove unused backoff wrapper Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/feature_flags/cache.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/feature_flags/cache.rs b/src/feature_flags/cache.rs index e104b405..b00503c8 100644 --- a/src/feature_flags/cache.rs +++ b/src/feature_flags/cache.rs @@ -268,10 +268,6 @@ impl RefreshGuard { ) } - pub(crate) fn backoff(self) -> FeatureFlagValues { - self.backoff_for(NEGATIVE_TTL) - } - pub(crate) fn backoff_for(mut self, ttl: Duration) -> FeatureFlagValues { self.cache.complete_cached( self.key.take().expect("refresh guard is armed"), @@ -405,7 +401,7 @@ mod tests { } )); - cache.refresh_guard(key).backoff(); + cache.refresh_guard(key).backoff_for(NEGATIVE_TTL); } #[test] @@ -425,7 +421,10 @@ mod tests { )); assert_eq!( - cache.refresh_guard(key.clone()).backoff().get("test.flag"), + cache + .refresh_guard(key.clone()) + .backoff_for(NEGATIVE_TTL) + .get("test.flag"), Some("test-value") ); assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); @@ -436,7 +435,10 @@ mod tests { let cache = Arc::new(FeatureFlagCache::default()); let key = key("failure"); assert!(matches!(cache.lookup(&key), CacheLookup::Load)); - assert!(cache.refresh_guard(key.clone()).backoff().is_empty()); + assert!(cache + .refresh_guard(key.clone()) + .backoff_for(NEGATIVE_TTL) + .is_empty()); assert!(matches!(cache.lookup(&key), CacheLookup::Fresh(_))); }