Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

fix(rust-sdk): split an ApiEmbedder batch that one input makes the provider reject (#2768)

LJ πŸ₯₯🌴5e777c7bbd8a
diff --git a/rust/sdk/cocoindex/src/ops/api.rs b/rust/sdk/cocoindex/src/ops/api.rs
index e19130c3..558c060d 100644
--- a/rust/sdk/cocoindex/src/ops/api.rs
+++ b/rust/sdk/cocoindex/src/ops/api.rs
@@ -60,6 +60,47 @@ fn is_retryable_status(status: reqwest::StatusCode) -> bool {
RETRYABLE_STATUSES.contains(&status.as_u16()) || status.is_server_error()
}
+/// Statuses about who we are or what we asked for (credentials, payment,
+/// permissions, an unknown model): batch composition cannot change them
+/// (Python's `_GLOBAL_LITELLM_EXCEPTION_CLASSES`).
+const GLOBAL_FAILURE_STATUSES: &[u16] = &[401, 402, 403, 404];
+
+/// Why a request failed, so a batch body can tell the failures a smaller
+/// batch may avoid from those it cannot.
+enum RequestFailure {
+ /// The request bound or the caller's deadline expired. Never split: each
+ /// half would take a fresh bound against a backend already too slow.
+ TimedOut(Error),
+ /// A failure that fails every request alike (see
+ /// [`GLOBAL_FAILURE_STATUSES`]).
+ Global(Error),
+ /// Anything else: a rejected request, a transport error, an undecodable
+ /// response. A smaller request may pass where this one did not.
+ Other(Error),
+}
+
+impl RequestFailure {
+ /// The error a batch body returns: [`Error::retry_with_smaller_batch`]
+ /// for a failure a smaller batch may avoid, like Python's
+ /// `LiteLLMEmbedder._embed`.
+ fn into_batch_error(self) -> Error {
+ match self {
+ RequestFailure::Other(err) => Error::retry_with_smaller_batch(err),
+ RequestFailure::TimedOut(err) | RequestFailure::Global(err) => err,
+ }
+ }
+}
+
+impl From<RequestFailure> for Error {
+ fn from(failure: RequestFailure) -> Self {
+ match failure {
+ RequestFailure::TimedOut(err)
+ | RequestFailure::Global(err)
+ | RequestFailure::Other(err) => err,
+ }
+ }
+}
+
/// Shared HTTP configuration of the three clients in this module.
#[derive(Clone)]
struct Endpoint {
@@ -102,30 +143,27 @@ impl Endpoint {
ctx: Option<&Ctx>,
build: impl Fn() -> reqwest::RequestBuilder,
what: &str,
- ) -> Result<reqwest::Response> {
+ ) -> std::result::Result<reqwest::Response, RequestFailure> {
let timeout = ctx
.and_then(Ctx::remaining_deadline)
.map_or(self.timeout, |remaining| remaining.min(self.timeout));
let deadline = Instant::now() + timeout;
let timed_out = || {
- if let Some(ctx) = ctx {
- ctx.check_cancellation()?;
- }
- Err(Error::engine(format!(
- "{what} did not complete within {timeout:?}"
- )))
+ let err = ctx
+ .and_then(|ctx| ctx.check_cancellation().err())
+ .unwrap_or_else(|| {
+ Error::engine(format!("{what} did not complete within {timeout:?}"))
+ });
+ Err(RequestFailure::TimedOut(err))
};
let mut backoff = RETRY_INITIAL_BACKOFF;
loop {
// The permit covers one attempt only: a sleeping retry holds no
// slot (cf. Python's `_inflight_permit`).
let permit = match &self.inflight {
- Some(semaphore) => Some(
- semaphore
- .acquire()
- .await
- .map_err(|_| Error::engine("in-flight request limiter closed"))?,
- ),
+ Some(semaphore) => Some(semaphore.acquire().await.map_err(|_| {
+ RequestFailure::Other(Error::engine("in-flight request limiter closed"))
+ })?),
None => None,
};
let remaining = deadline.saturating_duration_since(Instant::now());
@@ -143,7 +181,12 @@ impl Endpoint {
let status = resp.status();
if !is_retryable_status(status) {
let body = resp.text().await.unwrap_or_default();
- return Err(Error::engine(format!("{what} failed ({status}): {body}")));
+ let err = Error::engine(format!("{what} failed ({status}): {body}"));
+ return Err(if GLOBAL_FAILURE_STATUSES.contains(&status.as_u16()) {
+ RequestFailure::Global(err)
+ } else {
+ RequestFailure::Other(err)
+ });
}
resp.headers()
.get(reqwest::header::RETRY_AFTER)
@@ -152,7 +195,11 @@ impl Endpoint {
.map(Duration::from_secs)
}
Ok(Err(e)) if e.is_connect() || e.is_request() => None,
- Ok(Err(e)) => return Err(Error::engine(format!("{what} failed: {e}"))),
+ Ok(Err(e)) => {
+ return Err(RequestFailure::Other(Error::engine(format!(
+ "{what} failed: {e}"
+ ))));
+ }
};
let delay = retry_after.unwrap_or(backoff).min(RETRY_MAX_BACKOFF);
if Instant::now() + delay >= deadline {
@@ -209,10 +256,14 @@ async fn embed_api_scheduled(
embedder: ScheduledApiEmbedder,
input_type: Option<String>,
) -> Result<Vec<Vec<f32>>> {
- embedder
+ // A failure a smaller request may avoid (a provider's payload cap, one
+ // rejected input) halves the batch, down to the one text it belongs to.
+ let response = embedder
.0
- .request_embeddings(None, texts, input_type.as_deref())
+ .fetch_embeddings(&texts, input_type.as_deref())
.await
+ .map_err(RequestFailure::into_batch_error)?;
+ embeddings_in_input_order(response.data, texts.len())
}
impl ApiEmbedder {
@@ -248,7 +299,12 @@ impl ApiEmbedder {
/// Bound each embedding request, retries included. Defaults to 10 minutes;
/// raise it for a slow endpoint, since one request carries up to 64 texts.
+ ///
+ /// # Panics
+ ///
+ /// If `timeout` is zero: every request would expire before it is sent.
pub fn with_timeout(mut self, timeout: Duration) -> Self {
+ assert!(!timeout.is_zero(), "timeout must be positive");
self.endpoint.timeout = timeout;
self
}
@@ -256,7 +312,15 @@ impl ApiEmbedder {
/// Cap how many requests this embedder keeps open against the backend at
/// once. Uncapped by default; useful for self-hosted endpoints that reject
/// bursts with 429s. The cap is shared by all clones of this embedder.
+ ///
+ /// # Panics
+ ///
+ /// If `max_inflight_requests` is zero: no request could ever be sent.
pub fn with_max_inflight_requests(mut self, max_inflight_requests: usize) -> Self {
+ assert!(
+ max_inflight_requests > 0,
+ "max_inflight_requests must be positive"
+ );
self.endpoint.inflight = Some(Arc::new(Semaphore::new(max_inflight_requests)));
self
}
@@ -301,18 +365,19 @@ impl ApiEmbedder {
/// batching: the path for code outside a CocoIndex update, such as
/// embedding a search query.
pub async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {
- self.request_embeddings(None, texts, None).await
+ if texts.is_empty() {
+ return Ok(Vec::new());
+ }
+ let response = self.fetch_embeddings(&texts, None).await?;
+ embeddings_in_input_order(response.data, texts.len())
}
- async fn request_embeddings(
+ /// Send one `/embeddings` request for `texts` and decode the response.
+ async fn fetch_embeddings(
&self,
- ctx: Option<&Ctx>,
- texts: Vec<String>,
+ texts: &[String],
input_type: Option<&str>,
- ) -> Result<Vec<Vec<f32>>> {
- if texts.is_empty() {
- return Ok(Vec::new());
- }
+ ) -> std::result::Result<EmbeddingResponse, RequestFailure> {
let url = self.endpoint.url("embeddings");
let mut body = json!({ "model": self.model, "input": texts });
if let Some(dimensions) = self.dimensions {
@@ -324,7 +389,7 @@ impl ApiEmbedder {
let resp = self
.endpoint
.send_with_retry(
- ctx,
+ None,
|| {
self.endpoint
.authorize(self.endpoint.client.post(&url).json(&body))
@@ -332,11 +397,11 @@ impl ApiEmbedder {
"embedding request",
)
.await?;
- let parsed: EmbeddingResponse = resp
- .json()
- .await
- .map_err(|e| Error::engine(format!("embedding response decode failed: {e}")))?;
- embeddings_in_input_order(parsed.data, texts.len())
+ resp.json().await.map_err(|e| {
+ RequestFailure::Other(Error::engine(format!(
+ "embedding response decode failed: {e}"
+ )))
+ })
}
/// The embedding dimension, discovered by embedding a probe text and
@@ -484,7 +549,12 @@ impl ApiTranscriber {
/// Bound each transcription request, retries included. Defaults to 10
/// minutes; raise it for long audio, since one request carries a whole file.
+ ///
+ /// # Panics
+ ///
+ /// If `timeout` is zero: every request would expire before it is sent.
pub fn with_timeout(mut self, timeout: Duration) -> Self {
+ assert!(!timeout.is_zero(), "timeout must be positive");
self.endpoint.timeout = timeout;
self
}
diff --git a/rust/sdk/cocoindex/tests/ops_api.rs b/rust/sdk/cocoindex/tests/ops_api.rs
index a2bc33f9..90b5b3f6 100644
--- a/rust/sdk/cocoindex/tests/ops_api.rs
+++ b/rust/sdk/cocoindex/tests/ops_api.rs
@@ -847,3 +847,347 @@ async fn api_embedder_orders_batch_results_by_index() {
.unwrap();
assert_eq!(out, vec![vec![1.0], vec![2.0]]);
}
+
+/// An `/embeddings` server that rejects every request carrying `poison` with
+/// `status` and otherwise answers like [`LengthEmbeddings`].
+struct RejectsPoison(u16);
+
+impl Respond for RejectsPoison {
+ fn respond(&self, req: &Request) -> ResponseTemplate {
+ let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap();
+ let has_poison = body["input"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|text| text.as_str() == Some("poison"));
+ if has_poison {
+ ResponseTemplate::new(self.0).set_body_string("input rejected")
+ } else {
+ LengthEmbeddings.respond(req)
+ }
+ }
+}
+
+/// Embed `texts` concurrently in one update and return each text's result as
+/// `Ok(vector)` or `Err(message)`.
+async fn embed_all(
+ embedder: ApiEmbedder,
+ texts: Vec<String>,
+) -> Vec<std::result::Result<Vec<f32>, String>> {
+ in_update("api_embed_all", move |ctx| async move {
+ Ok(
+ join_all(texts.into_iter().map(|text| embedder.embed(&ctx, text)))
+ .await
+ .into_iter()
+ .map(|result| result.map_err(|err| err.to_string()))
+ .collect::<Vec<_>>(),
+ )
+ })
+ .await
+ .unwrap()
+}
+
+fn texts_with_poison_at(poison: usize, len: usize) -> Vec<String> {
+ (0..len)
+ .map(|index| {
+ if index == poison {
+ "poison".to_string()
+ } else {
+ format!("text-{index}")
+ }
+ })
+ .collect()
+}
+
+/// Like Python's `LiteLLMEmbedder._embed`: a request one input makes the
+/// provider reject is halved down to that input, so only its caller fails.
+#[tokio::test]
+async fn api_embedder_isolates_a_rejected_input_by_splitting_the_batch() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(RejectsPoison(400))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model").with_base_url(server.uri());
+ let texts = texts_with_poison_at(17, 40);
+
+ let results = embed_all(embedder, texts.clone()).await;
+ for (text, result) in texts.iter().zip(&results) {
+ if text == "poison" {
+ let err = result.as_ref().unwrap_err();
+ assert!(err.contains("input rejected"), "{err}");
+ } else {
+ assert_eq!(result.as_ref().unwrap(), &vec![text.len() as f32]);
+ }
+ }
+ let bodies = request_bodies(&server).await;
+ assert!(
+ bodies
+ .iter()
+ .any(|body| input_count(body) == 1 && body["input"][0] == "poison"),
+ "the poison input should end up in a request of its own"
+ );
+}
+
+/// A credentials, permission or unknown-model failure fails every request
+/// alike, so the batch is not split (Python's global litellm errors).
+#[tokio::test]
+async fn api_embedder_does_not_split_on_a_global_failure() {
+ for status in [401, 403, 404] {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(ResponseTemplate::new(status).set_body_string("no access"))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model").with_base_url(server.uri());
+ let texts: Vec<String> = (0..20).map(|index| format!("text-{index}")).collect();
+
+ let results = embed_all(embedder, texts).await;
+ assert!(results.iter().all(Result::is_err));
+ let bodies = request_bodies(&server).await;
+ assert_eq!(
+ bodies.iter().map(input_count).sum::<usize>(),
+ 20,
+ "status {status}: no input should be sent twice"
+ );
+ }
+}
+
+/// A batch that exhausts its timeout is not split either: each half would
+/// take a fresh timeout against a backend that is already too slow.
+#[tokio::test]
+async fn api_embedder_does_not_split_a_timed_out_batch() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_delay(Duration::from_secs(5))
+ .set_body_json(json!({"data": []})),
+ )
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model")
+ .with_base_url(server.uri())
+ .with_timeout(Duration::from_millis(300));
+ let texts: Vec<String> = (0..10).map(|index| format!("text-{index}")).collect();
+
+ let started = Instant::now();
+ let results = embed_all(embedder, texts).await;
+ assert!(started.elapsed() < Duration::from_secs(4));
+ for result in &results {
+ let err = result.as_ref().unwrap_err();
+ assert!(err.contains("did not complete within"), "{err}");
+ }
+ let bodies = request_bodies(&server).await;
+ assert_eq!(bodies.iter().map(input_count).sum::<usize>(), 10);
+}
+
+/// An undecodable response is split like a rejected request; at size one the
+/// caller sees the decode error.
+#[tokio::test]
+async fn api_embedder_reports_a_malformed_response() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(ResponseTemplate::new(200).set_body_string("{\"data\": [{\"embed"))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model").with_base_url(server.uri());
+
+ let results = embed_all(embedder.clone(), vec!["a".into(), "b".into()]).await;
+ for result in &results {
+ let err = result.as_ref().unwrap_err();
+ assert!(err.contains("decode failed"), "{err}");
+ }
+ let err = embedder.embed_batch(vec!["a".into()]).await.unwrap_err();
+ assert!(err.to_string().contains("decode failed"), "{err}");
+}
+
+/// A response with fewer vectors than inputs fails the request with a clear
+/// message instead of misaligning vectors with texts.
+#[tokio::test]
+async fn api_embedder_rejects_a_partial_response() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "data": [{"index": 0, "embedding": [1.0]}]
+ })))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model").with_base_url(server.uri());
+
+ let err = embedder
+ .embed_batch(vec!["a".into(), "b".into()])
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("returned 1 vectors for 2 inputs"),
+ "{err}"
+ );
+
+ // Duplicate indices are rejected too.
+ server.reset().await;
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "data": [{"index": 0, "embedding": [1.0]}, {"index": 0, "embedding": [2.0]}]
+ })))
+ .mount(&server)
+ .await;
+ let err = embedder
+ .embed_batch(vec!["a".into(), "b".into()])
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("duplicate or out-of-range"),
+ "{err}"
+ );
+}
+
+/// A server error is retried, and `Retry-After` sets the wait before the
+/// next attempt.
+#[tokio::test]
+async fn api_embedder_waits_for_retry_after_before_retrying() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ struct FailsTwice(AtomicUsize);
+ impl Respond for FailsTwice {
+ fn respond(&self, _: &Request) -> ResponseTemplate {
+ match self.0.fetch_add(1, Ordering::SeqCst) {
+ 0 => ResponseTemplate::new(503).insert_header("retry-after", "1"),
+ 1 => ResponseTemplate::new(429).insert_header("retry-after", "0"),
+ _ => ResponseTemplate::new(200).set_body_json(json!({
+ "data": [{"embedding": [3.0]}]
+ })),
+ }
+ }
+ }
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(FailsTwice(AtomicUsize::new(0)))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model").with_base_url(server.uri());
+
+ let started = Instant::now();
+ let out = embedder.embed_batch(vec!["x".into()]).await.unwrap();
+ assert_eq!(out, vec![vec![3.0]]);
+ assert!(started.elapsed() >= Duration::from_millis(950));
+ assert_eq!(server.received_requests().await.unwrap().len(), 3);
+}
+
+/// A `Retry-After` beyond the request's timeout fails at once rather than
+/// sleeping past the bound.
+#[tokio::test]
+async fn api_embedder_gives_up_when_retry_after_exceeds_the_timeout() {
+ let Some(server) = mock_server().await else {
+ return;
+ };
+ Mock::given(method("POST"))
+ .and(path("/embeddings"))
+ .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "3600"))
+ .mount(&server)
+ .await;
+ let embedder = ApiEmbedder::new("fake-model")
+ .with_base_url(server.uri())
+ .with_timeout(Duration::from_secs(5));
+
+ let started = Instant::now();
+ let err = embedder.embed_batch(vec!["x".into()]).await.unwrap_err();
+ assert!(started.elapsed() < Duration::from_secs(2), "{err}");
+ assert!(err.to_string().contains("did not complete within"), "{err}");
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
+
+/// A refused connection is retried until the timeout, then reported.
+#[tokio::test]
+async fn api_embedder_retries_a_refused_connection_until_the_timeout() {
+ // Bind and drop a listener: the port is then (almost surely) closed.
+ let port = std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let embedder = ApiEmbedder::new("fake-model")
+ .with_base_url(format!("http://127.0.0.1:{port}"))
+ .with_timeout(Duration::from_millis(1500));
+
+ let started = Instant::now();
+ let err = embedder.embed_batch(vec!["x".into()]).await.unwrap_err();
+ let elapsed = started.elapsed();
+ assert!(elapsed >= Duration::from_millis(900), "{elapsed:?}: {err}");
+ assert!(elapsed < Duration::from_secs(4), "{elapsed:?}: {err}");
+ assert!(err.to_string().contains("did not complete within"), "{err}");
+}
+
+/// The API key, timeout and in-flight cap are not part of an embedding's memo
+/// key: rotating the key must not re-embed everything.
+#[tokio::test]
+async fn api_embedder_memo_key_excludes_the_api_key() {
+ let Some(server) = length_embedding_server().await else {
+ return;
+ };
+ let tempdir = tempfile::tempdir().unwrap();
+ let app = app_in(&tempdir, "api_key_rotation").await;
+ let configs = [
+ ApiEmbedder::new("fake-model")
+ .with_base_url(server.uri())
+ .with_api_key("key-one"),
+ ApiEmbedder::new("fake-model")
+ .with_base_url(server.uri())
+ .with_api_key("key-two")
+ .with_timeout(Duration::from_secs(30))
+ .with_max_inflight_requests(2),
+ ];
+ for embedder in configs {
+ app.update(move |ctx| async move {
+ assert_eq!(embedder.embed(&ctx, "hello").await?, vec![5.0]);
+ Ok(())
+ })
+ .await
+ .unwrap();
+ }
+ let requests = server.received_requests().await.unwrap();
+ assert_eq!(requests.len(), 1, "the second update should hit the memo");
+ assert_eq!(
+ requests[0].headers.get("authorization").unwrap(),
+ "Bearer key-one"
+ );
+
+ // The model is part of the key.
+ let other_model = ApiEmbedder::new("other-model").with_base_url(server.uri());
+ app.update(move |ctx| async move {
+ other_model.embed(&ctx, "hello").await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert_eq!(server.received_requests().await.unwrap().len(), 2);
+}
+
+#[test]
+#[should_panic(expected = "max_inflight_requests must be positive")]
+fn api_embedder_rejects_a_zero_inflight_cap() {
+ let _ = ApiEmbedder::new("fake-model").with_max_inflight_requests(0);
+}
+
+#[test]
+#[should_panic(expected = "timeout must be positive")]
+fn api_embedder_rejects_a_zero_timeout() {
+ let _ = ApiEmbedder::new("fake-model").with_timeout(Duration::ZERO);
+}