Skip to content

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

fix(rust-sdk): batched callers check their deadline; reject empty entity embeddings (#2789)

LJ πŸ₯₯🌴055b129d8917
diff --git a/rust/sdk/cocoindex/src/batched.rs b/rust/sdk/cocoindex/src/batched.rs
index 90505b5c..734bcbec 100644
--- a/rust/sdk/cocoindex/src/batched.rs
+++ b/rust/sdk/cocoindex/src/batched.rs
@@ -201,14 +201,20 @@ where
}
/// Await one item's result from a batcher: a whole-batch error, then the
-/// item's own error from a split sub-batch.
+/// item's own error from a split sub-batch. The batch runs without its
+/// callers' deadlines, so the caller checks its own once the result is back
+/// (like Python's batched runner): an expired caller gets
+/// [`Error::DeadlineExceeded`], not the result.
async fn run_item<In, Out>(batcher: &FunctionBatcher<In, Out>, call: BatchCall<In>) -> Result<Out>
where
In: Clone + Send + 'static,
Out: Send + 'static,
{
+ let caller_deadline = call.ctx.deadline;
let item_result = batcher.run(call).await.map_err(Error::from)?;
- item_result.map_err(Error::from)
+ let output = item_result.map_err(Error::from)?;
+ caller_deadline.check().map_err(Error::from)?;
+ Ok(output)
}
/// A single-item interface over a batch-shaped async function.
diff --git a/rust/sdk/cocoindex/src/connectors/doris.rs b/rust/sdk/cocoindex/src/connectors/doris.rs
index e0074ea2..77a6142d 100644
--- a/rust/sdk/cocoindex/src/connectors/doris.rs
+++ b/rust/sdk/cocoindex/src/connectors/doris.rs
@@ -2071,8 +2071,7 @@ mod tests {
for bad in ["db`; DROP DATABASE x; --", "", "my-db", "a b"] {
let err = DorisConnection::connect(DorisConfig::new("127.0.0.1", bad))
.await
- .err()
- .expect("rejected before connecting");
+ .expect_err("rejected before connecting");
assert!(err.to_string().contains("database name"), "{bad:?}: {err}");
}
}
diff --git a/rust/sdk/cocoindex/src/entity_resolution.rs b/rust/sdk/cocoindex/src/entity_resolution.rs
index 5279c60e..f1a2d04a 100644
--- a/rust/sdk/cocoindex/src/entity_resolution.rs
+++ b/rust/sdk/cocoindex/src/entity_resolution.rs
@@ -264,6 +264,13 @@ where
)
.await?;
let dimension = embeddings.first().map_or(0, Vec::len);
+ if dimension == 0 {
+ // Nothing to compare: the partition would see no rows and drop every
+ // entity from the result.
+ return Err(Error::engine(
+ "entity embeddings have 0 dimensions; the embedder returned empty vectors",
+ ));
+ }
let mut infos = Vec::with_capacity(entity_list.len());
let mut matrix = VectorMatrix {
dimension,
diff --git a/rust/sdk/cocoindex/tests/code_fuzz.rs b/rust/sdk/cocoindex/tests/code_fuzz.rs
new file mode 100644
index 00000000..e70cb6f0
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/code_fuzz.rs
@@ -0,0 +1,155 @@
+//! Structural matching and rendering over malformed source: truncated files,
+//! random bytes of syntax, unbalanced brackets. Matching must not panic, every
+//! match and capture must lie on char boundaries of the source with positions
+//! that agree with its byte range, and `render_match` must partition its text.
+//!
+//! Seeded, so every run checks the same inputs. Run with:
+//! `cargo test -p cocoindex --features code_match --test code_fuzz`.
+#![cfg(feature = "code_match")]
+
+use cocoindex::ops::code::{CodeAst, render_match};
+use cocoindex::resources::chunk::Chunk;
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+
+/// A language, a well-formed sample to truncate and mutate, and patterns.
+const CASES: &[(&str, &str, &[&str])] = &[
+ (
+ "python",
+ "class Greeter:\n def greet(self, name):\n prefix = \"hi ζ—₯本\"\n return prefix + name\n\ndef top(a, b=1, *args):\n return [x for x in a]\n",
+ &[r"def \NAME(\(A*\)):", r"return \X", r"\VAR = \VALUE"],
+ ),
+ (
+ "rust",
+ "pub struct S { a: u32 }\nimpl S {\n fn greet(&self, name: &str) -> String { format!(\"{name} πŸ¦€\") }\n}\nfn main() { let x = S { a: 1 }; println!(\"{}\", x.greet(\"Γ©\")); }\n",
+ &[r"fn \NAME(\(P*\))", r"let \X = \Y;", r"impl \T"],
+ ),
+ (
+ "go",
+ "package main\n\nfunc main() {\n\tx := 1\n\tif x > 0 { println(\"ok\") }\n}\n\nfunc add(a, b int) int { return a + b }\n",
+ &[r"func \N(\(P*\))", r"return \X"],
+ ),
+ (
+ "cpp",
+ "#include <cstdio>\nvoid run() { int x = 1; }\nclass A { public: int f(int y) { return y * 2; } };\n",
+ &[r"void \N(\(P*\))", r"return \X;"],
+ ),
+ (
+ "javascript",
+ "function greet(name) { return `hi ${name}`; }\nconst f = (a, b) => a + b;\nclass C { m() { return 1; } }\n",
+ &[r"function \N(\(P*\))", r"return \X;"],
+ ),
+];
+
+/// Check that `chunk` is a valid region of `source`.
+fn check_chunk(source: &str, chunk: &Chunk, context: &str) {
+ let range = chunk.range();
+ assert!(range.start <= range.end, "{context}: inverted {range:?}");
+ assert!(
+ source.get(range.clone()).is_some(),
+ "{context}: {range:?} is not on char boundaries"
+ );
+ let before = &source[..range.start];
+ assert_eq!(
+ chunk.start.char_offset,
+ before.chars().count(),
+ "{context}: char offset of {range:?}"
+ );
+ assert_eq!(
+ chunk.start.line as usize,
+ before.matches('\n').count() + 1,
+ "{context}: line of {range:?}"
+ );
+ assert_eq!(chunk.end.byte_offset, range.end, "{context}");
+}
+
+/// Malformed variants of `sample`: truncations at every few chars, and
+/// random deletions, duplications and insertions of syntax.
+fn malformed_variants(sample: &str, rng: &mut StdRng) -> Vec<String> {
+ let boundaries: Vec<usize> = sample
+ .char_indices()
+ .map(|(index, _)| index)
+ .chain([sample.len()])
+ .collect();
+ let mut out: Vec<String> = boundaries
+ .iter()
+ .step_by(7)
+ .map(|end| sample[..*end].to_string())
+ .collect();
+ const NOISE: &[&str] = &[
+ "(", ")", "{", "}", "[", "\"", "'", "`", ":", ";", "\n", "\t", "\\", "/*", "*/", "#", "Γ©",
+ "πŸ¦€", "\0",
+ ];
+ for _ in 0..40 {
+ let mut text = sample.to_string();
+ for _ in 0..rng.gen_range(1..6) {
+ let positions: Vec<usize> = text
+ .char_indices()
+ .map(|(index, _)| index)
+ .chain([text.len()])
+ .collect();
+ let at = positions[rng.gen_range(0..positions.len())];
+ match rng.gen_range(0..3) {
+ 0 => text.insert_str(at, NOISE[rng.gen_range(0..NOISE.len())]),
+ 1 => {
+ let end = positions.iter().copied().find(|p| *p > at).unwrap_or(at);
+ text.replace_range(at..end, "");
+ }
+ _ => {
+ let end = positions
+ .iter()
+ .copied()
+ .filter(|p| *p >= at)
+ .nth(rng.gen_range(0..10))
+ .unwrap_or(text.len());
+ let piece = text[at..end].to_string();
+ text.insert_str(at, &piece);
+ }
+ }
+ }
+ out.push(text);
+ }
+ out.push(String::new());
+ out.push("(".repeat(3000));
+ out
+}
+
+#[test]
+fn matching_and_rendering_survive_malformed_source() {
+ let mut rng = StdRng::seed_from_u64(0xc0de_0001);
+ let mut total_matches = 0;
+ for (language, sample, patterns) in CASES {
+ for (variant_index, source) in malformed_variants(sample, &mut rng).iter().enumerate() {
+ let ast = CodeAst::new(source.clone(), *language).unwrap();
+ for pattern in *patterns {
+ let context = format!("{language} variant {variant_index} {pattern}: {source:?}");
+ let matches = ast.matches(pattern).unwrap();
+ total_matches += matches.len();
+ for m in &matches {
+ for chunk in &m.chunks {
+ check_chunk(source, chunk, &context);
+ }
+ for (name, captures) in &m.captures {
+ for chunk in captures {
+ check_chunk(source, chunk, &format!("{context} capture {name}"));
+ }
+ }
+ let view = render_match(&ast, m);
+ let mut cursor = 0;
+ for seg in &view.segments {
+ assert_eq!(seg.rendered_start, cursor, "{context}");
+ assert!(seg.rendered_end >= seg.rendered_start, "{context}");
+ cursor = seg.rendered_end;
+ }
+ assert_eq!(cursor, view.text.chars().count(), "{context}");
+ }
+ }
+ // Splitting and term extraction of the same malformed parse.
+ for chunk in ast.split(40, None, None).unwrap() {
+ check_chunk(source, &chunk, &format!("{language} split"));
+ }
+ let _ = ast.index_terms(2);
+ }
+ }
+ assert!(total_matches > 100, "the variants must exercise matches");
+}
diff --git a/rust/sdk/cocoindex/tests/deadline.rs b/rust/sdk/cocoindex/tests/deadline.rs
index c839e0ff..50a9fa07 100644
--- a/rust/sdk/cocoindex/tests/deadline.rs
+++ b/rust/sdk/cocoindex/tests/deadline.rs
@@ -444,3 +444,37 @@ async fn use_mount_each_drains_started_siblings_on_deadline_error() {
"B's started work must drain to commit before use_mount_each returns"
);
}
+
+static BATCH_BODY_SAW_DEADLINE: AtomicBool = AtomicBool::new(true);
+
+#[cocoindex::function(batching)]
+async fn advances_clock_in_batch(
+ ctx: &cocoindex::Ctx,
+ items: Vec<i64>,
+) -> cocoindex::Result<Vec<i64>> {
+ BATCH_BODY_SAW_DEADLINE.store(ctx.has_deadline(), Ordering::SeqCst);
+ testing_advance_deadline_clock(Duration::from_secs(20));
+ Ok(items)
+}
+
+/// Like Python's `test_batched_runner_body_is_deadline_isolated` and
+/// `test_batched_runner_caller_checks_deadline_after_return`: the batch body
+/// runs without its callers' deadline, and a caller whose deadline expired
+/// while the batch ran gets `DeadlineExceeded`, not the result.
+#[tokio::test]
+async fn batched_caller_checks_its_deadline_after_the_batch_returns() {
+ let _clock = TestClockGuard::new();
+ let (app, _env) = temp_app("sdk_deadline_batched_after_return").await;
+ let err = app
+ .update(|ctx| async move {
+ let scoped = ctx.with_timeout(Duration::from_secs(10));
+ advances_clock_in_batch(&scoped, 1).await
+ })
+ .await
+ .unwrap_err();
+ assert_deadline(err);
+ assert!(
+ !BATCH_BODY_SAW_DEADLINE.load(Ordering::SeqCst),
+ "the batch body must not inherit a caller's deadline"
+ );
+}
diff --git a/rust/sdk/cocoindex/tests/entity_resolution.rs b/rust/sdk/cocoindex/tests/entity_resolution.rs
index 7c14abf4..b402c905 100644
--- a/rust/sdk/cocoindex/tests/entity_resolution.rs
+++ b/rust/sdk/cocoindex/tests/entity_resolution.rs
@@ -557,3 +557,119 @@ async fn matrix_search_matches_the_reference_resolution() {
assert_eq!(resolved.to_map(), expected);
}
+
+#[tokio::test]
+async fn a_single_entity_is_its_own_canonical_without_a_resolver_call() {
+ let resolver = Arc::new(ScriptedResolver::default());
+ let result = resolve(
+ &["solo"],
+ embedder(&[("solo", &[1.0, 0.0])]),
+ resolver.clone(),
+ None,
+ ResolveOptions::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.canonical_of("solo").unwrap(), "solo");
+ assert_eq!(result.to_map().len(), 1);
+ assert!(resolver.calls().is_empty());
+}
+
+#[tokio::test]
+async fn duplicate_names_are_resolved_once() {
+ let resolver = ScriptedResolver::deciding("b", &["a"], PairDecision::matched("a"));
+ let result = resolve(
+ &["b", "a", "b", "a", "a"],
+ embedder(&[("a", &[1.0, 0.0]), ("b", &[0.99, 0.05])]),
+ resolver.clone(),
+ None,
+ ResolveOptions::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.to_map().len(), 2);
+ assert_eq!(result.canonical_of("b").unwrap(), "a");
+ assert_eq!(
+ resolver.calls(),
+ vec![("b".to_string(), vec!["a".to_string()])]
+ );
+}
+
+/// An embedder that returns no numbers would leave nothing to compare; it is
+/// an error, not a silently empty result.
+#[tokio::test]
+async fn zero_dimensional_embeddings_are_rejected() {
+ let err = resolve(
+ &["a", "b"],
+ embedder(&[("a", &[]), ("b", &[])]),
+ Arc::new(ScriptedResolver::default()),
+ None,
+ ResolveOptions::default(),
+ )
+ .await
+ .unwrap_err();
+ assert!(err.to_string().contains("0 dimensions"), "{err}");
+}
+
+#[tokio::test]
+async fn a_non_finite_embedding_is_rejected() {
+ for bad in [f32::NAN, f32::INFINITY] {
+ let vectors: Vec<(String, Vec<f32>)> = vec![
+ ("a".to_string(), vec![1.0, 0.0]),
+ ("b".to_string(), vec![bad, 0.0]),
+ ];
+ let embedder = Arc::new(ScriptedEmbedder {
+ vectors: vectors.into_iter().collect(),
+ });
+ let err = resolve(
+ &["a", "b"],
+ embedder,
+ Arc::new(ScriptedResolver::default()),
+ None,
+ ResolveOptions::default(),
+ )
+ .await
+ .unwrap_err();
+ assert!(err.to_string().contains("non-finite"), "{err}");
+ }
+}
+
+/// The result depends on the set of names, not on the order they come in.
+#[tokio::test]
+async fn resolution_does_not_depend_on_input_order() {
+ use rand::SeedableRng;
+ use rand::seq::SliceRandom;
+ let Clustered {
+ entities,
+ cluster_of,
+ } = clustered_vectors(20, 4, 30, 16);
+ let embedder = Arc::new(ScriptedEmbedder {
+ vectors: entities.iter().cloned().collect(),
+ });
+ let resolver = Arc::new(ClusterResolver { cluster_of });
+ let mut names: Vec<String> = entities.iter().map(|(name, _)| name.clone()).collect();
+ let mut rng = rand::rngs::StdRng::seed_from_u64(7);
+ let mut first = None;
+ for _ in 0..4 {
+ names.shuffle(&mut rng);
+ let (names, embedder, resolver) = (names.clone(), embedder.clone(), resolver.clone());
+ let resolved = in_update(move |ctx| async move {
+ resolve_entities(
+ &ctx,
+ names.iter(),
+ &*embedder,
+ &*resolver,
+ None,
+ ResolveOptions::default(),
+ )
+ .await
+ })
+ .await
+ .unwrap()
+ .to_map();
+ match &first {
+ None => first = Some(resolved),
+ Some(first) => assert_eq!(&resolved, first),
+ }
+ }
+}
diff --git a/rust/sdk/cocoindex/tests/pipeline.rs b/rust/sdk/cocoindex/tests/pipeline.rs
index d90dde40..c7e61154 100644
--- a/rust/sdk/cocoindex/tests/pipeline.rs
+++ b/rust/sdk/cocoindex/tests/pipeline.rs
@@ -1796,7 +1796,10 @@ mod batched_test {
DEADLINE_BLOCKER_RELEASE.notify_one();
let blocked = blocker.await.unwrap();
- assert_eq!(expired?, 1);
+ // The body ran without the expired caller's deadline, but that
+ // caller checks its own once the result is back, like Python's
+ // batched runner.
+ assert!(expired.unwrap_err().is_deadline_exceeded());
assert_eq!(ordinary?, 2);
assert_eq!(blocked?, 0);
Ok(())
@@ -3841,3 +3844,59 @@ mod mount_macros_file_state {
assert_eq!(std::fs::read(out.join("a.txt")).unwrap(), b"two");
}
}
+
+/// Ids from `generate_id` and a shared `IdGenerator` stay unique when many
+/// components allocate them concurrently, and each `(component, dep)` keeps
+/// its id on the next run.
+#[tokio::test]
+async fn ids_are_unique_under_concurrency_and_stable_across_runs() {
+ let (app, _dir) = temp_app("ids_concurrent").await;
+
+ async fn allocate(app: &App) -> Vec<(u32, u32, u64, u64, uuid::Uuid)> {
+ app.update(|ctx| async move {
+ let per_component = (0..40u32).map(|component| {
+ let ctx = ctx.clone();
+ async move {
+ ctx.scope(&format!("c{component}"), move |ctx| async move {
+ let id_gen = IdGenerator::new();
+ let id_gen = &id_gen;
+ ctx.map(0..25u32, |dep| {
+ let ctx = &ctx;
+ async move {
+ let id = generate_id(ctx, &dep).await?;
+ // A per-dep dependency keeps the ordinal of
+ // each call independent of arrival order.
+ let from_gen = id_gen.next_id(ctx, &dep).await?;
+ let uuid = generate_uuid(ctx, &dep).await?;
+ Ok((component, dep, id, from_gen, uuid))
+ }
+ })
+ .await
+ })
+ .await
+ }
+ });
+ let nested = futures::future::try_join_all(per_component).await?;
+ Ok(nested.into_iter().flatten().collect::<Vec<_>>())
+ })
+ .await
+ .unwrap()
+ }
+
+ let first = allocate(&app).await;
+ assert_eq!(first.len(), 40 * 25);
+ let ids: std::collections::HashSet<u64> = first
+ .iter()
+ .flat_map(|(_, _, id, from_gen, _)| [*id, *from_gen])
+ .collect();
+ assert_eq!(ids.len(), 2 * 40 * 25, "every id is distinct");
+ let uuids: std::collections::HashSet<uuid::Uuid> =
+ first.iter().map(|(_, _, _, _, uuid)| *uuid).collect();
+ assert_eq!(uuids.len(), 40 * 25, "every uuid is distinct");
+
+ let mut second = allocate(&app).await;
+ let mut first = first;
+ first.sort();
+ second.sort();
+ assert_eq!(first, second, "ids are stable across runs");
+}