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
feat(rust-sdk): Runner trait, GPU-bound local embedders, matrix entity resolution and typed chat extraction (#2718)
LJ π₯₯π΄4c9e79681f3b
diff --git a/docs/src/content/docs/ops/sentence_transformers.mdx b/docs/src/content/docs/ops/sentence_transformers.mdxindex 20be6f34..604de19d 100644--- a/docs/src/content/docs/ops/sentence_transformers.mdx+++ b/docs/src/content/docs/ops/sentence_transformers.mdx@@ -484,4 +484,4 @@ embedder = SentenceTransformerEmbedder()```-The Rust embedder always normalizes: `fastembed` L2-normalizes its output, so `normalize_embeddings` has no Rust counterpart. Python's `prompt_name` and `device` have none either: `fastembed` has no prompt registry (prepend the model's query or document prefix to the text yourself) and runs on the execution providers compiled into the binary.+The Rust embedder always normalizes: `fastembed` L2-normalizes its output, so `normalize_embeddings` has no Rust counterpart. Python's `prompt_name` has none either: `fastembed` has no prompt registry, so prepend the model's query or document prefix to the text yourself. Python's `device` is `SentenceTransformerEmbedder::load_with(name_or_path, execution_providers)`: the ONNX Runtime execution providers to try, such as `CUDAExecutionProvider::default().build()` from the `ort` crate, which the binary must enable through `ort`'s `cuda` feature; without any, the model runs on the CPU. As in Python (`runner=coco.GPU`), each batch runs under the GPU runner, so one inference runs at a time per GPU in the pool.diff --git a/rust/sdk/SHOWCASE.md b/rust/sdk/SHOWCASE.mdindex 78abb695..c6efef7d 100644--- a/rust/sdk/SHOWCASE.md+++ b/rust/sdk/SHOWCASE.md@@ -364,6 +364,25 @@ before the first GPU function runs. Python's subprocess mode and dedicated GPUthread exist for the GIL and CUDA's fork rules, which a Rust body does nothave, so there is no equivalent.+Any type implementing `cocoindex::Runner` (Python's `Runner` base class) goes+in `runner = ...`: it receives each body as a future and decides when to run+it. The value is built on the function's first call and shared by every call.++```rust+struct AtMostTwo(tokio::sync::Semaphore);++#[async_trait::async_trait]+impl cocoindex::Runner for AtMostTwo {+ async fn run(&self, body: cocoindex::RunnerBody<'_>) -> Result<cocoindex::RunnerOutput> {+ let _permit = self.0.acquire().await.map_err(|e| Error::engine(e.to_string()))?;+ body.await+ }+}++#[cocoindex::function(memo, runner = AtMostTwo(tokio::sync::Semaphore::new(2)))]+async fn summarize(_ctx: &Ctx, text: String) -> Result<String> { /* ... */ }+```+## Embed, transcribe and resolve entities with the built-in opsThe model ops use the two patterns above, so a pipeline calls them per item@@ -384,6 +403,10 @@ and gets memoization and batching from the engine, as the Python ops do under- `LlmPairResolver` memoizes each `(entity, candidates)` decision, and`resolve_entities(&ctx, names, &embedder, &resolver, ..)` embeds the namesthrough the batched path. Any `Embedder` is an `EntityEmbedder`.+- `ApiChatClient::extract::<T>(&ctx, &messages)` runs a JSON-mode chat+ completion, deserializes the answer into `T` and memoizes it by model,+ endpoint and messages: structured extraction with an LLM, without parsing+ by hand.```rustcocoindex::context_key!(static EMBEDDER: ApiEmbedder, detect_change);@@ -411,9 +434,13 @@ memoizes nothing.`SentenceTransformerEmbedder::load(name_or_path)` accepts a `fastembed`registry name, a local directory holding a sentence-transformers ONNX export,or the Hugging Face repository of such an export, like Python's-`model_name_or_path`. `fastembed` always normalizes its vectors and has no-prompt registry or device selection, so Python's `normalize_embeddings`,-`prompt_name` and `device` have no Rust counterpart.+`model_name_or_path`. Its batches, like `ImageEmbedder`'s, run under the GPU+runner, as Python's do under `runner=coco.GPU`: one inference at a time per+GPU in the pool. `load_with(name, execution_providers)` picks the ONNX Runtime+execution providers (Python's `device`), such as CUDA when the binary enables+the `ort` crate's `cuda` feature. `fastembed` always normalizes its vectors+and has no prompt registry, so Python's `normalize_embeddings` and+`prompt_name` have no Rust counterpart.## Mount processing componentsdiff --git a/rust/sdk/cocoindex/Cargo.toml b/rust/sdk/cocoindex/Cargo.tomlindex f74ef48a..83e4d8c3 100644--- a/rust/sdk/cocoindex/Cargo.toml+++ b/rust/sdk/cocoindex/Cargo.toml@@ -282,3 +282,7 @@ name = "state_store_read"harness = false# Run with: cargo bench -p cocoindex --features bench-supportrequired-features = ["bench-support"]++[[bench]]+name = "entity_resolution"+harness = falsediff --git a/rust/sdk/cocoindex/benches/entity_resolution.rs b/rust/sdk/cocoindex/benches/entity_resolution.rsnew file mode 100644index 00000000..333e3ee5--- /dev/null+++ b/rust/sdk/cocoindex/benches/entity_resolution.rs@@ -0,0 +1,207 @@+//! Benchmark of `resolve_entities` on synthetic data, the Rust counterpart of+//! `benchmarks/entity_resolution/benchmark.py`: deterministic clusters of+//! aliases whose vectors are a shared base plus small noise, isolated entities+//! far from everything, a scripted embedder and a ground-truth pair resolver.+//! It measures the similarity search and the resolution loop, not an embedder+//! or an LLM.+//!+//! Run with: cargo bench -p cocoindex --bench entity_resolution++use std::collections::HashMap;+use std::sync::Arc;++use async_trait::async_trait;+use cocoindex::{+ App, Ctx, EntityEmbedder, PairDecision, PairResolver, ResolveOptions, resolve_entities,+};+use criterion::{BenchmarkId, Criterion, SamplingMode, criterion_group, criterion_main};+use rand::rngs::StdRng;+use rand::{Rng, SeedableRng};++const DIM: usize = 384;+const SEED: u64 = 7;++struct Profile {+ label: &'static str,+ /// Sizes of the alias clusters; each cluster resolves to one canonical.+ cluster_sizes: Vec<usize>,+ /// Entities with no near neighbour.+ isolated: usize,+}++fn profiles() -> Vec<Profile> {+ vec![+ // The Python `synthetic-fast` profile: 100 groups of 4 plus 100 isolated.+ Profile {+ label: "synthetic-fast-500",+ cluster_sizes: vec![4; 100],+ isolated: 100,+ },+ // One cluster: the resolution loop and the candidate search dominate.+ Profile {+ label: "one-giant-300",+ cluster_sizes: vec![300],+ isolated: 0,+ },+ // Many entities: the all-pairs partition dominates.+ Profile {+ label: "many-components-3000",+ cluster_sizes: vec![4; 500],+ isolated: 1000,+ },+ ]+}++struct Dataset {+ entities: Vec<String>,+ canonical_of: HashMap<String, String>,+ vectors: HashMap<String, Vec<f32>>,+}++/// A standard normal sample by Box-Muller, so the benchmark needs no+/// distribution crate.+fn normal(rng: &mut StdRng) -> f32 {+ let u1: f32 = rng.gen_range(f32::EPSILON..1.0);+ let u2: f32 = rng.r#gen();+ (-2.0 * u1.ln()).sqrt() * (2.0 * std::f32::consts::PI * u2).cos()+}++fn unit(mut vec: Vec<f32>) -> Vec<f32> {+ let norm = vec.iter().map(|v| v * v).sum::<f32>().sqrt();+ for v in &mut vec {+ *v /= norm;+ }+ vec+}++fn generate(profile: &Profile) -> Dataset {+ let mut rng = StdRng::seed_from_u64(SEED);+ let mut entities = Vec::new();+ let mut canonical_of = HashMap::new();+ let mut vectors = HashMap::new();+ let mut add_cluster = |canonical: String, size: usize, rng: &mut StdRng| {+ let base = unit((0..DIM).map(|_| normal(rng)).collect());+ for alias_idx in 0..size {+ let name = if alias_idx == 0 {+ canonical.clone()+ } else {+ format!("{canonical} Alias {alias_idx:02}")+ };+ let vec = unit(+ base.iter()+ .map(|b| b + normal(rng) * 0.015 + (alias_idx as f32 + 1.0) * 0.0001)+ .collect(),+ );+ entities.push(name.clone());+ canonical_of.insert(name.clone(), canonical.clone());+ vectors.insert(name, vec);+ }+ };+ for (idx, size) in profile.cluster_sizes.iter().enumerate() {+ add_cluster(format!("Entity {idx:04}"), *size, &mut rng);+ }+ for idx in 0..profile.isolated {+ add_cluster(format!("Isolated Entity {idx:04}"), 1, &mut rng);+ }+ Dataset {+ entities,+ canonical_of,+ vectors,+ }+}++struct ScriptedEmbedder {+ vectors: HashMap<String, Vec<f32>>,+}++#[async_trait]+impl EntityEmbedder for ScriptedEmbedder {+ async fn embed_entity(&self, _ctx: &Ctx, entity: &str) -> cocoindex::Result<Vec<f32>> {+ Ok(self.vectors[entity].clone())+ }+}++/// Matches a candidate of the entity's own cluster, as the Python benchmark's+/// ground-truth resolver does.+struct GroundTruthResolver {+ canonical_of: HashMap<String, String>,+}++#[async_trait]+impl PairResolver for GroundTruthResolver {+ async fn resolve_pair(+ &self,+ _ctx: &Ctx,+ entity: &str,+ candidates: &[String],+ ) -> cocoindex::Result<PairDecision> {+ let expected = &self.canonical_of[entity];+ Ok(candidates+ .iter()+ .find(|candidate| &self.canonical_of[candidate.as_str()] == expected)+ .map_or_else(PairDecision::no_match, PairDecision::matched))+ }+}++fn bench_resolve_entities(c: &mut Criterion) {+ let runtime = tokio::runtime::Runtime::new().unwrap();+ let mut group = c.benchmark_group("resolve_entities");+ group.sampling_mode(SamplingMode::Flat);+ group.sample_size(10);+ for profile in profiles() {+ let dataset = generate(&profile);+ let embedder = Arc::new(ScriptedEmbedder {+ vectors: dataset.vectors,+ });+ let resolver = Arc::new(GroundTruthResolver {+ canonical_of: dataset.canonical_of.clone(),+ });+ let entities = Arc::new(dataset.entities);+ let dir = tempfile::tempdir().unwrap();+ let app = runtime.block_on(async {+ App::builder(&format!("entity_resolution_bench_{}", profile.label))+ .db_path(dir.path().join("lmdb"))+ .build()+ .await+ .unwrap()+ });+ let expected_groups = dataset+ .canonical_of+ .values()+ .collect::<std::collections::HashSet<_>>()+ .len();+ group.bench_with_input(+ BenchmarkId::from_parameter(profile.label),+ &profile,+ |b, _profile| {+ b.to_async(&runtime).iter(|| {+ let embedder = embedder.clone();+ let resolver = resolver.clone();+ let entities = entities.clone();+ let app = app.clone();+ async move {+ let resolved = app+ .update(move |ctx| async move {+ resolve_entities(+ &ctx,+ entities.iter(),+ embedder.as_ref(),+ resolver.as_ref(),+ None,+ ResolveOptions::default(),+ )+ .await+ })+ .await+ .unwrap();+ assert_eq!(resolved.canonicals().len(), expected_groups);+ }+ });+ },+ );+ }+ group.finish();+}++criterion_group!(benches, bench_resolve_entities);+criterion_main!(benches);diff --git a/rust/sdk/cocoindex/src/batched.rs b/rust/sdk/cocoindex/src/batched.rsindex 32e9cef7..90505b5c 100644--- a/rust/sdk/cocoindex/src/batched.rs+++ b/rust/sdk/cocoindex/src/batched.rs@@ -25,7 +25,8 @@//! each half re-run, down to single items, so that one bad input fails only//! its own caller and the rest keep their results. A `runner` (see//! [`crate::runner`]) bounds how many bodies run at once; each physical batch-//! and each retried half takes the runner's resource for the time it runs.+//! and each retried half runs under the runner, so it takes the runner's+//! resource for the time it runs.//! A batching function must not call itself recursively from its body//! because it would wait on the batcher that is already executing that body.//! [`Batched`] remains available as the lower-level explicit adapter when a@@ -45,7 +46,7 @@ use serde::de::DeserializeOwned;use crate::ctx::Ctx;use crate::error::{Error, Result};-use crate::runner::GPURunner;+use crate::runner::__run_under;type CoreResult<T> = cocoindex_utils::error::Result<T>;@@ -64,10 +65,10 @@ struct BatchCall<In> {/// Adapts a user closure `Vec<In> -> Result<Vec<Out>>` to the core batcher's/// `Runner`, with split-and-retry on [`Error::RetryWithSmallerBatch`] and an-/// optional GPU runner around every body run.+/// optional [`crate::Runner`] around every body run.struct FnRunner<In, Out> {f: BatchFn<In, Out>,- runner: Option<GPURunner>,+ runner: Option<Arc<dyn crate::Runner>>,}impl<In: Clone + Send + 'static, Out: Send + 'static> FnRunner<In, Out> {@@ -86,7 +87,7 @@ impl<In: Clone + Send + 'static, Out: Send + 'static> FnRunner<In, Out> {batch_ctx.deadline = DeadlineContext::NONE;let body = (self.f)(batch_ctx, inputs);let result = match &self.runner {- Some(runner) => runner.run(body).await,+ Some(runner) => __run_under(runner.as_ref(), body).await,None => body.await,};@@ -185,7 +186,7 @@ type ScheduledBatchers<In, Out> = Mutex<HashMap<ScheduledBatchKey, Weak<Functionfn new_batcher<In, Out>(f: BatchFn<In, Out>,- runner: Option<GPURunner>,+ runner: Option<Arc<dyn crate::Runner>>,options: BatchingOptions,) -> Arc<FunctionBatcher<In, Out>>where@@ -282,7 +283,7 @@ whereOut: Send + 'static,{options: BatchingOptions,- runner: Option<GPURunner>,+ runner: Option<Arc<dyn crate::Runner>>,batchers: ScheduledBatchers<In, Out>,code_hash: u64,}@@ -294,7 +295,11 @@ where{/// Construct the scheduler used by generated batching wrappers.#[doc(hidden)]- pub fn __new(code_hash: u64, max_batch_size: Option<usize>, runner: Option<GPURunner>) -> Self {+ pub fn __new(+ code_hash: u64,+ max_batch_size: Option<usize>,+ runner: Option<Arc<dyn crate::Runner>>,+ ) -> Self {Self {options: BatchingOptions {max_batch_size,@@ -337,7 +342,7 @@ whereif let Some(batcher) = batchers.get(&key).and_then(Weak::upgrade) {batcher} else {- let batcher = new_batcher(f, self.runner, self.options.clone());+ let batcher = new_batcher(f, self.runner.clone(), self.options.clone());batchers.insert(key, Arc::downgrade(&batcher));batcher}diff --git a/rust/sdk/cocoindex/src/entity_resolution.rs b/rust/sdk/cocoindex/src/entity_resolution.rsindex 243ba056..5279c60e 100644--- a/rust/sdk/cocoindex/src/entity_resolution.rs+++ b/rust/sdk/cocoindex/src/entity_resolution.rs@@ -1,4 +1,5 @@use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::sync::Arc;use async_trait::async_trait;use serde::{Deserialize, Serialize};@@ -145,13 +146,49 @@ impl Default for ResolveOptions {}}-#[derive(Clone)]struct EntityInfo {name: String,- normalized_vec: Vec<f32>,is_existing: bool,}+/// The entities' unit vectors, one row per entity in `EntityInfo` order,+/// stored contiguously (Python's FAISS flat index holds the same matrix).+struct VectorMatrix {+ dimension: usize,+ data: Vec<f32>,+}++impl VectorMatrix {+ fn row(&self, index: usize) -> &[f32] {+ &self.data[index * self.dimension..(index + 1) * self.dimension]+ }++ /// Cosine similarity of two rows: their dot product, as both are unit+ /// vectors.+ fn similarity(&self, a: usize, b: usize) -> f32 {+ dot(self.row(a), self.row(b))+ }+}++/// Dot product in eight lanes, so the compiler vectorizes it.+fn dot(a: &[f32], b: &[f32]) -> f32 {+ const LANES: usize = 8;+ let mut lanes = [0.0f32; LANES];+ let (a_chunks, a_tail) = a.as_chunks::<LANES>();+ let (b_chunks, b_tail) = b.as_chunks::<LANES>();+ for (x, y) in a_chunks.iter().zip(b_chunks) {+ for lane in 0..LANES {+ lanes[lane] += x[lane] * y[lane];+ }+ }+ let tail: f32 = a_tail.iter().zip(b_tail).map(|(x, y)| x * y).sum();+ lanes.iter().sum::<f32>() + tail+}++/// Fewer rows than this and the all-pairs partition runs on the caller's+/// task; from here on it is spread over blocking threads.+const PARALLEL_PARTITION_MIN_ROWS: usize = 256;+#[derive(Default)]struct ComponentEvents {pass_1: Vec<ResolutionEvent>,@@ -228,6 +265,10 @@ where.await?;let dimension = embeddings.first().map_or(0, Vec::len);let mut infos = Vec::with_capacity(entity_list.len());+ let mut matrix = VectorMatrix {+ dimension,+ data: Vec::with_capacity(entity_list.len() * dimension),+ };for (name, vec) in entity_list.iter().zip(embeddings) {if vec.len() != dimension {return Err(Error::engine(format!(@@ -235,23 +276,27 @@ wherevec.len())));}+ push_normalized(&mut matrix.data, vec)?;infos.push(EntityInfo {name: name.clone(),- normalized_vec: normalize(vec)?,is_existing: is_existing_canonical.is_some_and(|f| f(name)),});}+ let matrix = Arc::new(matrix);- let components = partition_components(&infos, options.max_distance);- let entity_map: HashMap<String, EntityInfo> = infos+ let components = partition_components(&matrix, options.max_distance).await?;+ let entity_map: HashMap<&str, usize> = infos.iter()- .map(|info| (info.name.clone(), info.clone()))+ .enumerate()+ .map(|(index, info)| (info.name.as_str(), index)).collect();// Components are disjoint and never reference each other's entities, so// resolve them concurrently (cf. Python's `asyncio.gather`). Each component// owns its local dedup/candidate-index/events and borrows the shared,- // immutable `entity_map` and `resolve_pair`.+ // immutable entities, vectors and `resolve_pair`.+ let infos = &infos;+ let matrix = &*matrix;let entity_map_ref = &entity_map;// Each component's events live outside its future, so the events a// component produced before a failure survive the cancellation of its@@ -260,33 +305,26 @@ where.iter().map(|_| ComponentEvents::default()).collect();- let component_futures =- components- .into_iter()- .zip(component_events.iter_mut())- .map(|(component, events)| {- let component_infos: Vec<EntityInfo> = component- .into_iter()- .map(|idx| infos[idx].clone())- .collect();- async move {- let mut component_dedup = BTreeMap::new();- let mut candidate_index =- CandidateIndex::new(options.max_distance, options.top_n);- resolve_component(- ctx,- &component_infos,- entity_map_ref,- &mut component_dedup,- &mut candidate_index,- options.existing_policy,- resolve_pair,- events,- )- .await?;- Ok::<_, Error>(component_dedup)- }- });+ let component_futures = components.into_iter().zip(component_events.iter_mut()).map(+ |(component, events)| async move {+ let mut component_dedup = BTreeMap::new();+ let mut candidate_index =+ CandidateIndex::new(matrix, options.max_distance, options.top_n);+ resolve_component(+ ctx,+ infos,+ &component,+ entity_map_ref,+ &mut component_dedup,+ &mut candidate_index,+ options.existing_policy,+ resolve_pair,+ events,+ )+ .await?;+ Ok::<_, Error>(component_dedup)+ },+ );// The first failure drops (cancels) the remaining components.let results = futures::future::try_join_all(component_futures).await;@@ -303,25 +341,30 @@ whereOk(ResolvedEntities { dedup })}+/// Resolve the entities at `members` (indexes into `infos`, ascending).#[allow(clippy::too_many_arguments)]async fn resolve_component<R: PairResolver + Sync>(ctx: &Ctx,infos: &[EntityInfo],- entity_map: &HashMap<String, EntityInfo>,+ members: &[usize],+ entity_map: &HashMap<&str, usize>,dedup: &mut BTreeMap<String, Option<String>>,- candidate_index: &mut CandidateIndex,+ candidate_index: &mut CandidateIndex<'_>,existing_policy: ExistingCanonicalPolicy,resolve_pair: &R,events: &mut ComponentEvents,) -> Result<()> {- let (pass_1, pass_2): (Vec<_>, Vec<_>) = match existing_policy {- ExistingCanonicalPolicy::Pinned => infos.iter().partition(|info| info.is_existing),- ExistingCanonicalPolicy::Preferred => (Vec::new(), infos.iter().collect()),+ let (pass_1, pass_2): (Vec<usize>, Vec<usize>) = match existing_policy {+ ExistingCanonicalPolicy::Pinned => {+ members.iter().partition(|index| infos[**index].is_existing)+ }+ ExistingCanonicalPolicy::Preferred => (Vec::new(), members.to_vec()),};- for info in pass_1 {+ for index in pass_1 {+ let info = &infos[index];dedup.insert(info.name.clone(), None);- candidate_index.add(info);+ candidate_index.add(index);events.pass_1.push(ResolutionEvent {entity: info.name.clone(),canonical: info.name.clone(),@@ -332,11 +375,12 @@ async fn resolve_component<R: PairResolver + Sync>(});}- for info in pass_2 {- let candidates = candidate_index.search(info, dedup);+ for index in pass_2 {+ let info = &infos[index];+ let candidates = candidate_index.search(infos, index, dedup);if candidates.is_empty() {dedup.insert(info.name.clone(), None);- candidate_index.add(info);+ candidate_index.add(index);events.pass_2.push(ResolutionEvent {entity: info.name.clone(),canonical: info.name.clone(),@@ -353,8 +397,8 @@ async fn resolve_component<R: PairResolver + Sync>(.await?;validate_pair_decision(&info.name, &candidates, &decision)?;let (canonical, repointed) =- apply_pair_decision(info, &decision, entity_map, dedup, existing_policy)?;- candidate_index.add(info);+ apply_pair_decision(infos, index, &decision, entity_map, dedup, existing_policy)?;+ candidate_index.add(index);events.pass_2.push(ResolutionEvent {entity: info.name.clone(),canonical,@@ -368,18 +412,21 @@ async fn resolve_component<R: PairResolver + Sync>(}fn apply_pair_decision(- info: &EntityInfo,+ infos: &[EntityInfo],+ index: usize,decision: &PairDecision,- entity_map: &HashMap<String, EntityInfo>,+ entity_map: &HashMap<&str, usize>,dedup: &mut BTreeMap<String, Option<String>>,existing_policy: ExistingCanonicalPolicy,) -> Result<(String, Option<String>)> {+ let info = &infos[index];let Some(matched) = &decision.matched else {dedup.insert(info.name.clone(), None);return Ok((info.name.clone(), None));};let matched_info = entity_map- .get(matched)+ .get(matched.as_str())+ .map(|matched_index| &infos[*matched_index]).ok_or_else(|| Error::engine(format!("unknown matched entity: {matched}")))?;if new_wins(info, matched_info, decision, existing_policy) {dedup.insert(info.name.clone(), None);@@ -427,39 +474,51 @@ fn validate_pair_decision(Ok(())}-#[derive(Default)]-struct CandidateIndex {- indexed: Vec<EntityInfo>,+/// The already-resolved entities of one component, searched by similarity+/// for each new entity (Python's `_CandidateIndex` over a FAISS flat index).+struct CandidateIndex<'a> {+ matrix: &'a VectorMatrix,+ /// Indexes of the entities added so far.+ indexed: Vec<usize>,max_distance: f32,top_n: usize,}-impl CandidateIndex {- fn new(max_distance: f32, top_n: usize) -> Self {+impl<'a> CandidateIndex<'a> {+ fn new(matrix: &'a VectorMatrix, max_distance: f32, top_n: usize) -> Self {Self {+ matrix,indexed: Vec::new(),max_distance,top_n,}}- fn add(&mut self, info: &EntityInfo) {- self.indexed.push(info.clone());+ fn add(&mut self, index: usize) {+ self.indexed.push(index);}- fn search(&self, info: &EntityInfo, dedup: &BTreeMap<String, Option<String>>) -> Vec<String> {+ /// The up to `top_n` canonical names of indexed entities within+ /// `max_distance` of entity `index`, best first.+ fn search(+ &self,+ infos: &[EntityInfo],+ index: usize,+ dedup: &BTreeMap<String, Option<String>>,+ ) -> Vec<String> {if self.top_n == 0 {return Vec::new();}let threshold = 1.0 - self.max_distance;+ let name = &infos[index].name;let mut scored: Vec<(f32, String)> = self.indexed.iter().filter_map(|candidate| {- let score = cosine(&info.normalized_vec, &candidate.normalized_vec);- (score >= threshold).then(|| (score, chain_walk(dedup, &candidate.name)))+ let score = self.matrix.similarity(index, *candidate);+ (score >= threshold).then(|| (score, chain_walk(dedup, &infos[*candidate].name)))})- .filter(|(_, name)| name != &info.name)+ .filter(|(_, candidate)| candidate != name).collect();scored.sort_by(|(a_score, a_name), (b_score, b_name)| {b_score.total_cmp(a_score).then_with(|| a_name.cmp(b_name))@@ -478,29 +537,88 @@ impl CandidateIndex {}}-fn partition_components(infos: &[EntityInfo], max_distance: f32) -> Vec<Vec<usize>> {- let n = infos.len();+/// Connected components of the graph with an edge between every pair of+/// entities within `max_distance` (Python's `_partition_components`): a+/// superset of any candidate pair the resolution loop can surface, so+/// entities of different components never meet. Each component lists its+/// members ascending; components are ordered by their first member.+///+/// Every pair is compared, so the work is spread over blocking threads, each+/// taking every k-th row (rows get shorter as they go, so a stride balances+/// them); the caller's task only joins the edges.+async fn partition_components(+ matrix: &Arc<VectorMatrix>,+ max_distance: f32,+) -> Result<Vec<Vec<usize>>> {+ let n = matrix.data.len() / matrix.dimension.max(1);if n == 0 {- return Vec::new();+ return Ok(Vec::new());}+ let threshold = 1.0 - max_distance;+ let num_workers = if n < PARALLEL_PARTITION_MIN_ROWS {+ 1+ } else {+ std::thread::available_parallelism().map_or(1, |p| p.get())+ };let mut parent: Vec<usize> = (0..n).collect();- for i in 0..n {- for j in (i + 1)..n {- if cosine(&infos[i].normalized_vec, &infos[j].normalized_vec) >= 1.0 - max_distance {- let ri = find(&mut parent, i);- let rj = find(&mut parent, j);- if ri != rj {- parent[ri] = rj;- }+ if num_workers == 1 {+ for (i, j) in similar_pairs(matrix, 0, 1, threshold) {+ union(&mut parent, i, j);+ }+ } else {+ let workers = (0..num_workers).map(|worker| {+ let matrix = matrix.clone();+ tokio::task::spawn_blocking(move || {+ similar_pairs(&matrix, worker, num_workers, threshold)+ })+ });+ for edges in futures::future::join_all(workers).await {+ let edges =+ edges.map_err(|e| Error::engine(format!("entity partition task panicked: {e}")))?;+ for (i, j) in edges {+ union(&mut parent, i, j);}}}- let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();+ // Keyed by the component's first (smallest) member, so the order does+ // not depend on which member became the root.+ let mut groups: BTreeMap<usize, Vec<usize>> = BTreeMap::new();for i in 0..n {let root = find(&mut parent, i);- groups.entry(infos[root].name.clone()).or_default().push(i);+ groups.entry(root).or_default().push(i);+ }+ let mut components: Vec<Vec<usize>> = groups.into_values().collect();+ components.sort_by_key(|members| members[0]);+ Ok(components)+}++/// The pairs `(i, j)`, `i < j`, with similarity at or above `threshold`, for+/// the rows `i β‘ worker (mod stride)`.+fn similar_pairs(+ matrix: &VectorMatrix,+ worker: usize,+ stride: usize,+ threshold: f32,+) -> Vec<(usize, usize)> {+ let n = matrix.data.len() / matrix.dimension.max(1);+ let mut pairs = Vec::new();+ for i in (worker..n).step_by(stride) {+ let row = matrix.row(i);+ for j in (i + 1)..n {+ if dot(row, matrix.row(j)) >= threshold {+ pairs.push((i, j));+ }+ }+ }+ pairs+}++fn union(parent: &mut [usize], i: usize, j: usize) {+ let ri = find(parent, i);+ let rj = find(parent, j);+ if ri != rj {+ parent[ri] = rj;}- groups.into_values().collect()}fn find(parent: &mut [usize], mut x: usize) -> usize {@@ -511,24 +629,19 @@ fn find(parent: &mut [usize], mut x: usize) -> usize {x}-/// Scale to unit length. A zero vector stays zero (it then matches nothing),-/// as FAISS `normalize_L2` leaves it in the Python SDK.-fn normalize(mut vec: Vec<f32>) -> Result<Vec<f32>> {+/// Append `vec` scaled to unit length. A zero vector stays zero (it then+/// matches nothing), as FAISS `normalize_L2` leaves it in the Python SDK.+fn push_normalized(data: &mut Vec<f32>, vec: Vec<f32>) -> Result<()> {let norm = vec.iter().map(|v| v * v).sum::<f32>().sqrt();if !norm.is_finite() {return Err(Error::engine("entity embedding has a non-finite norm"));}if norm == 0.0 {- return Ok(vec);- }- for value in &mut vec {- *value /= norm;+ data.extend(vec);+ } else {+ data.extend(vec.iter().map(|value| value / norm));}- Ok(vec)-}--fn cosine(a: &[f32], b: &[f32]) -> f32 {- a.iter().zip(b).map(|(x, y)| x * y).sum()+ Ok(())}fn chain_walk(dedup: &BTreeMap<String, Option<String>>, name: &str) -> String {diff --git a/rust/sdk/cocoindex/src/lib.rs b/rust/sdk/cocoindex/src/lib.rsindex 133c064f..bdc1caff 100644--- a/rust/sdk/cocoindex/src/lib.rs+++ b/rust/sdk/cocoindex/src/lib.rs@@ -81,7 +81,8 @@ pub use resources::id::{generate_uuid_default,};pub use runner::{- GPU, GPURunner, configure_gpu_pool, current_gpu, current_gpu_fraction, current_gpus,+ GPU, GPURunner, Runner, RunnerBody, RunnerOutput, configure_gpu_pool, current_gpu,+ current_gpu_fraction, current_gpus,};// Re-exported so `#[cocoindex::function]` output can register each function's// logic fingerprint without the user crate needing a direct `linkme` dependency.diff --git a/rust/sdk/cocoindex/src/ops/api.rs b/rust/sdk/cocoindex/src/ops/api.rsindex 6a48e19e..a40495b3 100644--- a/rust/sdk/cocoindex/src/ops/api.rs+++ b/rust/sdk/cocoindex/src/ops/api.rs@@ -15,8 +15,10 @@//! - [`ApiTranscriber`] calls `POST {base_url}/audio/transcriptions` with the//! audio as a multipart upload, reading the bytes from any [`FileLike`].//! `transcribe` is memoized by the file's identity and content.-//! - [`ApiChatClient`] calls `POST {base_url}/chat/completions`;-//! [`LlmPairResolver`] builds on it and memoizes each decision.+//! - [`ApiChatClient`] calls `POST {base_url}/chat/completions` in JSON mode;+//! [`ApiChatClient::extract`] deserializes the answer into a type and+//! memoizes it per conversation, and [`LlmPairResolver`] builds on the+//! client and memoizes each decision.//!//! Every request is bounded by the op's `timeout` (10 minutes by default)://! fast failures (408/409/425/429/5xx, a refused or reset connection) are@@ -28,6 +30,7 @@ use std::sync::Arc;use std::time::{Duration, Instant};use async_trait::async_trait;+use serde::de::DeserializeOwned;use serde::{Deserialize, Serialize};use serde_json::json;use tokio::sync::{Mutex, Semaphore};@@ -552,7 +555,7 @@ struct TranscriptionResponse {use crate::entity_resolution::{CanonicalSide, PairDecision, PairResolver};/// A single chat message (`role` + `content`).-#[derive(Clone, Debug, Serialize)]+#[derive(Clone, Debug, Serialize, crate::MemoInput)]pub struct ChatMessage {pub role: String,pub content: String,@@ -625,6 +628,21 @@ impl ApiChatClient {self.request_chat_json(None, messages).await}+ /// Run a chat completion in JSON mode and deserialize the answer into+ /// `T`, memoized through the engine by the model, the endpoint and the+ /// messages: the way to extract structured data with an LLM inside an+ /// update (Python's `litellm` call with a `response_format` model). The+ /// prompt has to describe the JSON shape `T` deserializes from.+ pub async fn extract<T: DeserializeOwned>(+ &self,+ ctx: &Ctx,+ messages: &[ChatMessage],+ ) -> Result<T> {+ let content = chat_json_memoized(ctx, self, messages).await?;+ serde_json::from_str(&content)+ .map_err(|e| Error::engine(format!("chat response was not the expected JSON: {e}")))+ }+async fn request_chat_json(&self,ctx: Option<&Ctx>,@@ -660,6 +678,20 @@ impl ApiChatClient {}}+/// The memo identity of a client's answers: the model and the endpoint.+fn client_identity(client: &ApiChatClient) -> (&str, &str) {+ (&client.model, &client.endpoint.base_url)+}++#[crate::function(memo, memo_key(client = client_identity))]+async fn chat_json_memoized(+ ctx: &Ctx,+ client: &ApiChatClient,+ messages: &[ChatMessage],+) -> Result<String> {+ client.request_chat_json(Some(ctx), &messages).await+}+#[derive(Deserialize)]struct ChatResponse {choices: Vec<ChatChoice>,diff --git a/rust/sdk/cocoindex/src/ops/image.rs b/rust/sdk/cocoindex/src/ops/image.rsindex 8ef0b5de..32579399 100644--- a/rust/sdk/cocoindex/src/ops/image.rs+++ b/rust/sdk/cocoindex/src/ops/image.rs@@ -9,13 +9,15 @@//! `image_search` example.//!//! Implements [`VectorSchemaProvider`] so a vector column can be defined from-//! the model's dimension.+//! the model's dimension. Each batch runs under the GPU runner, one at a time+//! per GPU, like the text embedder; [`ImageEmbedder::load_with`] picks the+//! ONNX Runtime execution providers.use std::sync::Arc;use async_trait::async_trait;use bytes::Bytes;-use fastembed::{ImageEmbedding, ImageInitOptions};+use fastembed::{ExecutionProviderDispatch, ImageEmbedding, ImageInitOptions};use crate::ctx::Ctx;use crate::error::{Error, Result};@@ -54,7 +56,7 @@ impl serde::Serialize for ScheduledImageEmbedder {}}-#[crate::function(memo, batching, max_batch_size = 64)]+#[crate::function(memo, batching, max_batch_size = 64, runner = crate::GPU)]async fn embed_scheduled(_ctx: &Ctx,images: Vec<Bytes>,@@ -73,13 +75,26 @@ impl ImageEmbedder {/// Loading downloads and initializes the ONNX model, so it runs on a/// blocking thread.pub async fn load(model_name: impl Into<String>) -> Result<Self> {+ Self::load_with(model_name, Vec::new()).await+ }++ /// Like [`load`](Self::load), running the model on the first of+ /// `execution_providers` that ONNX Runtime can start; see+ /// [`SentenceTransformerEmbedder::load_with`](crate::ops::sentence_transformers::SentenceTransformerEmbedder::load_with).+ pub async fn load_with(+ model_name: impl Into<String>,+ execution_providers: Vec<ExecutionProviderDispatch>,+ ) -> Result<Self> {let model_name = model_name.into();- tokio::task::spawn_blocking(move || Self::load_blocking(&model_name))+ tokio::task::spawn_blocking(move || Self::load_blocking(&model_name, execution_providers)).await.map_err(|e| Error::engine(format!("image embedder load task panicked: {e}")))?}- fn load_blocking(model_name: &str) -> Result<Self> {+ fn load_blocking(+ model_name: &str,+ execution_providers: Vec<ExecutionProviderDispatch>,+ ) -> Result<Self> {let suffix = |code: &str| code.rsplit('/').next().unwrap_or(code).to_string();let wanted_suffix = suffix(model_name);let info = ImageEmbedding::list_supported_models()@@ -95,7 +110,9 @@ impl ImageEmbedder {})?;let dimension = info.dim;- let model = ImageEmbedding::try_new(ImageInitOptions::new(info.model))+ let options =+ ImageInitOptions::new(info.model).with_execution_providers(execution_providers);+ let model = ImageEmbedding::try_new(options).map_err(|e| Error::engine(format!("load image model `{model_name}`: {e}")))?;Ok(Self {model: Arc::new(model),diff --git a/rust/sdk/cocoindex/src/ops/sentence_transformers.rs b/rust/sdk/cocoindex/src/ops/sentence_transformers.rsindex 01653526..221afaf4 100644--- a/rust/sdk/cocoindex/src/ops/sentence_transformers.rs+++ b/rust/sdk/cocoindex/src/ops/sentence_transformers.rs@@ -8,18 +8,27 @@//! column can be defined from the model's dimension, and [`Embedder`] so it//! plugs into `resolve_entities` directly.//!+//! As in Python (`runner=coco.GPU`), each batch runs under the GPU runner:+//! batches take turns on the GPU pool, one at a time per GPU, so a burst of+//! calls never starts more inferences than there are GPUs (one, when none is+//! detected).+//!//! # What `fastembed` cannot do//!//! Python's embedder takes `prompt_name`, `normalize_embeddings` and `device`.//! `fastembed` has no prompt registry (prepend the model's query/document-//! prefix to the text yourself), always L2-normalizes its output, and runs on-//! the ONNX Runtime execution providers compiled into the binary (CPU by-//! default). Those three options therefore have no Rust counterpart.+//! prefix to the text yourself) and always L2-normalizes its output, so those+//! two options have no Rust counterpart. The device is chosen through ONNX+//! Runtime execution providers instead: [`SentenceTransformerEmbedder::load_with`]+//! takes the providers to try, such as CUDA, which the binary must compile in+//! through the `ort` crate's features (`cuda`, `coreml`, β¦); without any, the+//! model runs on the CPU.use std::path::{Path, PathBuf};use std::sync::Arc;use async_trait::async_trait;+pub use fastembed::ExecutionProviderDispatch;use fastembed::{InitOptions, InitOptionsUserDefined, Pooling, TextEmbedding, TokenizerFiles,UserDefinedEmbeddingModel,@@ -63,7 +72,7 @@ impl serde::Serialize for ScheduledEmbedder {}}-#[crate::function(memo, batching, max_batch_size = 64)]+#[crate::function(memo, batching, max_batch_size = 64, runner = crate::GPU)]async fn embed_scheduled(_ctx: &Ctx,texts: Vec<String>,@@ -168,13 +177,28 @@ impl SentenceTransformerEmbedder {/// Loading downloads and initializes the ONNX model, so it runs on a/// blocking thread.pub async fn load(model_name_or_path: impl Into<String>) -> Result<Self> {+ Self::load_with(model_name_or_path, Vec::new()).await+ }++ /// Like [`load`](Self::load), running the model on the first of+ /// `execution_providers` that ONNX Runtime can start (Python's `device`).+ /// A provider is registered when its `ort` feature is compiled in, e.g.+ /// `ort::execution_providers::CUDAExecutionProvider::default().build()`+ /// with the `cuda` feature; otherwise ONNX Runtime falls back to the CPU.+ pub async fn load_with(+ model_name_or_path: impl Into<String>,+ execution_providers: Vec<ExecutionProviderDispatch>,+ ) -> Result<Self> {let model_name = model_name_or_path.into();- tokio::task::spawn_blocking(move || Self::load_blocking(&model_name))+ tokio::task::spawn_blocking(move || Self::load_blocking(&model_name, execution_providers)).await.map_err(|e| Error::engine(format!("embedder load task panicked: {e}")))?}- fn load_blocking(model_name: &str) -> Result<Self> {+ fn load_blocking(+ model_name: &str,+ execution_providers: Vec<ExecutionProviderDispatch>,+ ) -> Result<Self> {let suffix = |code: &str| code.rsplit('/').next().unwrap_or(code).to_string();let wanted_suffix = suffix(model_name);let registered = TextEmbedding::list_supported_models()@@ -188,7 +212,9 @@ impl SentenceTransformerEmbedder {let (model, dimension) = match registered {Some(info) => {- let model = TextEmbedding::try_new(InitOptions::new(info.model)).map_err(|e| {+ let options =+ InitOptions::new(info.model).with_execution_providers(execution_providers);+ let model = TextEmbedding::try_new(options).map_err(|e| {Error::engine(format!("load embedding model `{model_name}`: {e}"))})?;(model, info.dim)@@ -196,9 +222,17 @@ impl SentenceTransformerEmbedder {None => {let path = Path::new(model_name);let model = if path.is_dir() {- load_user_defined(&LocalDir(path.to_path_buf()), model_name)?+ load_user_defined(+ &LocalDir(path.to_path_buf()),+ model_name,+ execution_providers,+ )?} else {- load_user_defined(&HfHubRepo::open(model_name)?, model_name)?+ load_user_defined(+ &HfHubRepo::open(model_name)?,+ model_name,+ execution_providers,+ )?};// The export does not state its output dimension in one agreed// place, so measure it.@@ -249,7 +283,11 @@ impl SentenceTransformerEmbedder {}}-fn load_user_defined(files: &dyn ModelFiles, model_name: &str) -> Result<TextEmbedding> {+fn load_user_defined(+ files: &dyn ModelFiles,+ model_name: &str,+ execution_providers: Vec<ExecutionProviderDispatch>,+) -> Result<TextEmbedding> {let required = |relative: &str| -> Result<Vec<u8>> {files.read(relative)?.ok_or_else(|| {Error::engine(format!(@@ -281,7 +319,8 @@ fn load_user_defined(files: &dyn ModelFiles, model_name: &str) -> Result<TextEmbif let Some(pooling_config) = files.read(POOLING_CONFIG_FILE)? {model = model.with_pooling(pooling_from_config(&pooling_config, model_name)?);}- TextEmbedding::try_new_from_user_defined(model, InitOptionsUserDefined::default())+ let options = InitOptionsUserDefined::default().with_execution_providers(execution_providers);+ TextEmbedding::try_new_from_user_defined(model, options).map_err(|e| Error::engine(format!("load embedding model `{model_name}`: {e}")))}@@ -324,7 +363,7 @@ impl VectorSchemaProvider for SentenceTransformerEmbedder {#[async_trait]impl Embedder for SentenceTransformerEmbedder {- /// Memoized and batched, like the inherent+ /// Memoized, batched and run on the GPU pool, like the inherent/// [`embed`](SentenceTransformerEmbedder::embed).async fn embed(&self, ctx: &Ctx, text: &str) -> Result<Vec<f32>> {SentenceTransformerEmbedder::embed(self, ctx, text).await@@ -333,7 +372,10 @@ impl Embedder for SentenceTransformerEmbedder {#[cfg(test)]mod tests {+ use std::num::NonZeroUsize;use std::sync::Mutex;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;use futures::future::join_all;@@ -414,6 +456,65 @@ mod tests {assert!(batches.iter().all(|batch| batch.len() <= 64));}+ /// Counts the model's batches running at once, as the ONNX session would+ /// see them.+ #[derive(Default)]+ struct SlowModel {+ now: AtomicUsize,+ peak: AtomicUsize,+ batches: AtomicUsize,+ }++ impl EmbeddingModel for SlowModel {+ fn embed(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {+ let now = self.now.fetch_add(1, Ordering::SeqCst) + 1;+ self.peak.fetch_max(now, Ordering::SeqCst);+ self.batches.fetch_add(1, Ordering::SeqCst);+ std::thread::sleep(Duration::from_millis(20));+ self.now.fetch_sub(1, Ordering::SeqCst);+ Ok(texts+ .into_iter()+ .map(|text| vec![text.len() as f32])+ .collect())+ }+ }++ /// Python runs `_embed` under `runner=coco.GPU`: with one GPU in the pool+ /// (the default when none is detected), batches take turns, so a burst of+ /// calls never runs two inferences at once.+ #[tokio::test]+ async fn batches_run_one_at_a_time_per_gpu() {+ crate::configure_gpu_pool(NonZeroUsize::new(1).unwrap());+ let model = Arc::new(SlowModel::default());+ let embedder = SentenceTransformerEmbedder {+ model: model.clone(),+ model_name: "slow-model".to_string(),+ dimension: 1,+ };+ let (_tempdir, app) = test_app("sentence_transformer_gpu_runner").await;+ let texts: Vec<String> = (0..200).map(|index| format!("text-{index}")).collect();++ app.update(move |ctx| async move {+ join_all(texts.into_iter().map(|text| embedder.embed(&ctx, text)))+ .await+ .into_iter()+ .collect::<Result<Vec<_>>>()?;+ Ok(())+ })+ .await+ .unwrap();++ assert!(+ model.batches.load(Ordering::SeqCst) >= 4,+ "200 texts in batches of at most 64 take at least four batches"+ );+ assert_eq!(+ model.peak.load(Ordering::SeqCst),+ 1,+ "batches run one at a time on one GPU"+ );+ }+struct NeverMatches;#[async_trait]diff --git a/rust/sdk/cocoindex/src/prelude.rs b/rust/sdk/cocoindex/src/prelude.rsindex 695c3e33..e45d2308 100644--- a/rust/sdk/cocoindex/src/prelude.rs+++ b/rust/sdk/cocoindex/src/prelude.rs@@ -34,7 +34,8 @@ pub use crate::resources::schema::{};pub use crate::resources::view::{SegmentKind, SourceView, ViewSegment};pub use crate::runner::{- GPU, GPURunner, configure_gpu_pool, current_gpu, current_gpu_fraction, current_gpus,+ GPU, GPURunner, Runner, RunnerBody, RunnerOutput, configure_gpu_pool, current_gpu,+ current_gpu_fraction, current_gpus,};pub use crate::statediff::{DiffAction, ManagedBy, ManagedTargetOptions, MutualTrackingRecord, TrackingRecordTransition,diff --git a/rust/sdk/cocoindex/src/runner.rs b/rust/sdk/cocoindex/src/runner.rsindex 70f19efd..2838f83e 100644--- a/rust/sdk/cocoindex/src/runner.rs+++ b/rust/sdk/cocoindex/src/runner.rs@@ -1,11 +1,12 @@//! Runners: bound how many calls of a function run at once on a scarce//! resource, the Rust form of Python's `@coco.fn.as_async(runner=coco.GPU)`.//!-//! The one runner is [`GPURunner`]. Each call (or, for a `batching` function,-//! each physical batch) acquires a share of one GPU from the process-wide-//! GPU pool before its body runs and releases it afterwards, so a body that-//! holds a whole GPU never runs twice at once on the same GPU, and two-//! halves share one. Inside the body, [`current_gpu`], [`current_gpus`] and+//! A [`Runner`] wraps the body of every call of a function (or, for a+//! `batching` function, of every physical batch). The built-in runner is+//! [`GPURunner`]: each body acquires a share of one GPU from the process-wide+//! GPU pool before it runs and releases it afterwards, so a body that holds a+//! whole GPU never runs twice at once on the same GPU, and two halves share+//! one. Inside the body, [`current_gpu`], [`current_gpus`] and//! [`current_gpu_fraction`] tell which GPU was assigned.//!//! ```ignore@@ -16,6 +17,24 @@//! }//! ```//!+//! A user-defined runner implements [`Runner`], Python's `Runner` base class:+//! it receives the body as a future and decides when and how to run it.+//!+//! ```ignore+//! struct AtMostTwo(tokio::sync::Semaphore);+//!+//! #[async_trait::async_trait]+//! impl cocoindex::Runner for AtMostTwo {+//! async fn run(&self, body: cocoindex::RunnerBody<'_>) -> Result<cocoindex::RunnerOutput> {+//! let _permit = self.0.acquire().await;+//! body.await+//! }+//! }+//!+//! #[cocoindex::function(runner = AtMostTwo(tokio::sync::Semaphore::new(2)))]+//! async fn summarize(_ctx: &Ctx, text: String) -> Result<String> { /* ... */ }+//! ```+//!//! The pool's size is detected from `COCOINDEX_NUM_GPUS`, then//! `CUDA_VISIBLE_DEVICES`, then `nvidia-smi`, and falls back to one;//! [`configure_gpu_pool`] overrides it. Python's subprocess mode@@ -23,14 +42,67 @@//! for the GIL and CUDA's fork rules; a Rust body runs on the Tokio runtime//! and has neither problem, so there is no equivalent here.+use std::any::Any;use std::future::Future;use std::num::NonZeroUsize;+use std::pin::Pin;use std::sync::{Arc, Mutex};+use std::task::{Context, Poll};+use async_trait::async_trait;use cocoindex_utils::gpu_pool::GPUPool;use cocoindex_utils::gpu_pool::gpu_capacity::GPUCapacity;+use futures::future::BoxFuture;++use crate::error::{Error, Result};++/// The value a [`RunnerBody`] produces. It is the function's own result,+/// opaque to the runner, which hands it back unchanged.+pub struct RunnerOutput(Box<dyn Any + Send>);++/// The body of one call (or one physical batch) that a [`Runner`] runs: a+/// future the runner awaits once, when its resource is available.+pub struct RunnerBody<'a>(BoxFuture<'a, Result<RunnerOutput>>);-use crate::error::Result;+impl Future for RunnerBody<'_> {+ type Output = Result<RunnerOutput>;++ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {+ self.0.as_mut().poll(cx)+ }+}++/// Runs the bodies of a function's calls, Python's `Runner` base class. The+/// value of `#[cocoindex::function(runner = ...)]` is any type implementing+/// it; [`GPURunner`] is the built-in one.+///+/// An implementation awaits `body` exactly once and returns its output. What+/// it does around that await is its policy: wait for a permit, hold a+/// resource, set a task-local for the body to read.+#[async_trait]+pub trait Runner: Send + Sync + 'static {+ async fn run(&self, body: RunnerBody<'_>) -> Result<RunnerOutput>;+}++/// Run `f` under `runner` and give back its typed output. The macro-generated+/// wrappers and the batch scheduler go through here.+#[doc(hidden)]+pub async fn __run_under<T, F>(runner: &dyn Runner, f: F) -> Result<T>+where+ T: Send + 'static,+ F: Future<Output = Result<T>> + Send,+{+ let body = RunnerBody(Box::pin(async move {+ let output = f.await?;+ Ok(RunnerOutput(Box::new(output)))+ }));+ let output = runner.run(body).await?;+ output+ .0+ .downcast::<T>()+ .map(|output| *output)+ .map_err(|_| Error::engine("the runner returned another body's output"))+}/// A runner that serializes calls over the GPUs in the process-wide pool.///@@ -49,9 +121,10 @@ impl GPURunner {/// `coco.GPU(fraction)`. Calls whose fractions fit together run at once on/// the same GPU: two `fraction(0.5)` calls share one.///- /// `fraction` must be in `(0, 1]`. The function is `const`, so with a- /// literal in `#[cocoindex::function(runner = ...)]` a bad value is a- /// compile error; called at runtime with a bad value, it panics.+ /// `fraction` must be in `(0, 1]`: the function panics otherwise. It is+ /// `const`, so a `const` holding a bad literal fails to compile; in+ /// `#[cocoindex::function(runner = ...)]` the value is built on the first+ /// call, where a bad value panics.pub const fn fraction(fraction: f32) -> Self {assert!(fraction > 0.0 && fraction <= 1.0,@@ -59,14 +132,14 @@ impl GPURunner {);Self { fraction }}+}- /// Run `f` while holding this runner's share of one GPU: wait until a GPU- /// has that much capacity free, run `f` with [`current_gpu`] set to it,- /// and give the capacity back when `f` finishes or is cancelled.- pub async fn run<T, F>(&self, f: F) -> Result<T>- where- F: Future<Output = Result<T>>,- {+#[async_trait]+impl Runner for GPURunner {+ /// Run `body` while holding this runner's share of one GPU: wait until a+ /// GPU has that much capacity free, run `body` with [`current_gpu`] set+ /// to it, and give the capacity back when `body` finishes or is cancelled.+ async fn run(&self, body: RunnerBody<'_>) -> Result<RunnerOutput> {let pool = default_gpu_pool()?;let fraction = GPUCapacity::try_from(self.fraction)?;let gpu_id = pool.acquire(fraction).await?;@@ -79,7 +152,7 @@ impl GPURunner {gpus: vec![gpu_id],fraction: self.fraction,};- CURRENT_GPU.scope(assignment, f).await+ CURRENT_GPU.scope(assignment, body).await}}diff --git a/rust/sdk/cocoindex/tests/batching_runner.rs b/rust/sdk/cocoindex/tests/batching_runner.rsindex a07629ed..f9fcc338 100644--- a/rust/sdk/cocoindex/tests/batching_runner.rs+++ b/rust/sdk/cocoindex/tests/batching_runner.rs@@ -488,3 +488,85 @@ async fn gpu_runner_holds_the_gpu_per_physical_batch_and_per_retried_half() {"the rejected pair is retried as halves: {batches:?}");}++// ---------------------------------------------------------------------------+// A user-defined runner: any `Runner` bounds a function's bodies its own way+// ---------------------------------------------------------------------------++/// Runs at most `permits` bodies at once, and tags each with a task-local the+/// body reads, as `GPURunner` sets `current_gpu()`.+struct Permits(tokio::sync::Semaphore);++tokio::task_local! {+ static UNDER_PERMITS: bool;+}++#[async_trait::async_trait]+impl cocoindex::Runner for Permits {+ async fn run(&self, body: cocoindex::RunnerBody<'_>) -> Result<cocoindex::RunnerOutput> {+ let _permit = self+ .0+ .acquire()+ .await+ .map_err(|e| Error::engine(e.to_string()))?;+ UNDER_PERMITS.scope(true, body).await+ }+}++static PERMITS_IN_FLIGHT: InFlight = InFlight::new();++#[cocoindex::function(memo, runner = Permits(tokio::sync::Semaphore::new(2)))]+async fn two_at_once(_ctx: &Ctx, item: i64) -> Result<i64> {+ PERMITS_IN_FLIGHT.enter();+ assert!(UNDER_PERMITS.get(), "the body runs inside the runner");+ sleep(Duration::from_millis(30)).await;+ PERMITS_IN_FLIGHT.leave();+ Ok(item + 1)+}++#[tokio::test]+async fn user_runner_bounds_calls_of_a_plain_function() {+ PERMITS_IN_FLIGHT.reset();+ let (app, _dir) = temp_app("user_runner_plain").await;+ let outputs = app+ .update(|ctx| async move {+ let calls = (0..5).map(|item| two_at_once(&ctx, item));+ futures::future::join_all(calls)+ .await+ .into_iter()+ .collect::<Result<Vec<_>>>()+ })+ .await+ .unwrap();+ assert_eq!(outputs, vec![1, 2, 3, 4, 5]);+ assert_eq!(PERMITS_IN_FLIGHT.peak.load(Ordering::SeqCst), 2);+}++static PERMITS_BATCH_IN_FLIGHT: InFlight = InFlight::new();++#[cocoindex::function(batching, max_batch_size = 2, runner = Permits(tokio::sync::Semaphore::new(1)))]+async fn one_batch_at_once(_ctx: &Ctx, items: Vec<i64>) -> Result<Vec<i64>> {+ PERMITS_BATCH_IN_FLIGHT.enter();+ assert!(UNDER_PERMITS.get());+ sleep(Duration::from_millis(30)).await;+ PERMITS_BATCH_IN_FLIGHT.leave();+ Ok(items.into_iter().map(|item| item * 2).collect())+}++#[tokio::test]+async fn user_runner_bounds_physical_batches() {+ PERMITS_BATCH_IN_FLIGHT.reset();+ let (app, _dir) = temp_app("user_runner_batching").await;+ let outputs = app+ .update(|ctx| async move {+ let calls = (0..6).map(|item| one_batch_at_once(&ctx, item));+ futures::future::join_all(calls)+ .await+ .into_iter()+ .collect::<Result<Vec<_>>>()+ })+ .await+ .unwrap();+ assert_eq!(outputs, vec![0, 2, 4, 6, 8, 10]);+ assert_eq!(PERMITS_BATCH_IN_FLIGHT.peak.load(Ordering::SeqCst), 1);+}diff --git a/rust/sdk/cocoindex/tests/entity_resolution.rs b/rust/sdk/cocoindex/tests/entity_resolution.rsindex 3f4e6730..7c14abf4 100644--- a/rust/sdk/cocoindex/tests/entity_resolution.rs+++ b/rust/sdk/cocoindex/tests/entity_resolution.rs@@ -402,3 +402,158 @@ async fn a_zero_embedding_matches_nothing_instead_of_failing() {assert_eq!(result.canonical_of("Z").unwrap(), "Z");assert!(resolver.calls().is_empty());}++// ---------------------------------------------------------------------------+// The matrix search gives the same resolution as a plain scalar search+// ---------------------------------------------------------------------------++/// Resolves to a candidate of the entity's own cluster, if listed.+struct ClusterResolver {+ cluster_of: HashMap<String, usize>,+}++#[async_trait]+impl PairResolver for ClusterResolver {+ async fn resolve_pair(+ &self,+ _ctx: &Ctx,+ entity: &str,+ candidates: &[String],+ ) -> cocoindex::Result<PairDecision> {+ let cluster = self.cluster_of[entity];+ Ok(candidates+ .iter()+ .find(|candidate| self.cluster_of[candidate.as_str()] == cluster)+ .map_or_else(PairDecision::no_match, PairDecision::matched))+ }+}++/// Entities with their vectors, and the cluster each belongs to.+struct Clustered {+ entities: Vec<(String, Vec<f32>)>,+ cluster_of: HashMap<String, usize>,+}++/// Clusters of near-identical unit vectors plus isolated ones, in a+/// deterministic pseudo-random layout.+fn clustered_vectors(+ clusters: usize,+ per_cluster: usize,+ isolated: usize,+ dimension: usize,+) -> Clustered {+ use rand::{Rng, SeedableRng};+ let mut rng = rand::rngs::StdRng::seed_from_u64(11);+ let mut unit = |base: Option<&[f32]>, noise: f32| -> Vec<f32> {+ let mut vec: Vec<f32> = (0..dimension)+ .map(|k| base.map_or(0.0, |b| b[k]) + rng.gen_range(-noise..noise))+ .collect();+ let norm = vec.iter().map(|v| v * v).sum::<f32>().sqrt();+ vec.iter_mut().for_each(|v| *v /= norm);+ vec+ };+ let mut entities = Vec::new();+ let mut cluster_of = HashMap::new();+ for cluster in 0..clusters {+ let base = unit(None, 1.0);+ for member in 0..per_cluster {+ let name = format!("c{cluster:03}-m{member:02}");+ entities.push((name.clone(), unit(Some(&base), 0.02)));+ cluster_of.insert(name, cluster);+ }+ }+ for index in 0..isolated {+ let name = format!("iso-{index:03}");+ entities.push((name.clone(), unit(None, 1.0)));+ cluster_of.insert(name, clusters + index);+ }+ Clustered {+ entities,+ cluster_of,+ }+}++/// The resolution loop as plainly as it can be written: entities in name+/// order, each searched against every earlier one with a scalar cosine, no+/// components, no matrix.+fn reference_resolution(+ entities: &[(String, Vec<f32>)],+ cluster_of: &HashMap<String, usize>,+ max_distance: f32,+ top_n: usize,+) -> std::collections::BTreeMap<String, Option<String>> {+ let mut sorted: Vec<&(String, Vec<f32>)> = entities.iter().collect();+ sorted.sort_by(|a, b| a.0.cmp(&b.0));+ let cosine = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(x, y)| x * y).sum::<f32>();+ let canonical = |dedup: &std::collections::BTreeMap<String, Option<String>>, name: &str| {+ let mut current = name.to_string();+ while let Some(Some(next)) = dedup.get(¤t) {+ current = next.clone();+ }+ current+ };+ let mut dedup = std::collections::BTreeMap::new();+ let mut indexed: Vec<&(String, Vec<f32>)> = Vec::new();+ for entity in &sorted {+ let (name, vec) = entity;+ let mut scored: Vec<(f32, String)> = indexed+ .iter()+ .map(|(other, other_vec)| (cosine(vec, other_vec), canonical(&dedup, other)))+ .filter(|(score, other)| *score >= 1.0 - max_distance && other != name)+ .collect();+ scored.sort_by(|(a_score, a), (b_score, b)| {+ b_score.total_cmp(a_score).then_with(|| a.cmp(b))+ });+ let mut candidates: Vec<String> = Vec::new();+ for (_, other) in scored {+ if !candidates.contains(&other) {+ candidates.push(other);+ if candidates.len() >= top_n {+ break;+ }+ }+ }+ let matched = candidates+ .iter()+ .find(|candidate| cluster_of[candidate.as_str()] == cluster_of[name])+ .cloned();+ dedup.insert(name.clone(), matched);+ indexed.push(entity);+ }+ dedup+}++#[tokio::test]+async fn matrix_search_matches_the_reference_resolution() {+ // Over 256 entities, so the partition runs on blocking threads.+ let Clustered {+ entities,+ cluster_of,+ } = clustered_vectors(60, 5, 100, 48);+ let expected = reference_resolution(&entities, &cluster_of, 0.3, 5);+ assert!(+ expected.values().filter(|target| target.is_some()).count() >= 200,+ "the data must exercise matches"+ );++ let embedder = Arc::new(ScriptedEmbedder {+ vectors: entities.iter().cloned().collect(),+ });+ let resolver = Arc::new(ClusterResolver { cluster_of });+ let names: Vec<String> = entities.iter().map(|(name, _)| name.clone()).collect();+ let resolved = in_update(move |ctx| async move {+ resolve_entities(+ &ctx,+ names.iter(),+ &*embedder,+ &*resolver,+ None,+ ResolveOptions::default(),+ )+ .await+ })+ .await+ .unwrap();++ assert_eq!(resolved.to_map(), expected);+}diff --git a/rust/sdk/cocoindex/tests/ops_api.rs b/rust/sdk/cocoindex/tests/ops_api.rsindex b6938d0c..061e282d 100644--- a/rust/sdk/cocoindex/tests/ops_api.rs+++ b/rust/sdk/cocoindex/tests/ops_api.rs@@ -13,7 +13,9 @@ use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant, SystemTime};-use cocoindex::ops::api::{ApiEmbedder, ApiTranscriber, LlmPairResolver};+use cocoindex::ops::api::{+ ApiChatClient, ApiEmbedder, ApiTranscriber, ChatMessage, LlmPairResolver,+};use cocoindex::prelude::{FileContentCache, FileLike, FileMetadata, FilePath};use cocoindex::{CanonicalSide, Ctx, PairResolver, walk_items};use futures::future::join_all;@@ -629,6 +631,90 @@ async fn llm_pair_resolver_memoizes_decisions() {assert_eq!(server.received_requests().await.unwrap().len(), 2);}+// ---------------------------------------------------------------------------+// ApiChatClient::extract β a typed, memoized JSON-mode completion+// ---------------------------------------------------------------------------++#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]+struct Person {+ name: String,+ age: u32,+}++#[tokio::test]+async fn chat_client_extract_deserializes_and_memoizes() {+ let Some(server) = mock_server().await else {+ return;+ };+ Mock::given(method("POST"))+ .and(path("/chat/completions"))+ .respond_with(chat_response(r#"{"name": "Ada", "age": 36}"#))+ .mount(&server)+ .await;+ let client = ApiChatClient::new("fake-model").with_base_url(server.uri());+ let tempdir = tempfile::tempdir().unwrap();+ let app = app_in(&tempdir, "chat_extract").await;++ let extract = |text: &'static str| {+ let client = client.clone();+ app.update(move |ctx| async move {+ let messages = [+ ChatMessage::system("Reply with JSON {name, age}."),+ ChatMessage::user(text),+ ];+ client.extract::<Person>(&ctx, &messages).await+ })+ };++ for _ in 0..2 {+ let person = extract("Ada is 36.").await.unwrap();+ assert_eq!(+ person,+ Person {+ name: "Ada".into(),+ age: 36+ }+ );+ }+ assert_eq!(+ server.received_requests().await.unwrap().len(),+ 1,+ "the same conversation is served from the memo store"+ );++ extract("Ada, 36 years old.").await.unwrap();+ assert_eq!(server.received_requests().await.unwrap().len(), 2);++ let requests = server.received_requests().await.unwrap();+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();+ assert_eq!(body["response_format"]["type"], "json_object");+}++#[tokio::test]+async fn chat_client_extract_rejects_an_answer_of_another_shape() {+ let Some(server) = mock_server().await else {+ return;+ };+ Mock::given(method("POST"))+ .and(path("/chat/completions"))+ .respond_with(chat_response(r#"{"name": "Ada"}"#))+ .mount(&server)+ .await;+ let client = ApiChatClient::new("fake-model").with_base_url(server.uri());+ let err = in_update("chat_extract_bad_shape", move |ctx| async move {+ client+ .extract::<Person>(&ctx, &[ChatMessage::user("Ada")])+ .await+ .map(|person| person.age)+ })+ .await+ .unwrap_err();+ assert!(+ err.to_string().contains("expected JSON"),+ "unexpected error: {err}"+ );+}+/// A rate-limited (429) response is retried, honoring `Retry-After`.#[tokio::test]async fn api_embedder_retries_rate_limited_requests() {diff --git a/rust/sdk/cocoindex_macros/src/lib.rs b/rust/sdk/cocoindex_macros/src/lib.rsindex 224695c8..78ac8d96 100644--- a/rust/sdk/cocoindex_macros/src/lib.rs+++ b/rust/sdk/cocoindex_macros/src/lib.rs@@ -378,9 +378,9 @@ struct FunctionArgs {memo: bool,batching: bool,max_batch_size: Option<usize>,- /// `runner = <expr>`: a `cocoindex::GPURunner` const expression whose- /// resource every call (or physical batch) of the function holds while- /// its body runs.+ /// `runner = <expr>`: an expression of a type implementing+ /// `cocoindex::Runner`, under which every call (or physical batch) of+ /// the function runs its body.runner: Option<Expr>,version: Option<u64>,memo_key: Vec<MemoKeyOverride>,@@ -940,20 +940,22 @@ fn gen_owned_param_clones(params: &[ParamInfo]) -> Vec<TokenStream2> {.collect()}-/// Name of the `const` holding a function's `runner = ...` value.+/// Name of the `static` holding a function's `runner = ...` value.fn runner_const_name(fn_name: &Ident) -> Ident {format_ident!("__COCO_RUNNER_{}", fn_name.to_string().to_uppercase())}-/// The `const` item for `runner = <expr>`, or nothing. A `const` item makes-/// `GPURunner::fraction(x)` with a bad literal a compile error.+/// The `static` item for `runner = <expr>`, or nothing: the runner, of any+/// type implementing `cocoindex::Runner`, built on the function's first call+/// and shared by every call.fn gen_runner_const(fn_name: &Ident, args: &FunctionArgs) -> TokenStream2 {match &args.runner {Some(expr) => {let name = runner_const_name(fn_name);quote! {#[doc(hidden)]- const #name: ::cocoindex::GPURunner = #expr;+ static #name: ::std::sync::LazyLock<::std::sync::Arc<dyn ::cocoindex::Runner>> =+ ::std::sync::LazyLock::new(|| ::std::sync::Arc::new(#expr));}}None => quote! {},@@ -968,7 +970,7 @@ fn gen_runner_wrap(fn_name: &Ident, args: &FunctionArgs, body: TokenStream2) ->}let name = runner_const_name(fn_name);quote! {- #name.run(async move { #body }).await+ ::cocoindex::runner::__run_under(&**#name, async move { #body }).await}}@@ -1008,7 +1010,7 @@ fn expand_batching_function(let runner_const = gen_runner_const(fn_name, args);let runner = if args.runner.is_some() {let name = runner_const_name(fn_name);- quote! { ::core::option::Option::Some(#name) }+ quote! { ::core::option::Option::Some(::std::sync::Arc::clone(&*#name)) }} else {quote! { ::core::option::Option::None }};@@ -1186,8 +1188,10 @@ fn expand_batching_function(/// #[cocoindex::function(runner = cocoindex::GPURunner::fraction(0.5))]/// async fn infer(ctx: &Ctx, image: &Image) -> Result<Label> { ... }/// ```-/// The value is a `const` expression of type `cocoindex::GPURunner`, and the-/// function must be `async`.+/// The value is an expression of any type implementing `cocoindex::Runner`+/// (`cocoindex::GPU`, `cocoindex::GPURunner::fraction(..)`, or a user-defined+/// runner), built on the first call and shared by every call; the function+/// must be `async`.////// Optional `version` parameter forces cache invalidation:/// ```ignore