Incremental engine for long horizon agents 🌟 Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(rust-sdk): no panics on server responses and out-of-range settings (#2766)
LJ 🥥🌴9add7bfed5ef
diff --git a/rust/sdk/cocoindex/src/connectors/azure_blob.rs b/rust/sdk/cocoindex/src/connectors/azure_blob.rsindex d31e6515..248c09a3 100644--- a/rust/sdk/cocoindex/src/connectors/azure_blob.rs+++ b/rust/sdk/cocoindex/src/connectors/azure_blob.rs@@ -745,11 +745,17 @@ fn parse_token_response(body: &str, what: &str) -> Result<FreshToken> {))})?.to_string();+ // A day at most: a huge value from the server would overflow `SystemTime`+ // (here or where the renewal time is computed); renewing early is harmless.+ let max = Duration::from_secs(86_400);let expires_in = match (number("expires_in"), number("expires_on")) {- (Some(secs), _) => Duration::from_secs(secs),- (None, Some(at)) => (UNIX_EPOCH + Duration::from_secs(at))- .duration_since(SystemTime::now())- .unwrap_or_default(),+ (Some(secs), _) => Duration::from_secs(secs).min(max),+ (None, Some(at)) => UNIX_EPOCH+ .checked_add(Duration::from_secs(at))+ .map_or(max, |at| {+ at.duration_since(SystemTime::now()).unwrap_or_default()+ })+ .min(max),(None, None) => {return Err(Error::engine(format!("azure blob {what}: token response has no expires_in or expires_on"diff --git a/rust/sdk/cocoindex/src/connectors/bigquery.rs b/rust/sdk/cocoindex/src/connectors/bigquery.rsindex 336ee6e3..e12e6238 100644--- a/rust/sdk/cocoindex/src/connectors/bigquery.rs+++ b/rust/sdk/cocoindex/src/connectors/bigquery.rs@@ -285,7 +285,8 @@ impl BigQueryConnection {.map_err(|e| Error::engine(format!("bigquery: parse token response: {e}")))?;*guard = Some(CachedToken {token: token.access_token.clone(),- expires_at: Instant::now() + Duration::from_secs(token.expires_in.max(60)),+ // Clamped above too: a huge `expires_in` would overflow `Instant`.+ expires_at: Instant::now() + Duration::from_secs(token.expires_in.clamp(60, 86_400)),});Ok(token.access_token)}@@ -392,7 +393,7 @@ impl BigQueryConnection {.and_then(JsonValue::as_str).map(str::to_string)})- .unwrap_or_else(|| truncate(&text, 500));+ .unwrap_or_else(|| super::truncate_for_error(&text, 500));return Err(Error::engine(format!("bigquery: HTTP {status}: {message}")));}serde_json::from_str(&text)@@ -453,14 +454,6 @@ fn decode_cell(ty: &str, raw: JsonValue) -> JsonValue {}}-fn truncate(s: &str, max: usize) -> String {- if s.len() <= max {- s.to_string()- } else {- format!("{}…", &s[..max])- }-}-// ---------------------------------------------------------------------------// Credentials// ---------------------------------------------------------------------------diff --git a/rust/sdk/cocoindex/src/connectors/doris.rs b/rust/sdk/cocoindex/src/connectors/doris.rsindex b61db70c..db0d966b 100644--- a/rust/sdk/cocoindex/src/connectors/doris.rs+++ b/rust/sdk/cocoindex/src/connectors/doris.rs@@ -184,6 +184,16 @@ impl DorisConnection {/// port (used for DDL/DELETE) and builds an HTTP client for Stream Load. The/// `database` must already exist.pub async fn connect(config: DorisConfig) -> Result<Self> {+ for (name, value) in [+ ("retry_base_delay", config.retry_base_delay),+ ("retry_max_delay", config.retry_max_delay),+ ] {+ if !(value.is_finite() && value >= 0.0) {+ return Err(Error::engine(format!(+ "DorisConfig.{name} must be a finite number of seconds >= 0, got {value}"+ )));+ }+ }// Doris speaks the MySQL wire protocol but rejects the `SET// sql_mode=CONCAT(@@sql_mode, …)` and timezone statements sqlx issues on// connect ("Set statement doesn't support non-constant expr"). Disable@@ -1429,8 +1439,11 @@ async fn stream_load(e.message)));}- let delay = (config.retry_base_delay * 2f64.powi(attempt as i32))- .min(config.retry_max_delay);+ // Both delays are finite and >= 0 (checked in `connect`), so+ // `delay` is too, even when the doubling overflows to infinity.+ let exponent = i32::try_from(attempt).unwrap_or(i32::MAX);+ let delay =+ (config.retry_base_delay * 2f64.powi(exponent)).min(config.retry_max_delay);tracing::warn!("doris stream load attempt {} failed ({}); retrying in {:.1}s",attempt + 1,@@ -1508,7 +1521,10 @@ async fn do_stream_load(}let text = resp.text().await.map_err(transport_err)?;let result: JsonValue = serde_json::from_str(&text).map_err(|_| StreamLoadError {- message: format!("invalid stream load response: {}", truncate(&text, 200)),+ message: format!(+ "invalid stream load response: {}",+ super::truncate_for_error(&text, 200)+ ),retryable: false,})?;let load_status = result@@ -1572,14 +1588,6 @@ fn stream_load_label() -> String {format!("cocoindex_{millis}_{}", &rand[..8])}-fn truncate(s: &str, max: usize) -> String {- if s.len() <= max {- s.to_string()- } else {- format!("{}…", &s[..max])- }-}-// ---------------------------------------------------------------------------// DDL builder// ---------------------------------------------------------------------------@@ -1865,6 +1873,19 @@ fn validate_indexes(schema: &TableSchema, options: &DorisTableOptions) -> Resultmod tests {use super::*;+ #[tokio::test]+ async fn connect_rejects_a_retry_delay_that_cannot_be_slept() {+ for (base, max) in [(-1.0, 30.0), (f64::NAN, 30.0), (1.0, f64::INFINITY)] {+ let mut config = config();+ config.retry_base_delay = base;+ config.retry_max_delay = max;+ let Err(err) = DorisConnection::connect(config).await else {+ panic!("connect accepted retry delays ({base}, {max})");+ };+ assert!(err.to_string().contains("must be a finite number"), "{err}");+ }+ }+fn config() -> DorisConfig {DorisConfig::new("localhost", "testdb")}diff --git a/rust/sdk/cocoindex/src/connectors/gdrive.rs b/rust/sdk/cocoindex/src/connectors/gdrive.rsindex 2ffcd0a6..0cc009c1 100644--- a/rust/sdk/cocoindex/src/connectors/gdrive.rs+++ b/rust/sdk/cocoindex/src/connectors/gdrive.rs@@ -253,6 +253,9 @@ impl crate::memo::MemoInput for DriveFile {/// random wait of up to `2^n` × [`RETRY_BACKOFF_UNIT`]; Drive's usage-limits/// guide asks clients to do exactly that.const RETRIES: u32 = 5;+/// The longest an access token is cached, whatever `expires_in` says: a huge+/// value would overflow `Instant`, and refreshing early is harmless.+const MAX_TOKEN_TTL_SECS: u64 = 86_400;const RETRY_BACKOFF_UNIT: Duration = Duration::from_secs(1);/// A random fraction in `[0, 1)`, for the retry jitter.@@ -662,7 +665,8 @@ impl GoogleDriveClient {.json().await.map_err(|e| Error::engine(format!("parse token response: {e}")))?;- let ttl = token.expires_in.max(60);+ // Clamped above too: a huge `expires_in` would overflow `Instant`.+ let ttl = token.expires_in.clamp(60, MAX_TOKEN_TTL_SECS);*guard = Some(CachedToken {token: token.access_token.clone(),expires_at: Instant::now() + Duration::from_secs(ttl),@@ -1436,12 +1440,18 @@ fn url_decode(value: &str) -> String {while i < bytes.len() {match bytes[i] {b'+' => out.push(b' '),- b'%' if i + 2 < bytes.len() => match u8::from_str_radix(&value[i + 1..i + 3], 16) {- Ok(b) => {+ // Byte-wise: slicing the `str` could cut a multi-byte character+ // (`%aé`), and `from_str_radix` alone would take a sign (`%+1`).+ b'%' => match bytes+ .get(i + 1..i + 3)+ .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit))+ .and_then(|hex| u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok())+ {+ Some(b) => {out.push(b);i += 2;}- Err(_) => out.push(b'%'),+ None => out.push(b'%'),},b => out.push(b),}@@ -1610,7 +1620,7 @@ fn random_urlsafe(bytes: usize) -> String {/// Compare two strings in time independent of where they differ.fn constant_time_eq(a: &str, b: &str) -> bool {let (a, b) = (a.as_bytes(), b.as_bytes());- let mut diff = (a.len() ^ b.len()) as u8;+ let mut diff = u8::from(a.len() != b.len());for i in 0..a.len().max(b.len()) {diff |= a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0);}@@ -1987,6 +1997,26 @@ impl GoogleDriveSource {mod tests {use super::*;+ #[test]+ fn url_decode_handles_malformed_escapes() {+ assert_eq!(url_decode("a%20b+c"), "a b c");+ // A `%` before a multi-byte character must not slice inside it.+ assert_eq!(url_decode("%a\u{e9}"), "%a\u{e9}");+ assert_eq!(url_decode("%\u{e9}"), "%\u{e9}");+ assert_eq!(url_decode("%+1"), "% 1"); // a sign is no hex digit; `+` is a space+ assert_eq!(url_decode("%4"), "%4");+ assert_eq!(url_decode("%"), "%");+ }++ #[test]+ fn constant_time_eq_compares_lengths_exactly() {+ assert!(constant_time_eq("state", "state"));+ assert!(!constant_time_eq("state", "stat"));+ // Lengths that differ by 256 with NUL padding were once equal.+ let padded = format!("state{}", "\0".repeat(256));+ assert!(!constant_time_eq("state", &padded));+ }+#[test]fn export_mime_mapping() {assert_eq!(diff --git a/rust/sdk/cocoindex/src/connectors/mod.rs b/rust/sdk/cocoindex/src/connectors/mod.rsindex ac1b2af1..85152c0e 100644--- a/rust/sdk/cocoindex/src/connectors/mod.rs+++ b/rust/sdk/cocoindex/src/connectors/mod.rs@@ -40,3 +40,32 @@ pub mod turbopuffer;pub mod valkey;#[cfg(feature = "zvec")]pub mod zvec;++/// Cut a server's response body to at most `max` bytes for an error message,+/// on a character boundary: a body is arbitrary text, and slicing inside a+/// multi-byte character panics.+#[cfg(any(feature = "bigquery", feature = "doris", feature = "snowflake"))]+fn truncate_for_error(s: &str, max: usize) -> String {+ if s.len() <= max {+ s.to_string()+ } else {+ format!("{}…", &s[..s.floor_char_boundary(max)])+ }+}++#[cfg(all(+ test,+ any(feature = "bigquery", feature = "doris", feature = "snowflake")+))]+mod tests {+ use super::truncate_for_error;++ #[test]+ fn truncate_for_error_cuts_on_a_character_boundary() {+ assert_eq!(truncate_for_error("short", 10), "short");+ assert_eq!(truncate_for_error("abcdef", 3), "abc…");+ // "é" is two bytes; byte 2 falls inside it.+ assert_eq!(truncate_for_error("aébc", 2), "a…");+ assert_eq!(truncate_for_error("日本語", 4), "日…");+ }+}diff --git a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rsindex 59c72927..16c02e52 100644--- a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs+++ b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs@@ -646,7 +646,10 @@ impl InstancePrincipal {let mut session = self.session.lock().await;let now = chrono::Utc::now().timestamp();if let Some(current) = session.as_ref()- && now <= current.expires_at - SESSION_TOKEN_EXPIRY_MARGIN_SECS+ && now+ <= current+ .expires_at+ .saturating_sub(SESSION_TOKEN_EXPIRY_MARGIN_SECS){return Ok(current.signer.clone());}diff --git a/rust/sdk/cocoindex/src/connectors/snowflake.rs b/rust/sdk/cocoindex/src/connectors/snowflake.rsindex e07b90e9..6f65aaf6 100644--- a/rust/sdk/cocoindex/src/connectors/snowflake.rs+++ b/rust/sdk/cocoindex/src/connectors/snowflake.rs@@ -338,7 +338,7 @@ async fn send_json(request: reqwest::RequestBuilder, token: Option<&str>) -> Resif !status.is_success() {return Err(Error::engine(format!("snowflake: HTTP {status}: {}",- truncate(&text, 500)+ super::truncate_for_error(&text, 500))));}serde_json::from_str(&text)@@ -423,14 +423,6 @@ fn decode_cell(ty: &str, raw: JsonValue) -> JsonValue {}}-fn truncate(s: &str, max: usize) -> String {- if s.len() <= max {- s.to_string()- } else {- format!("{}…", &s[..max])- }-}-// ---------------------------------------------------------------------------// Schema// ---------------------------------------------------------------------------diff --git a/rust/sdk/cocoindex/src/connectors/turbopuffer.rs b/rust/sdk/cocoindex/src/connectors/turbopuffer.rsindex 25b2cfa7..9d92deef 100644--- a/rust/sdk/cocoindex/src/connectors/turbopuffer.rs+++ b/rust/sdk/cocoindex/src/connectors/turbopuffer.rs@@ -29,6 +29,7 @@ use crate::target_state::{// Connection// ---------------------------------------------------------------------------+#[derive(Clone)]struct ConnInner {http: reqwest::Client,base_url: String,@@ -67,9 +68,7 @@ impl TurbopufferConnection {/// for pointing at a mock server in tests.pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {let base_url = base_url.into().trim_end_matches('/').to_string();- let inner = Arc::get_mut(&mut self.inner)- .expect("with_base_url must be called before the connection is shared");- inner.base_url = base_url;+ Arc::make_mut(&mut self.inner).base_url = base_url;self}diff --git a/rust/sdk/cocoindex/src/memo.rs b/rust/sdk/cocoindex/src/memo.rsindex 98020793..fb48d6bd 100644--- a/rust/sdk/cocoindex/src/memo.rs+++ b/rust/sdk/cocoindex/src/memo.rs@@ -548,9 +548,11 @@ impl MemoKeyWriter<'_> {}}+#[doc(hidden)]#[derive(Clone)]pub struct MemoStateValue(Value);+#[doc(hidden)]pub struct MemoStateDecision {state: MemoStateValue,memo_valid: bool,diff --git a/rust/sdk/cocoindex/src/ops/api.rs b/rust/sdk/cocoindex/src/ops/api.rsindex 558c060d..0d66f75a 100644--- a/rust/sdk/cocoindex/src/ops/api.rs+++ b/rust/sdk/cocoindex/src/ops/api.rs@@ -48,6 +48,9 @@ const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10 * 60);const RETRY_INITIAL_BACKOFF: Duration = Duration::from_secs(1);const RETRY_MAX_BACKOFF: Duration = Duration::from_secs(30);+/// The longest timeout a request gets (about a year): a longer one, such as+/// `Duration::MAX` for "no timeout", would overflow `Instant`.+const MAX_TIMEOUT: Duration = Duration::from_secs(365 * 24 * 60 * 60);/// Statuses worth another try: a fast failure that batch composition and time/// can change (Python's `_RETRYABLE_HTTP_STATUS_CODES` plus every 5xx).const RETRYABLE_STATUSES: &[u16] = &[408, 409, 425, 429];@@ -146,7 +149,10 @@ impl Endpoint {) -> std::result::Result<reqwest::Response, RequestFailure> {let timeout = ctx.and_then(Ctx::remaining_deadline)- .map_or(self.timeout, |remaining| remaining.min(self.timeout));+ .map_or(self.timeout, |remaining| remaining.min(self.timeout))+ // `with_timeout(Duration::MAX)` means "no timeout"; adding it to+ // `Instant::now()` would overflow.+ .min(MAX_TIMEOUT);let deadline = Instant::now() + timeout;let timed_out = || {let err = ctx