Skip to content

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

fix(rust-sdk): validate Qdrant, Valkey and Turbopuffer points at declare time (#2765)

LJ 🥥🌴6f7851d6e094
diff --git a/docs/src/content/docs/advanced_topics/memoization_keys.mdx b/docs/src/content/docs/advanced_topics/memoization_keys.mdx
index 1bb2c632..53a55a00 100644
--- a/docs/src/content/docs/advanced_topics/memoization_keys.mdx
+++ b/docs/src/content/docs/advanced_topics/memoization_keys.mdx
@@ -290,7 +290,7 @@ Each entry in `memo_key(..)`:
The macro checks the names at compile time. A transform also suppresses the argument type's `memo_state` validation; use a newtype when the freshness check must stay.
-**Target handles.** A target handle is where output goes, not an input of the computation, so it is not `MemoInput`. `DirTarget` and the Postgres, SQLite, Doris, SurrealDB, LanceDB, Neo4j and FalkorDB table and relation targets are `Serialize` instead: as an argument of a memoized function or of `mount!`, `use_mount!` or `mount_each!`, one is keyed by its stable key. The other connectors' handles are only `Clone`. Skip those in the memo key; you can skip any handle the same way:
+**Target handles.** A target handle is where output goes, not an input of the computation, so it is not `MemoInput`. `DirTarget`, the Postgres, SQLite, Doris, SurrealDB, LanceDB, Neo4j and FalkorDB table and relation targets, the Qdrant collection, the Valkey index and the Turbopuffer namespace targets are `Serialize` instead: as an argument of a memoized function or of `mount!`, `use_mount!` or `mount_each!`, one is keyed by its stable key. The other connectors' handles are only `Clone`. Skip those in the memo key; you can skip any handle the same way:
{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (target_state_of_nested_memo_survives_outer_memo_hit) */}
```rust
diff --git a/docs/src/content/docs/connectors/qdrant.mdx b/docs/src/content/docs/connectors/qdrant.mdx
index 7c919692..61384c21 100644
--- a/docs/src/content/docs/connectors/qdrant.mdx
+++ b/docs/src/content/docs/connectors/qdrant.mdx
@@ -328,7 +328,7 @@ impl CollectionTarget {
}
```
-The id, the vector and the payload are separate arguments, and the shape of the vector picks the method. The payload is a `serde_json::Map<String, Value>`. Each method checks the point against the collection schema and the id rules (see [Point IDs](#point-ids)) when it is called, and returns an error for a mismatch.
+The id, the vector and the payload are separate arguments, and the shape of the vector picks the method. The payload is a `serde_json::Map<String, Value>`. Each method checks the point against the collection schema and the id rules (see [Point IDs](#point-ids)) when it is called, and returns an error for a mismatch: a vector of the wrong length, an empty multivector, a NaN or infinite element, or a payload integer beyond the `i64` range Qdrant stores. Writes wait until Qdrant has applied them.
</Fragment>
</LangTabs>
diff --git a/docs/src/content/docs/connectors/turbopuffer.mdx b/docs/src/content/docs/connectors/turbopuffer.mdx
index 4a740831..85bbe6d7 100644
--- a/docs/src/content/docs/connectors/turbopuffer.mdx
+++ b/docs/src/content/docs/connectors/turbopuffer.mdx
@@ -296,7 +296,7 @@ The id, the vector(s) and the attributes are separate arguments. The id is a `Ro
<Lang only="rust">
- `id` — Document id (string or unsigned integer).
-- `vector` / `vectors` — For an unnamed-vector schema, pass one `Vec<f32>` to `declare_row`. For a named-vectors schema, pass `(name, vector)` pairs to `declare_named_row`.
+- `vector` / `vectors` — For an unnamed-vector schema, pass one `Vec<f32>` to `declare_row`. For a named-vectors schema, pass `(name, vector)` pairs to `declare_named_row`. Each vector must have its field's dimension and finite elements; otherwise the declare call returns an error.
- `attributes` — Non-vector attributes (text, tags, metadata, etc.). Turbopuffer infers attribute types from the data.
</Lang>
diff --git a/docs/src/content/docs/connectors/valkey.mdx b/docs/src/content/docs/connectors/valkey.mdx
index 91f57dbf..ec57d72a 100644
--- a/docs/src/content/docs/connectors/valkey.mdx
+++ b/docs/src/content/docs/connectors/valkey.mdx
@@ -381,7 +381,7 @@ index.declare_document(
- `document` — A `valkey::Document` containing:
- `id` — Document ID (string)
- - `vector` — Vector data (`Vec<f32>`)
+ - `vector` — Vector data (`Vec<f32>`). It must have the index's dimension and finite elements: the search module stores a hash whose vector it cannot read but never indexes it, so `declare_document` returns an error instead.
- `payload` — Optional metadata map (values are text, `i64` or `f64`). The key `vector` is reserved for the vector field (see [Data storage](#data-storage)), so `declare_document` returns an error for a payload with that key.
</Lang>
diff --git a/rust/sdk/cocoindex/src/connectors/qdrant.rs b/rust/sdk/cocoindex/src/connectors/qdrant.rs
index 86cd0d56..4c51fd7c 100644
--- a/rust/sdk/cocoindex/src/connectors/qdrant.rs
+++ b/rust/sdk/cocoindex/src/connectors/qdrant.rs
@@ -643,7 +643,34 @@ impl NamedPointVector {
}
}
-/// Check a sparse vector's own shape: one value per index, no index twice.
+/// Check a dense vector against its field: the declared length, and finite
+/// elements (Qdrant stores a NaN, which then poisons every score it is in).
+fn validate_dense_vector(v: &[f32], size: u64) -> std::result::Result<(), String> {
+ if v.len() as u64 != size {
+ return Err(format!(
+ "has {} elements but the collection expects {size}",
+ v.len()
+ ));
+ }
+ if v.iter().any(|x| !x.is_finite()) {
+ return Err("contains a non-finite (NaN/Inf) element".to_string());
+ }
+ Ok(())
+}
+
+/// Check a multivector: at least one vector, each a valid dense vector.
+fn validate_multivector(vs: &[Vec<f32>], size: u64) -> std::result::Result<(), String> {
+ if vs.is_empty() {
+ return Err("has no vectors".to_string());
+ }
+ for (i, v) in vs.iter().enumerate() {
+ validate_dense_vector(v, size).map_err(|detail| format!("vector {i} {detail}"))?;
+ }
+ Ok(())
+}
+
+/// Check a sparse vector's own shape: one value per index, no index twice,
+/// finite values.
fn validate_sparse_vector(indices: &[u32], values: &[f32]) -> std::result::Result<(), String> {
if indices.len() != values.len() {
return Err(format!(
@@ -652,6 +679,9 @@ fn validate_sparse_vector(indices: &[u32], values: &[f32]) -> std::result::Resul
values.len()
));
}
+ if values.iter().any(|x| !x.is_finite()) {
+ return Err("contains a non-finite (NaN/Inf) value".to_string());
+ }
let mut seen = std::collections::HashSet::with_capacity(indices.len());
if let Some(dup) = indices.iter().find(|index| !seen.insert(**index)) {
return Err(format!("repeats index {dup}"));
@@ -703,6 +733,28 @@ fn canonical_uuid_text(text: &str) -> Option<String> {
.map(|id| id.hyphenated().to_string())
}
+/// Check a payload for values Qdrant cannot store as given: Qdrant keeps
+/// integers as `i64`, and the client turns a larger one into a rounded float.
+fn validate_payload(payload: &Map<String, JsonValue>) -> std::result::Result<(), String> {
+ fn check(path: &str, value: &JsonValue) -> std::result::Result<(), String> {
+ match value {
+ JsonValue::Number(n) if n.as_i64().is_none() && n.is_u64() => Err(format!(
+ "field {path:?} holds the integer {n}, beyond the i64 range Qdrant stores; \
+ store it as a string or a float"
+ )),
+ JsonValue::Array(items) => items
+ .iter()
+ .enumerate()
+ .try_for_each(|(i, item)| check(&format!("{path}[{i}]"), item)),
+ JsonValue::Object(fields) => fields
+ .iter()
+ .try_for_each(|(k, v)| check(&format!("{path}.{k}"), v)),
+ _ => Ok(()),
+ }
+ }
+ payload.iter().try_for_each(|(k, v)| check(k, v))
+}
+
const POINT_ID_RULE: &str = "Qdrant point IDs must be an unsigned 64-bit integer or a UUID; see \
https://qdrant.tech/documentation/manage-data/points/#point-ids. For a stable ID derived \
from an arbitrary string key, use a version-5 UUID, e.g. \
@@ -755,8 +807,19 @@ struct Point {
}
impl Point {
+ /// Check the point against the collection schema: its vectors' shapes,
+ /// lengths and values, and its payload. Run at declare time, so a bad
+ /// point fails its own declaration rather than the whole batch's write.
+ fn validate(&self, schema: &CollectionSchema) -> Result<()> {
+ self.to_qdrant_vectors(schema)?;
+ validate_payload(&self.payload)
+ .map_err(|detail| Error::engine(format!("qdrant point {}: payload {detail}", self.id)))
+ }
+
fn to_qdrant_vectors(&self, schema: &CollectionSchema) -> Result<Vectors> {
let vector_fields = schema.vector_fields();
+ let invalid =
+ |detail: String| Error::engine(format!("qdrant point {}: vector {detail}", self.id));
match (&vector_fields, &self.vector) {
(VectorFields::Single(def), PointVector::Single(v)) => {
if def.is_multivector() {
@@ -765,6 +828,7 @@ impl Point {
self.id
)));
}
+ validate_dense_vector(v, def.vector_size()).map_err(invalid)?;
Ok(Vector::new_dense(v.clone()).into())
}
(VectorFields::Single(def), PointVector::Multi(v)) => {
@@ -774,6 +838,7 @@ impl Point {
self.id
)));
}
+ validate_multivector(v, def.vector_size()).map_err(invalid)?;
Ok(Vector::new_multi(v.clone()).into())
}
(VectorFields::Single(_), PointVector::Named(_)) => Err(Error::engine(format!(
@@ -796,11 +861,25 @@ impl Point {
let mut named = HashMap::new();
for (name, point_vector) in point_vectors {
+ let field_invalid = |detail: String| {
+ Error::engine(format!(
+ "qdrant point {}: vector field {:?} {detail}",
+ self.id, name
+ ))
+ };
let shape_matches = if let Some(def) = vectors.get(name) {
match point_vector {
- NamedPointVector::Single(_) => !def.is_multivector(),
- NamedPointVector::Multi(_) => def.is_multivector(),
- NamedPointVector::Sparse { .. } => false,
+ NamedPointVector::Single(v) if !def.is_multivector() => {
+ validate_dense_vector(v, def.vector_size())
+ .map_err(field_invalid)?;
+ true
+ }
+ NamedPointVector::Multi(vs) if def.is_multivector() => {
+ validate_multivector(vs, def.vector_size())
+ .map_err(field_invalid)?;
+ true
+ }
+ _ => false,
}
} else if schema.sparse_vectors.contains_key(name) {
match point_vector {
@@ -848,10 +927,17 @@ impl Point {
}
/// A declarative Qdrant collection target. See the [module docs](self).
-#[derive(Clone)]
+///
+/// As a `mount_each!` / `use_mount!` or memoized function argument it
+/// fingerprints by its stable key, the connection key and collection name;
+/// the schema and runtime provider are not part of the identity.
+#[derive(Clone, Serialize)]
pub struct CollectionTarget {
+ conn_key: Arc<str>,
collection_name: Arc<str>,
+ #[serde(skip)]
schema: CollectionSchema,
+ #[serde(skip)]
points: TargetStateProvider<Point>,
}
@@ -886,6 +972,7 @@ pub async fn mount_collection_target_with_options(
let schema = ts.value().schema.clone();
let points = mount_target::<CollectionSpec, Point>(ctx, ts).await?;
Ok(CollectionTarget {
+ conn_key: Arc::from(conn.name()),
collection_name: Arc::from(name),
schema,
points,
@@ -969,6 +1056,7 @@ pub fn declare_collection_target_with_options(
let schema = ts.value().schema.clone();
let points = declare_target_state_with_child::<CollectionSpec, Point>(ctx, ts)?;
Ok(CollectionTarget {
+ conn_key: Arc::from(conn.name()),
collection_name: Arc::from(name),
schema,
points,
@@ -996,7 +1084,7 @@ impl CollectionTarget {
vector: PointVector::Single(vector),
payload,
};
- point.to_qdrant_vectors(&self.schema)?;
+ point.validate(&self.schema)?;
declare_target_state(ctx, self.points.target_state(key, point))
}
@@ -1018,7 +1106,7 @@ impl CollectionTarget {
vector: PointVector::Multi(vectors),
payload,
};
- point.to_qdrant_vectors(&self.schema)?;
+ point.validate(&self.schema)?;
declare_target_state(ctx, self.points.target_state(key, point))
}
@@ -1049,7 +1137,7 @@ impl CollectionTarget {
),
payload,
};
- point.to_qdrant_vectors(&self.schema)?;
+ point.validate(&self.schema)?;
declare_target_state(ctx, self.points.target_state(key, point))
}
}
@@ -1426,7 +1514,9 @@ fn point_sink(
deleted.iter().map(QdrantPointId::to_qdrant).collect();
if !upserts.is_empty() {
client
- .upsert_points(UpsertPointsBuilder::new(collection_name.clone(), upserts))
+ .upsert_points(
+ UpsertPointsBuilder::new(collection_name.clone(), upserts).wait(true),
+ )
.await
.map_err(|e| Error::engine(format!("qdrant upsert_points: {e}")))?;
}
@@ -1434,7 +1524,8 @@ fn point_sink(
client
.delete_points(
DeletePointsBuilder::new(collection_name.clone())
- .points(PointsIdsList { ids: deletes }),
+ .points(PointsIdsList { ids: deletes })
+ .wait(true),
)
.await
.map_err(|e| Error::engine(format!("qdrant delete_points: {e}")))?;
diff --git a/rust/sdk/cocoindex/src/connectors/turbopuffer.rs b/rust/sdk/cocoindex/src/connectors/turbopuffer.rs
index 74120ffa..25b2cfa7 100644
--- a/rust/sdk/cocoindex/src/connectors/turbopuffer.rs
+++ b/rust/sdk/cocoindex/src/connectors/turbopuffer.rs
@@ -496,8 +496,16 @@ struct Row {
attributes: Map<String, JsonValue>,
}
-/// Error if any element of a vector is non-finite (NaN/±Inf).
-fn reject_nonfinite_vector(id: &RowId, field: &str, v: &[f32]) -> Result<()> {
+/// Error if a vector does not have its field's length, or if any element is
+/// non-finite (NaN/±Inf).
+fn validate_vector(id: &RowId, field: &str, v: &[f32], def: &VectorDef) -> Result<()> {
+ if v.len() != def.schema.size {
+ return Err(Error::engine(format!(
+ "turbopuffer row {id}: vector field {field:?} has {} elements but the schema expects {}",
+ v.len(),
+ def.schema.size
+ )));
+ }
if v.iter().any(|x| !x.is_finite()) {
return Err(Error::engine(format!(
"turbopuffer row {id}: vector field {field:?} contains a non-finite (NaN/Inf) element"
@@ -510,22 +518,16 @@ impl Row {
/// The wire shape Turbopuffer expects: `{id, vector, ...attributes}` or
/// `{id, text_vector, image_vector, ...attributes}`.
fn to_upsert(&self, schema: &NamespaceSchema) -> Result<JsonValue> {
- // Reject non-finite vector elements: `json!` turns NaN/±Inf into JSON
+ // Check each vector against its field: a wrong length fails only this
+ // row here, not the whole write; and `json!` turns NaN/±Inf into JSON
// null, silently corrupting the embedding sent to Turbopuffer.
- match &self.vector {
- RowVector::Single(v) => reject_nonfinite_vector(&self.id, "vector", v)?,
- RowVector::Named(m) => {
- for (name, v) in m {
- reject_nonfinite_vector(&self.id, name, v)?;
- }
- }
- }
let mut obj = Map::new();
obj.insert("id".into(), self.id.to_json());
let vector_fields = schema.vector_fields();
let reserved = match (&vector_fields, &self.vector) {
- (VectorFields::Single(_), RowVector::Single(vector)) => {
+ (VectorFields::Single(def), RowVector::Single(vector)) => {
+ validate_vector(&self.id, DEFAULT_VECTOR_FIELD, vector, def)?;
obj.insert(DEFAULT_VECTOR_FIELD.into(), json!(vector));
schema.vector_field_names()
}
@@ -548,12 +550,13 @@ impl Row {
)));
}
for (name, vector) in row_vectors {
- if !vectors.contains_key(name) {
+ let Some(def) = vectors.get(name) else {
return Err(Error::engine(format!(
"turbopuffer row {}: unexpected vector field {:?}",
self.id, name
)));
- }
+ };
+ validate_vector(&self.id, name, vector, def)?;
obj.insert(name.clone(), json!(vector));
}
schema.vector_field_names()
@@ -587,10 +590,17 @@ impl Row {
}
/// A declarative Turbopuffer namespace target. See the [module docs](self).
-#[derive(Clone)]
+///
+/// As a `mount_each!` / `use_mount!` or memoized function argument it
+/// fingerprints by its stable key, the connection key and namespace; the
+/// schema and runtime provider are not part of the identity.
+#[derive(Clone, Serialize)]
pub struct NamespaceTarget {
+ conn_key: Arc<str>,
namespace: Arc<str>,
+ #[serde(skip)]
schema: NamespaceSchema,
+ #[serde(skip)]
rows: TargetStateProvider<Row>,
}
@@ -624,6 +634,7 @@ pub async fn mount_namespace_target_with_options(
let schema = ts.value().schema.clone();
let rows = mount_target::<NamespaceSpec, Row>(ctx, ts).await?;
Ok(NamespaceTarget {
+ conn_key: Arc::from(conn.name()),
namespace: Arc::from(name),
schema,
rows,
@@ -708,6 +719,7 @@ pub fn declare_namespace_target_with_options(
let schema = ts.value().schema.clone();
let rows = declare_target_state_with_child::<NamespaceSpec, Row>(ctx, ts)?;
Ok(NamespaceTarget {
+ conn_key: Arc::from(conn.name()),
namespace: Arc::from(name),
schema,
rows,
diff --git a/rust/sdk/cocoindex/src/connectors/valkey.rs b/rust/sdk/cocoindex/src/connectors/valkey.rs
index e2af1c97..30929402 100644
--- a/rust/sdk/cocoindex/src/connectors/valkey.rs
+++ b/rust/sdk/cocoindex/src/connectors/valkey.rs
@@ -505,9 +505,17 @@ impl Document {
}
/// A declarative Valkey index target — a handle to declare documents on.
-#[derive(Clone)]
+///
+/// As a `mount_each!` / `use_mount!` or memoized function argument it
+/// fingerprints by its stable key, the database key and index name; the
+/// vector dimension and runtime provider are not part of the identity.
+#[derive(Clone, Serialize)]
pub struct IndexTarget {
+ db_key: Arc<str>,
index_name: Arc<str>,
+ #[serde(skip)]
+ dimension: usize,
+ #[serde(skip)]
documents: TargetStateProvider<Document>,
}
@@ -571,9 +579,12 @@ pub fn declare_index_target_with_options(
) -> Result<IndexTarget> {
let ts = index_target_with_options(ctx, db, index_name, schema, options)?;
let name = ts.value().index_name.clone();
+ let dimension = ts.value().schema.vectors.schema.size;
let documents = declare_target_state_with_child::<IndexSpec, Document>(ctx, ts)?;
Ok(IndexTarget {
+ db_key: Arc::from(db.name()),
index_name: Arc::from(name),
+ dimension,
documents,
})
}
@@ -604,9 +615,12 @@ pub async fn mount_index_target_with_options(
) -> Result<IndexTarget> {
let ts = index_target_with_options(ctx, db, index_name, schema, options)?;
let name = ts.value().index_name.clone();
+ let dimension = ts.value().schema.vectors.schema.size;
let documents = mount_target::<IndexSpec, Document>(ctx, ts).await?;
Ok(IndexTarget {
+ db_key: Arc::from(db.name()),
index_name: Arc::from(name),
+ dimension,
documents,
})
}
@@ -616,9 +630,27 @@ impl IndexTarget {
&self.index_name
}
- /// Declare a document to upsert into the index.
+ /// Declare a document to upsert into the index. Its vector must have the
+ /// index's dimension and finite elements: the search module skips a hash
+ /// whose vector it cannot read, without an error, so such a document
+ /// would be stored but never found.
pub fn declare_document(&self, ctx: &Ctx, document: Document) -> Result<()> {
validate_name(&document.id, "doc_id")?;
+ if document.vector.len() != self.dimension {
+ return Err(Error::engine(format!(
+ "valkey document {:?}: vector has {} elements but index {:?} expects {}",
+ document.id,
+ document.vector.len(),
+ self.index_name,
+ self.dimension
+ )));
+ }
+ if document.vector.iter().any(|x| !x.is_finite()) {
+ return Err(Error::engine(format!(
+ "valkey document {:?}: vector contains a non-finite (NaN/Inf) element",
+ document.id
+ )));
+ }
for key in document.payload.iter().flat_map(|p| p.keys()) {
if key == VECTOR_FIELD_NAME {
return Err(Error::engine(format!(
diff --git a/rust/sdk/cocoindex/tests/qdrant_target.rs b/rust/sdk/cocoindex/tests/qdrant_target.rs
index a8b9b48c..89885105 100644
--- a/rust/sdk/cocoindex/tests/qdrant_target.rs
+++ b/rust/sdk/cocoindex/tests/qdrant_target.rs
@@ -497,3 +497,700 @@ async fn qdrant_target_stores_sparse_vectors_over_a_caller_built_client() -> Res
let _ = conn.client().delete_collection(&collection).await;
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Battle tests: id forms, malformed vectors, payload values, batch sizes,
+// out-of-band changes, failed writes, handles as mount arguments.
+// ---------------------------------------------------------------------------
+
+use std::sync::Arc;
+
+use cocoindex::connectors::qdrant::{CollectionTarget, QdrantPointId};
+use cocoindex::{Ctx, UpdateOptions};
+use qdrant_client::qdrant::{ScrollPointsBuilder, point_id::PointIdOptions};
+
+type Declare = Arc<dyn Fn(&Ctx, &CollectionTarget) -> Result<()> + Send + Sync>;
+
+/// One live collection with its own CocoIndex app, deleted by `cleanup`.
+struct Live {
+ conn: QdrantConnection,
+ collection: String,
+ app: cocoindex::App,
+ _dir: tempfile::TempDir,
+}
+
+impl Live {
+ async fn new(tag: &str) -> Option<Self> {
+ let Ok(url) = std::env::var("QDRANT_URL") else {
+ eprintln!("skipping live Qdrant test; QDRANT_URL is not set");
+ return None;
+ };
+ let nonce = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let conn = QdrantConnection::connect(&url).await.unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .provide_key(&DB, conn.clone())
+ .build()
+ .await
+ .unwrap()
+ .app(&format!("QdrantBattle_{tag}"))
+ .await
+ .unwrap();
+ Some(Self {
+ conn,
+ collection: format!("coco_qdrant_{tag}_{nonce}"),
+ app,
+ _dir: dir,
+ })
+ }
+
+ async fn run_with(
+ &self,
+ options: UpdateOptions,
+ schema: CollectionSchema,
+ user_managed: bool,
+ declare: Declare,
+ ) -> Result<()> {
+ let collection = self.collection.clone();
+ self.app
+ .update_with_options(options, move |ctx| async move {
+ let target = if user_managed {
+ qdrant::mount_collection_target_with_options(
+ &ctx,
+ &DB,
+ &collection,
+ schema,
+ cocoindex::ManagedTargetOptions::user_managed(),
+ )
+ .await?
+ } else {
+ qdrant::mount_collection_target(&ctx, &DB, &collection, schema).await?
+ };
+ declare(&ctx, &target)
+ })
+ .await
+ }
+
+ async fn run(&self, schema: CollectionSchema, declare: Declare) -> Result<()> {
+ self.run_with(UpdateOptions::default(), schema, false, declare)
+ .await
+ }
+
+ async fn count(&self) -> u64 {
+ self.conn
+ .client()
+ .count(qdrant_client::qdrant::CountPointsBuilder::new(&self.collection).exact(true))
+ .await
+ .unwrap()
+ .result
+ .unwrap()
+ .count
+ }
+
+ async fn exists(&self) -> bool {
+ self.conn
+ .client()
+ .collection_exists(&self.collection)
+ .await
+ .unwrap()
+ }
+
+ /// Every point's id (as text) and payload, sorted by id text.
+ async fn points(&self) -> Vec<(String, serde_json::Value)> {
+ let response = self
+ .conn
+ .client()
+ .scroll(
+ ScrollPointsBuilder::new(&self.collection)
+ .limit(100_000)
+ .with_payload(true),
+ )
+ .await
+ .unwrap();
+ let mut points: Vec<_> = response
+ .result
+ .into_iter()
+ .map(|p| {
+ let id = match p.id.unwrap().point_id_options.unwrap() {
+ PointIdOptions::Num(n) => n.to_string(),
+ PointIdOptions::Uuid(u) => u,
+ };
+ let payload: serde_json::Value = qdrant_client::Payload::from(p.payload).into();
+ (id, payload)
+ })
+ .collect();
+ points.sort_by(|a, b| a.0.cmp(&b.0));
+ points
+ }
+
+ async fn cleanup(self) {
+ let _ = self.conn.client().delete_collection(&self.collection).await;
+ }
+}
+
+fn dense3() -> CollectionSchema {
+ CollectionSchema::new(3, Distance::Cosine)
+}
+
+fn declare_points(points: Vec<(QdrantPointId, Vec<f32>, &'static str)>) -> Declare {
+ Arc::new(move |ctx, target| {
+ for (id, v, text) in &points {
+ target.declare_point(ctx, id.clone(), v.clone(), payload("f.md", text))?;
+ }
+ Ok(())
+ })
+}
+
+/// All text forms of one UUID name one point and one target state; integer
+/// ids cover the whole `u64` range; a string that is not a UUID is rejected at
+/// declare time.
+#[tokio::test]
+async fn qdrant_point_id_forms_name_one_point_when_available() -> Result<()> {
+ let Some(live) = Live::new("ids").await else {
+ return Ok(());
+ };
+ let canonical = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
+ let forms = [
+ ("{6BA7B810-9DAD-11D1-80B4-00C04FD430C8}", "braced"),
+ ("urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8", "urn"),
+ ("6ba7b8109dad11d180b400c04fd430c8", "simple"),
+ ("6BA7B810-9dad-11D1-80b4-00C04FD430C8", "mixed"),
+ ];
+ for (form, text) in forms {
+ live.run(
+ dense3(),
+ declare_points(vec![
+ (QdrantPointId::from(form), vec![1.0, 0.0, 0.0], text),
+ (QdrantPointId::from(0u64), vec![0.0, 1.0, 0.0], "zero"),
+ (QdrantPointId::from(u64::MAX), vec![0.0, 0.0, 1.0], "max"),
+ ]),
+ )
+ .await?;
+ let points = live.points().await;
+ let ids: Vec<&str> = points.iter().map(|(id, _)| id.as_str()).collect();
+ assert_eq!(ids, ["0", "18446744073709551615", canonical], "form {form}");
+ assert_eq!(
+ points[2].1["text"], text,
+ "form {form} updates the same point"
+ );
+ }
+
+ // The canonical form names the same point too.
+ live.run(
+ dense3(),
+ declare_points(vec![(
+ QdrantPointId::from(canonical),
+ vec![1.0, 0.0, 0.0],
+ "typed",
+ )]),
+ )
+ .await?;
+ let points = live.points().await;
+ assert_eq!(
+ points,
+ [(
+ canonical.to_string(),
+ json!({"filename": "f.md", "text": "typed"})
+ )],
+ "the integer points are removed"
+ );
+
+ // Strings that are not UUIDs fail at declare time and write nothing.
+ for bad in [
+ "42",
+ "doc/1",
+ "",
+ "6ba7b810-9dad-11d1-80b4",
+ "ü-🙂 id with spaces",
+ ] {
+ let err = live
+ .run(
+ dense3(),
+ declare_points(vec![(QdrantPointId::from(bad), vec![1.0, 0.0, 0.0], "bad")]),
+ )
+ .await
+ .expect_err(bad);
+ assert!(err.to_string().contains("must be UUIDs"), "{bad}: {err}");
+ }
+ assert_eq!(live.points().await.len(), 1, "failed runs write nothing");
+ live.cleanup().await;
+ Ok(())
+}
+
+/// Two text forms of one UUID declared in one run are one target state
+/// declared twice: the run fails, naming the key.
+#[tokio::test]
+async fn qdrant_two_forms_of_one_uuid_in_one_run_when_available() -> Result<()> {
+ let Some(live) = Live::new("dupid").await else {
+ return Ok(());
+ };
+ let result = live
+ .run(
+ dense3(),
+ declare_points(vec![
+ (
+ QdrantPointId::from("6ba7b810-9dad-11d1-80b4-00c04fd430c8"),
+ vec![1.0, 0.0, 0.0],
+ "lower",
+ ),
+ (
+ QdrantPointId::from("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"),
+ vec![0.0, 1.0, 0.0],
+ "upper",
+ ),
+ ]),
+ )
+ .await;
+ let err = result.expect_err("one target state declared twice");
+ assert!(
+ err.to_string().contains("already declared"),
+ "the error names the duplicate: {err}"
+ );
+ assert!(!live.exists().await || live.count().await == 0);
+ live.cleanup().await;
+ Ok(())
+}
+
+/// Vectors that do not fit the schema fail at declare time, with the point
+/// named, before anything is written: wrong length, empty, non-finite, and
+/// malformed multivectors and sparse vectors. A later valid run succeeds.
+#[tokio::test]
+async fn qdrant_malformed_vectors_fail_at_declare_when_available() -> Result<()> {
+ let Some(live) = Live::new("badvec").await else {
+ return Ok(());
+ };
+ let cases: Vec<(&str, Vec<f32>)> = vec![
+ ("short", vec![1.0, 0.0]),
+ ("long", vec![1.0, 0.0, 0.0, 0.0]),
+ ("empty", vec![]),
+ ("nan", vec![f32::NAN, 0.0, 0.0]),
+ ("inf", vec![f32::INFINITY, 0.0, 0.0]),
+ ];
+ for (name, v) in cases {
+ let err = live
+ .run(
+ dense3(),
+ declare_points(vec![
+ (QdrantPointId::from(1u64), vec![1.0, 0.0, 0.0], "ok"),
+ (QdrantPointId::from(2u64), v, "bad"),
+ ]),
+ )
+ .await
+ .expect_err(name);
+ let msg = err.to_string();
+ assert!(msg.contains("qdrant point 2"), "{name}: {msg}");
+ }
+ assert!(
+ !live.exists().await || live.count().await == 0,
+ "nothing written"
+ );
+
+ // Multivectors: no vectors, or one of the wrong length or non-finite.
+ for (name, vs) in [
+ ("no vectors", vec![]),
+ ("wrong inner length", vec![vec![1.0, 0.0, 0.0], vec![1.0]]),
+ ("nan inner", vec![vec![f32::NAN, 0.0, 0.0]]),
+ ] {
+ let vs: Vec<Vec<f32>> = vs;
+ let err = live
+ .run(
+ CollectionSchema::multivector(3, Distance::Cosine),
+ Arc::new(move |ctx, target| {
+ target.declare_multivector_point(ctx, 5u64, vs.clone(), payload("m", "m"))
+ }),
+ )
+ .await
+ .expect_err(name);
+ assert!(err.to_string().contains("qdrant point 5"), "{name}: {err}");
+ }
+
+ // Sparse vectors: unsorted indices and an empty vector are valid; a
+ // repeated index, mismatched lengths and a NaN weight are not.
+ let sparse_schema = || {
+ CollectionSchema::named([
+ (
+ "dense",
+ QdrantNamedVectorDef::from(QdrantVectorDef::f32(3, Distance::Cosine).unwrap()),
+ ),
+ ("sparse", QdrantSparseVectorDef::default().into()),
+ ])
+ .unwrap()
+ };
+ let named_point = |dense: Vec<f32>, indices: Vec<u32>, values: Vec<f32>| -> Declare {
+ Arc::new(move |ctx, target| {
+ target.declare_named_vectors_point(
+ ctx,
+ 9u64,
+ [
+ ("dense", NamedPointVector::Single(dense.clone())),
+ (
+ "sparse",
+ NamedPointVector::Sparse {
+ indices: indices.clone(),
+ values: values.clone(),
+ },
+ ),
+ ],
+ payload("s", "s"),
+ )
+ })
+ };
+ let unit = || vec![1.0, 0.0, 0.0];
+ live.run(
+ sparse_schema(),
+ named_point(unit(), vec![30, 10, 20], vec![3.0, 1.0, 2.0]),
+ )
+ .await?;
+ live.run(sparse_schema(), named_point(unit(), vec![], vec![]))
+ .await?;
+ assert_eq!(live.count().await, 1);
+ for (name, dense, indices, values) in [
+ ("repeated index", unit(), vec![1, 1], vec![1.0, 2.0]),
+ ("length mismatch", unit(), vec![1, 2], vec![1.0]),
+ ("nan weight", unit(), vec![1], vec![f32::NAN]),
+ ("named dense wrong length", vec![1.0], vec![], vec![]),
+ ] {
+ let err = live
+ .run(sparse_schema(), named_point(dense, indices, values))
+ .await
+ .expect_err(name);
+ assert!(err.to_string().contains("qdrant point 9"), "{name}: {err}");
+ }
+ assert_eq!(live.count().await, 1, "the valid point stays");
+ live.cleanup().await;
+ Ok(())
+}
+
+/// Payload values of every JSON type round-trip, nested objects and arrays
+/// included, and a multi-megabyte payload is stored. An integer beyond `i64`
+/// (Qdrant stores integers as `i64`) fails at declare time rather than being
+/// rounded to a float.
+#[tokio::test]
+async fn qdrant_payload_values_round_trip_when_available() -> Result<()> {
+ let Some(live) = Live::new("payload").await else {
+ return Ok(());
+ };
+ let rich = json!({
+ "null": null,
+ "t": true,
+ "f": false,
+ "i_min": i64::MIN,
+ "i_max": i64::MAX,
+ "neg": -7,
+ "float": 1.5,
+ "tiny": 1e-300,
+ "text": "héllo \"wörld\" \n\t 🙂 \u{0}",
+ "empty_text": "",
+ "empty_list": [],
+ "empty_obj": {},
+ "list": [1, "two", 3.5, null, [4, [5]], {"six": 6}],
+ "nested": {"a": {"b": {"c": {"d": [true, {"e": "deep"}]}}}},
+ "key with spaces and . dots": 1,
+ });
+ let big = "x".repeat(4 * 1024 * 1024);
+ {
+ let rich = rich.clone();
+ let big = big.clone();
+ live.run(
+ dense3(),
+ Arc::new(move |ctx, target| {
+ target.declare_point(
+ ctx,
+ 1u64,
+ vec![1.0, 0.0, 0.0],
+ rich.as_object().unwrap().clone(),
+ )?;
+ target.declare_point(
+ ctx,
+ 2u64,
+ vec![0.0, 1.0, 0.0],
+ json!({ "big": big }).as_object().unwrap().clone(),
+ )
+ }),
+ )
+ .await?;
+ }
+ let points = live.points().await;
+ assert_eq!(points[0].1, rich);
+ assert_eq!(points[1].1["big"].as_str().map(str::len), Some(big.len()));
+
+ for (name, value) in [
+ ("u64 beyond i64", json!({ "n": u64::MAX })),
+ (
+ "nested u64 beyond i64",
+ json!({ "a": [{ "n": (i64::MAX as u64) + 1 }] }),
+ ),
+ ] {
+ let err = live
+ .run(
+ dense3(),
+ Arc::new(move |ctx, target| {
+ target.declare_point(
+ ctx,
+ 3u64,
+ vec![1.0, 0.0, 0.0],
+ value.as_object().unwrap().clone(),
+ )
+ }),
+ )
+ .await
+ .expect_err(name);
+ assert!(err.to_string().contains("qdrant point 3"), "{name}: {err}");
+ }
+ live.cleanup().await;
+ Ok(())
+}
+
+fn n_points(n: u64, tag: &'static str) -> Declare {
+ Arc::new(move |ctx, target| {
+ for i in 0..n {
+ let x = (i % 97) as f32 + 1.0;
+ target.declare_point(ctx, i, vec![x, 1.0, (i % 7) as f32], payload("f", tag))?;
+ }
+ Ok(())
+ })
+}
+
+/// Batches on both sides of the 500 and 1000 marks, growing and shrinking.
+#[tokio::test]
+async fn qdrant_batches_around_chunk_boundaries_when_available() -> Result<()> {
+ let Some(live) = Live::new("batch").await else {
+ return Ok(());
+ };
+ for n in [499u64, 500, 501, 999, 1000, 1001, 2500, 1, 0, 1000] {
+ live.run(dense3(), n_points(n, "v1")).await?;
+ assert_eq!(live.count().await, n, "after declaring {n} points");
+ }
+ // Every point's payload changes at once.
+ live.run(dense3(), n_points(1000, "v2")).await?;
+ let points = live.points().await;
+ assert!(points.iter().all(|(_, p)| p["text"] == "v2"));
+ live.cleanup().await;
+ Ok(())
+}
+
+/// A very large batch: 100k 128-dimension points in one run, then all of them
+/// deleted. Slow; run with
+/// QDRANT_URL=http://localhost:6334 cargo test -p cocoindex --features qdrant,testing \
+/// --test qdrant_target qdrant_very_large_batch -- --ignored
+#[tokio::test]
+#[ignore]
+async fn qdrant_very_large_batch_when_available() -> Result<()> {
+ let Some(live) = Live::new("huge").await else {
+ return Ok(());
+ };
+ const N: u64 = 100_000;
+ let schema = || CollectionSchema::new(128, Distance::Dot);
+ let start = std::time::Instant::now();
+ live.run(
+ schema(),
+ Arc::new(|ctx, target| {
+ for i in 0..N {
+ let mut v = vec![0.0f32; 128];
+ v[(i % 128) as usize] = 1.0;
+ target.declare_point(ctx, i, v, payload("f", "huge"))?;
+ }
+ Ok(())
+ }),
+ )
+ .await?;
+ eprintln!("upserted {N} points in {:?}", start.elapsed());
+ assert_eq!(live.count().await, N);
+ let start = std::time::Instant::now();
+ live.run(schema(), Arc::new(|_, _| Ok(()))).await?;
+ eprintln!("deleted {N} points in {:?}", start.elapsed());
+ assert_eq!(live.count().await, 0);
+ live.cleanup().await;
+ Ok(())
+}
+
+/// A collection deleted behind CocoIndex's back is recreated on the next run;
+/// a full reprocess writes its points again.
+#[tokio::test]
+async fn qdrant_collection_deleted_out_of_band_is_recreated_when_available() -> Result<()> {
+ let Some(live) = Live::new("oob").await else {
+ return Ok(());
+ };
+ live.run(dense3(), n_points(10, "v1")).await?;
+ live.conn
+ .client()
+ .delete_collection(&live.collection)
+ .await
+ .unwrap();
+ live.run(dense3(), n_points(10, "v1")).await?;
+ assert!(live.exists().await, "the collection is recreated");
+ live.run_with(
+ UpdateOptions {
+ full_reprocess: true,
+ ..Default::default()
+ },
+ dense3(),
+ false,
+ n_points(10, "v1"),
+ )
+ .await?;
+ assert_eq!(
+ live.count().await,
+ 10,
+ "a full reprocess restores the points"
+ );
+ live.cleanup().await;
+ Ok(())
+}
+
+/// A write that fails (the user-managed collection does not exist yet) fails
+/// the run and records nothing: once the collection exists, the next run
+/// writes every point.
+#[tokio::test]
+async fn qdrant_failed_write_is_retried_by_the_next_run_when_available() -> Result<()> {
+ let Some(live) = Live::new("retry").await else {
+ return Ok(());
+ };
+ let err = live
+ .run_with(
+ UpdateOptions::default(),
+ dense3(),
+ true,
+ n_points(1200, "v1"),
+ )
+ .await
+ .expect_err("the collection does not exist");
+ assert!(err.to_string().contains("qdrant"), "{err}");
+
+ live.conn
+ .client()
+ .create_collection(
+ qdrant_client::qdrant::CreateCollectionBuilder::new(&live.collection).vectors_config(
+ qdrant_client::qdrant::VectorParamsBuilder::new(
+ 3,
+ qdrant_client::qdrant::Distance::Cosine,
+ ),
+ ),
+ )
+ .await
+ .unwrap();
+ live.run_with(
+ UpdateOptions::default(),
+ dense3(),
+ true,
+ n_points(1200, "v1"),
+ )
+ .await?;
+ assert_eq!(live.count().await, 1200);
+ live.cleanup().await;
+ Ok(())
+}
+
+/// Changing the element type is a schema change: the collection is recreated
+/// with the new datatype and refilled. Qdrant has no f64 vectors: an f64
+/// schema is stored as f32.
+#[tokio::test]
+async fn qdrant_element_type_change_recreates_the_collection_when_available() -> Result<()> {
+ use cocoindex::resources::schema::{VectorElementType, VectorSchema};
+ let Some(live) = Live::new("dtype").await else {
+ return Ok(());
+ };
+ let datatype = |live: &Live| {
+ let conn = live.conn.clone();
+ let name = live.collection.clone();
+ async move {
+ let info = conn
+ .client()
+ .collection_info(&name)
+ .await
+ .unwrap()
+ .result
+ .unwrap();
+ let params = info.config.unwrap().params.unwrap().vectors_config.unwrap();
+ match params.config.unwrap() {
+ qdrant_client::qdrant::vectors_config::Config::Params(p) => p.datatype,
+ other => panic!("unexpected {other:?}"),
+ }
+ }
+ };
+ let schema = |t: VectorElementType| {
+ CollectionSchema::from_vector_schema(
+ VectorSchema {
+ element_type: t,
+ ..VectorSchema::f32(3)
+ },
+ Distance::Cosine,
+ )
+ .unwrap()
+ };
+ live.run(schema(VectorElementType::Float32), n_points(5, "f32"))
+ .await?;
+ assert_eq!(datatype(&live).await.unwrap_or(0), 0);
+ live.run(schema(VectorElementType::Float16), n_points(5, "f16"))
+ .await?;
+ assert_eq!(
+ datatype(&live).await,
+ Some(qdrant_client::qdrant::Datatype::Float16 as i32)
+ );
+ assert_eq!(
+ live.count().await,
+ 5,
+ "the recreated collection is refilled"
+ );
+ live.run(schema(VectorElementType::Float64), n_points(5, "f64"))
+ .await?;
+ assert_eq!(
+ datatype(&live).await.unwrap_or(0),
+ 0,
+ "f64 is stored as f32"
+ );
+ assert_eq!(live.count().await, 5);
+ // A distance change recreates it too.
+ live.run(
+ CollectionSchema::new(3, Distance::Euclid),
+ n_points(5, "l2"),
+ )
+ .await?;
+ assert_eq!(live.count().await, 5);
+ live.cleanup().await;
+ Ok(())
+}
+
+static QDRANT_ARG_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+#[cocoindex::function]
+async fn declare_qdrant_point_in_component(
+ ctx: &Ctx,
+ id: u64,
+ target: CollectionTarget,
+) -> Result<()> {
+ QDRANT_ARG_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ target.declare_point(ctx, id, vec![1.0, 0.0, id as f32], payload("f", "arg"))
+}
+
+/// A collection handle is a `mount_each!` argument, keyed by its collection.
+#[tokio::test]
+async fn qdrant_collection_target_is_a_mount_argument_when_available() -> Result<()> {
+ let Some(live) = Live::new("arg").await else {
+ return Ok(());
+ };
+ let calls = || QDRANT_ARG_CALLS.load(std::sync::atomic::Ordering::SeqCst);
+ for round in 0..2 {
+ let collection = live.collection.clone();
+ live.app
+ .run(move |ctx| async move {
+ let target =
+ qdrant::mount_collection_target(&ctx, &DB, &collection, dense3()).await?;
+ cocoindex::use_mount_each!(
+ vec![("1".to_string(), 1u64), ("2".to_string(), 2u64)],
+ |id| declare_qdrant_point_in_component(ctx, id, target.clone())
+ )
+ .await?;
+ Ok(())
+ })
+ .await?;
+ assert_eq!(calls(), 2, "round {round}: unchanged children are skipped");
+ assert_eq!(live.count().await, 2);
+ }
+ live.cleanup().await;
+ Ok(())
+}
diff --git a/rust/sdk/cocoindex/tests/turbopuffer_target.rs b/rust/sdk/cocoindex/tests/turbopuffer_target.rs
index e6036961..09da20bb 100644
--- a/rust/sdk/cocoindex/tests/turbopuffer_target.rs
+++ b/rust/sdk/cocoindex/tests/turbopuffer_target.rs
@@ -351,3 +351,421 @@ async fn turbopuffer_integer_row_ids_are_written_as_numbers_on_mock_server() ->
);
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Battle tests on a mock Turbopuffer API: malformed vectors, row ids,
+// attribute values, batch sizes, schema changes, a failed write retried by the
+// next run, handles as mount arguments.
+// ---------------------------------------------------------------------------
+
+use std::sync::Arc;
+
+use cocoindex::Ctx;
+use cocoindex::connectors::turbopuffer::{NamespaceTarget, RowId, VectorDef};
+use wiremock::matchers::{method, path};
+use wiremock::{Mock, MockServer, ResponseTemplate};
+
+type Declare = Arc<dyn Fn(&Ctx, &NamespaceTarget) -> Result<()> + Send + Sync>;
+
+/// A mock Turbopuffer server answering every write and delete of `namespace`
+/// with 200, and an app writing to it.
+struct Mocked {
+ server: MockServer,
+ namespace: &'static str,
+ app: cocoindex::App,
+ _dir: tempfile::TempDir,
+}
+
+impl Mocked {
+ async fn new(namespace: &'static str) -> Self {
+ let server = MockServer::start().await;
+ for verb in ["POST", "DELETE"] {
+ Mock::given(method(verb))
+ .and(path(format!("/v2/namespaces/{namespace}")))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+ }
+ let conn = TurbopufferConnection::new("mock", "key").with_base_url(server.uri());
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .provide_key(&DB, conn)
+ .build()
+ .await
+ .unwrap()
+ .app(namespace)
+ .await
+ .unwrap();
+ Self {
+ server,
+ namespace,
+ app,
+ _dir: dir,
+ }
+ }
+
+ async fn run(&self, schema: NamespaceSchema, declare: Declare) -> Result<()> {
+ let namespace = self.namespace;
+ self.app
+ .update(move |ctx| async move {
+ let target =
+ turbopuffer::mount_namespace_target(&ctx, &DB, namespace, schema).await?;
+ declare(&ctx, &target)
+ })
+ .await
+ }
+
+ /// Every request so far: `(method, JSON body or Null)`.
+ async fn requests(&self) -> Vec<(String, serde_json::Value)> {
+ self.server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .map(|r| {
+ (
+ r.method.to_string(),
+ r.body_json().unwrap_or(serde_json::Value::Null),
+ )
+ })
+ .collect()
+ }
+
+ async fn writes(&self) -> Vec<serde_json::Value> {
+ self.requests()
+ .await
+ .into_iter()
+ .filter(|(m, _)| m == "POST")
+ .map(|(_, body)| body)
+ .collect()
+ }
+}
+
+fn schema3() -> NamespaceSchema {
+ NamespaceSchema::new(3, DistanceMetric::CosineDistance)
+}
+
+fn n_rows(n: u64, text: &'static str) -> Declare {
+ Arc::new(move |ctx, target| {
+ for i in 0..n {
+ target.declare_row(ctx, i, vec![1.0, (i % 5) as f32, 0.0], attrs(text))?;
+ }
+ Ok(())
+ })
+}
+
+fn array_len(body: &serde_json::Value, key: &str) -> usize {
+ body.get(key).and_then(|v| v.as_array()).map_or(0, Vec::len)
+}
+
+/// Vectors that do not fit the schema fail at declare time with the row
+/// named, and nothing is sent: wrong length, empty, non-finite, and a named
+/// field of the wrong length. Reserved attribute names fail the same way.
+#[tokio::test]
+async fn turbopuffer_malformed_rows_fail_at_declare_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_bad_rows").await;
+ for (name, v) in [
+ ("short", vec![1.0, 0.0]),
+ ("long", vec![1.0, 0.0, 0.0, 0.0]),
+ ("empty", vec![]),
+ ("nan", vec![f32::NAN, 0.0, 0.0]),
+ ("inf", vec![0.0, f32::INFINITY, 0.0]),
+ ] {
+ let err = mock
+ .run(
+ schema3(),
+ Arc::new(move |ctx, target| {
+ target.declare_row(ctx, "ok", vec![1.0, 0.0, 0.0], attrs("ok"))?;
+ target.declare_row(ctx, "bad", v.clone(), attrs("bad"))
+ }),
+ )
+ .await
+ .expect_err(name);
+ assert!(err.to_string().contains("row \"bad\""), "{name}: {err}");
+ }
+ for reserved in ["id", "vector"] {
+ let err = mock
+ .run(
+ schema3(),
+ Arc::new(move |ctx, target| {
+ let attributes = json!({ reserved: 1 }).as_object().unwrap().clone();
+ target.declare_row(ctx, "r", vec![1.0, 0.0, 0.0], attributes)
+ }),
+ )
+ .await
+ .expect_err(reserved);
+ assert!(err.to_string().contains("reserved"), "{reserved}: {err}");
+ }
+ let named = NamespaceSchema::named(
+ [
+ ("text_vec", VectorDef::f32(3).unwrap()),
+ ("image_vec", VectorDef::f32(2).unwrap()),
+ ],
+ DistanceMetric::CosineDistance,
+ )?;
+ let err = mock
+ .run(
+ named,
+ Arc::new(|ctx, target| {
+ target.declare_named_row(
+ ctx,
+ "n",
+ [
+ ("text_vec", vec![1.0, 0.0, 0.0]),
+ ("image_vec", vec![1.0, 0.0, 0.0]),
+ ],
+ attrs("n"),
+ )
+ }),
+ )
+ .await
+ .expect_err("named wrong length");
+ assert!(err.to_string().contains("\"image_vec\""), "{err}");
+ assert!(mock.writes().await.is_empty(), "nothing is sent");
+ Ok(())
+}
+
+/// Row ids: a string with any characters is sent as is, a string `"7"` and an
+/// integer `7` are two rows, and an integer beyond `i64` fails at declare.
+#[tokio::test]
+async fn turbopuffer_row_id_forms_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_row_ids").await;
+ let ids: Vec<RowId> = vec![
+ RowId::from("7"),
+ RowId::from(7u64),
+ RowId::from("a/b c:d?e#f 🙂 \"q\""),
+ RowId::from(""),
+ RowId::from(0u64),
+ RowId::from(i64::MAX as u64),
+ ];
+ {
+ let ids = ids.clone();
+ mock.run(
+ schema3(),
+ Arc::new(move |ctx, target| {
+ for id in &ids {
+ target.declare_row(ctx, id.clone(), vec![1.0, 0.0, 0.0], attrs("x"))?;
+ }
+ Ok(())
+ }),
+ )
+ .await?;
+ }
+ let writes = mock.writes().await;
+ let mut sent: Vec<String> = writes[0]["upsert_rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|row| row["id"].to_string())
+ .collect();
+ sent.sort();
+ let mut expected: Vec<String> = [
+ json!("7"),
+ json!(7),
+ json!("a/b c:d?e#f 🙂 \"q\""),
+ json!(""),
+ json!(0),
+ json!(i64::MAX),
+ ]
+ .iter()
+ .map(|v| v.to_string())
+ .collect();
+ expected.sort();
+ assert_eq!(sent, expected);
+
+ let err = mock
+ .run(
+ schema3(),
+ Arc::new(|ctx, target| {
+ target.declare_row(ctx, u64::MAX, vec![1.0, 0.0, 0.0], attrs("x"))
+ }),
+ )
+ .await
+ .expect_err("u64 beyond i64");
+ assert!(err.to_string().contains("out of range"), "{err}");
+ Ok(())
+}
+
+/// Attribute values of every JSON type, nested ones included, are sent
+/// unchanged.
+#[tokio::test]
+async fn turbopuffer_attribute_values_are_sent_unchanged_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_attrs").await;
+ let rich = json!({
+ "null": null,
+ "t": true,
+ "i_min": i64::MIN,
+ "u_max": u64::MAX,
+ "float": 0.1,
+ "text": "héllo \"wörld\" \n 🙂",
+ "list": [1, "two", [3], {"four": 4}],
+ "nested": {"a": {"b": {"c": [null, {"d": "deep"}]}}},
+ "big": "z".repeat(1024 * 1024),
+ });
+ {
+ let rich = rich.clone();
+ mock.run(
+ schema3(),
+ Arc::new(move |ctx, target| {
+ target.declare_row(
+ ctx,
+ 1u64,
+ vec![1.0, 0.0, 0.0],
+ rich.as_object().unwrap().clone(),
+ )
+ }),
+ )
+ .await?;
+ }
+ let row = mock.writes().await[0]["upsert_rows"][0].clone();
+ for (k, v) in rich.as_object().unwrap() {
+ assert_eq!(&row[k], v, "attribute {k}");
+ }
+ Ok(())
+}
+
+/// Every batch goes out as one write, whatever its size, and reconciles to
+/// the right upserts and deletes around the 500 and 1000 marks.
+#[tokio::test]
+async fn turbopuffer_batches_around_chunk_boundaries_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_batches").await;
+ let mut prev = 0u64;
+ let mut expected_writes = 0;
+ for n in [499u64, 500, 501, 999, 1000, 1001, 2500, 1, 0] {
+ mock.run(schema3(), n_rows(n, "v1")).await?;
+ let writes = mock.writes().await;
+ let added = n.saturating_sub(prev) as usize;
+ let removed = prev.saturating_sub(n) as usize;
+ if added + removed > 0 {
+ expected_writes += 1;
+ }
+ assert_eq!(
+ writes.len(),
+ expected_writes,
+ "{n} rows: one write per batch"
+ );
+ if added + removed > 0 {
+ let last = writes.last().unwrap();
+ assert_eq!(array_len(last, "upsert_rows"), added, "{n} rows: upserts");
+ assert_eq!(array_len(last, "deletes"), removed, "{n} rows: deletes");
+ }
+ prev = n;
+ }
+ Ok(())
+}
+
+/// A write the server rejects fails the run and records nothing; the next
+/// run sends every row again.
+#[tokio::test]
+async fn turbopuffer_failed_write_is_retried_by_the_next_run_on_mock_server() -> Result<()> {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v2/namespaces/ns_retry"))
+ .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
+ .up_to_n_times(1)
+ .with_priority(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/v2/namespaces/ns_retry"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .with_priority(2)
+ .mount(&server)
+ .await;
+ let conn = TurbopufferConnection::new("mock", "key").with_base_url(server.uri());
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .provide_key(&DB, conn)
+ .build()
+ .await?
+ .app("TurbopufferRetry")
+ .await?;
+ let run = || {
+ app.update(|ctx| async move {
+ let target =
+ turbopuffer::mount_namespace_target(&ctx, &DB, "ns_retry", schema3()).await?;
+ n_rows(700, "v1")(&ctx, &target)
+ })
+ };
+ let err = run().await.expect_err("the first write fails");
+ assert!(err.to_string().contains("500"), "{err}");
+ run().await?;
+ // Unchanged after a successful write: nothing more is sent.
+ run().await?;
+ let bodies: Vec<serde_json::Value> = server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .map(|r| r.body_json().unwrap())
+ .collect();
+ assert_eq!(bodies.len(), 2);
+ assert_eq!(
+ array_len(&bodies[1], "upsert_rows"),
+ 700,
+ "every row is resent"
+ );
+ Ok(())
+}
+
+/// A dimension change deletes the namespace and writes every row again with
+/// the new schema.
+#[tokio::test]
+async fn turbopuffer_dimension_change_clears_and_refills_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_dims").await;
+ mock.run(schema3(), n_rows(3, "v1")).await?;
+ mock.run(
+ NamespaceSchema::new(4, DistanceMetric::CosineDistance),
+ Arc::new(|ctx, target| {
+ for i in 0..3u64 {
+ target.declare_row(ctx, i, vec![1.0, 0.0, 0.0, 0.0], attrs("v2"))?;
+ }
+ Ok(())
+ }),
+ )
+ .await?;
+ let requests = mock.requests().await;
+ let methods: Vec<&str> = requests.iter().map(|(m, _)| m.as_str()).collect();
+ assert_eq!(methods, ["POST", "DELETE", "POST"]);
+ let last = &requests[2].1;
+ assert_eq!(array_len(last, "upsert_rows"), 3);
+ assert_eq!(last["schema"]["vector"]["type"], "[4]f32");
+ Ok(())
+}
+
+static TPUF_ARG_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+#[cocoindex::function]
+async fn declare_tpuf_row_in_component(ctx: &Ctx, id: u64, target: NamespaceTarget) -> Result<()> {
+ TPUF_ARG_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ target.declare_row(ctx, id, vec![1.0, 0.0, 0.0], attrs("arg"))
+}
+
+/// A namespace handle is a `mount_each!` argument, keyed by its namespace.
+#[tokio::test]
+async fn turbopuffer_namespace_target_is_a_mount_argument_on_mock_server() -> Result<()> {
+ let mock = Mocked::new("ns_handle_arg").await;
+ let calls = || TPUF_ARG_CALLS.load(std::sync::atomic::Ordering::SeqCst);
+ for round in 0..2 {
+ mock.app
+ .run(|ctx| async move {
+ let target =
+ turbopuffer::mount_namespace_target(&ctx, &DB, "ns_handle_arg", schema3())
+ .await?;
+ cocoindex::use_mount_each!(
+ vec![("1".to_string(), 1u64), ("2".to_string(), 2u64)],
+ |id| declare_tpuf_row_in_component(ctx, id, target.clone())
+ )
+ .await?;
+ Ok(())
+ })
+ .await?;
+ assert_eq!(calls(), 2, "round {round}: unchanged children are skipped");
+ // Each child component writes its own row; the second round writes
+ // nothing.
+ assert_eq!(mock.writes().await.len(), 2, "round {round}");
+ }
+ Ok(())
+}
diff --git a/rust/sdk/cocoindex/tests/valkey_target.rs b/rust/sdk/cocoindex/tests/valkey_target.rs
index 6e320d85..b34a11e4 100644
--- a/rust/sdk/cocoindex/tests/valkey_target.rs
+++ b/rust/sdk/cocoindex/tests/valkey_target.rs
@@ -332,9 +332,12 @@ async fn valkey_user_managed_index_is_left_in_place_when_available() {
index_exists(&uri, &index_name).await,
"a user-managed index no longer declared is left in place"
);
+ // As with the other connectors' user-managed containers (see the LanceDB
+ // test `lancedb_user_managed_target_does_not_create_table`), the user owns
+ // what is in the index too: undeclaring it leaves its documents.
assert!(
- !key_exists(&uri, &doc_key).await,
- "its documents are removed"
+ key_exists(&uri, &doc_key).await,
+ "its documents are left in place too"
);
app.run(declare(index_name.clone())).await.unwrap();
@@ -343,7 +346,13 @@ async fn valkey_user_managed_index_is_left_in_place_when_available() {
index_exists(&uri, &index_name).await,
"drop_state leaves a user-managed index in place"
);
- assert!(!key_exists(&uri, &doc_key).await);
+ assert!(key_exists(&uri, &doc_key).await, "and its documents");
+
+ let _: redis::Value = redis::cmd("DEL")
+ .arg(&doc_key)
+ .query_async(&mut conn)
+ .await
+ .unwrap();
let _: redis::Value = redis::cmd("FT.DROPINDEX")
.arg(&index_name)
@@ -483,3 +492,428 @@ async fn valkey_connects_with_a_client_config_and_a_caller_built_client_when_ava
assert!(!index_exists(&uri, &index_name).await);
}
}
+
+// ---------------------------------------------------------------------------
+// Battle tests: malformed vectors, doc ids, payload values, schema changes,
+// out-of-band drops, batch sizes, handles as mount arguments.
+// ---------------------------------------------------------------------------
+
+use std::sync::Arc;
+
+use cocoindex::connectors::valkey::IndexTarget;
+use cocoindex::{Ctx, Result, UpdateOptions};
+
+type Declare = Arc<dyn Fn(&Ctx, &IndexTarget) -> Result<()> + Send + Sync>;
+
+/// One live index with its own CocoIndex app.
+struct Live {
+ uri: String,
+ index: String,
+ app: cocoindex::App,
+ _dir: tempfile::TempDir,
+}
+
+impl Live {
+ async fn new(tag: &str) -> Option<Self> {
+ let Some(vk) = try_connect().await else {
+ eprintln!("skipping live Valkey test; VALKEY_URI is not set or unavailable");
+ return None;
+ };
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join("db"))
+ .provide_key(&VK, vk)
+ .build()
+ .await
+ .unwrap()
+ .app(&format!("ValkeyBattle_{tag}"))
+ .await
+ .unwrap();
+ Some(Self {
+ uri: std::env::var("VALKEY_URI").unwrap(),
+ index: format!("idx_{tag}_{}", nonce()),
+ app,
+ _dir: dir,
+ })
+ }
+
+ async fn run_with(
+ &self,
+ options: UpdateOptions,
+ schema: IndexSchema,
+ declare: Declare,
+ ) -> Result<()> {
+ let index = self.index.clone();
+ self.app
+ .update_with_options(options, move |ctx| async move {
+ let target = valkey::mount_index_target(&ctx, &VK, index, schema).await?;
+ declare(&ctx, &target)
+ })
+ .await
+ }
+
+ async fn run(&self, schema: IndexSchema, declare: Declare) -> Result<()> {
+ self.run_with(UpdateOptions::default(), schema, declare)
+ .await
+ }
+
+ async fn conn(&self) -> redis::aio::MultiplexedConnection {
+ redis::Client::open(self.uri.as_str())
+ .unwrap()
+ .get_multiplexed_async_connection()
+ .await
+ .unwrap()
+ }
+
+ /// `(num_docs, hash_indexing_failures)` from `FT.INFO`.
+ async fn indexed(&self) -> (i64, i64) {
+ let info: Vec<redis::Value> = redis::cmd("FT.INFO")
+ .arg(&self.index)
+ .query_async(&mut self.conn().await)
+ .await
+ .unwrap();
+ let mut num_docs = -1;
+ let mut failures = -1;
+ for pair in info.chunks(2) {
+ let Ok(key) = redis::from_redis_value::<String>(&pair[0]) else {
+ continue;
+ };
+ let number = || {
+ let text: String = redis::from_redis_value(&pair[1]).unwrap();
+ text.parse::<f64>().unwrap() as i64
+ };
+ match key.as_str() {
+ "num_docs" => num_docs = number(),
+ "hash_indexing_failures" => failures = number(),
+ _ => {}
+ }
+ }
+ (num_docs, failures)
+ }
+
+ async fn drop_index_out_of_band(&self) {
+ let _: redis::Value = redis::cmd("FT.DROPINDEX")
+ .arg(&self.index)
+ .query_async(&mut self.conn().await)
+ .await
+ .unwrap();
+ }
+
+ async fn cleanup(self) {
+ let _: redis::RedisResult<redis::Value> = redis::cmd("FT.DROPINDEX")
+ .arg(&self.index)
+ .arg("DD")
+ .query_async(&mut self.conn().await)
+ .await;
+ }
+}
+
+async fn schema_with(dim: usize, fields: Vec<FieldDef>) -> IndexSchema {
+ IndexSchema::create(
+ VectorDef {
+ schema: &VectorSchema::f32(dim),
+ distance: Distance::Cosine,
+ algorithm: VectorAlgorithm::Hnsw,
+ },
+ fields,
+ )
+ .await
+ .unwrap()
+}
+
+fn n_docs(n: usize, tag: &'static str) -> Declare {
+ Arc::new(move |ctx, target| {
+ for i in 0..n {
+ target.declare_document(
+ ctx,
+ doc(&format!("d{i}"), vec![1.0, (i % 13) as f32, 0.5], tag),
+ )?;
+ }
+ Ok(())
+ })
+}
+
+/// A vector of the wrong length, an empty one, or one with a NaN/Inf fails at
+/// declare time: the search module would store the hash but never index it.
+#[tokio::test]
+async fn valkey_malformed_vectors_fail_at_declare_when_available() {
+ let Some(live) = Live::new("badvec").await else {
+ return;
+ };
+ for (name, v) in [
+ ("short", vec![1.0, 0.0]),
+ ("long", vec![1.0, 0.0, 0.0, 0.0]),
+ ("empty", vec![]),
+ ("nan", vec![f32::NAN, 0.0, 0.0]),
+ ("inf", vec![0.0, f32::NEG_INFINITY, 0.0]),
+ ] {
+ let err = live
+ .run(
+ schema().await,
+ Arc::new(move |ctx, target| {
+ target.declare_document(ctx, doc("ok", vec![1.0, 0.0, 0.0], "ok"))?;
+ target.declare_document(ctx, doc("bad", v.clone(), "bad"))
+ }),
+ )
+ .await
+ .expect_err(name);
+ assert!(err.to_string().contains("\"bad\""), "{name}: {err}");
+ }
+ live.run(schema().await, n_docs(3, "v1")).await.unwrap();
+ assert_eq!(
+ live.indexed().await,
+ (3, 0),
+ "every stored document is indexed"
+ );
+ live.cleanup().await;
+}
+
+/// Document ids are restricted to `[A-Za-z0-9_-]+` (as in Python): an id with
+/// a separator, a space, a glob character or non-ASCII text is rejected.
+#[tokio::test]
+async fn valkey_document_ids_are_validated_when_available() {
+ let Some(live) = Live::new("ids").await else {
+ return;
+ };
+ live.run(
+ schema().await,
+ Arc::new(|ctx, target| {
+ for id in ["a", "A-b_9", "0", "x".repeat(512).as_str()] {
+ target.declare_document(ctx, doc(id, vec![1.0, 0.0, 0.0], id))?;
+ }
+ Ok(())
+ }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(live.indexed().await.0, 4);
+ for bad in ["", "a:b", "a b", "a*", "ü", "a/b", "{a}"] {
+ let err = live
+ .run(
+ schema().await,
+ Arc::new(move |ctx, target| {
+ target.declare_document(ctx, doc(bad, vec![1.0, 0.0, 0.0], "bad"))
+ }),
+ )
+ .await
+ .expect_err(bad);
+ assert!(err.to_string().contains("doc_id"), "{bad}: {err}");
+ }
+ live.cleanup().await;
+}
+
+/// Payload values of each kind are stored as their text form, a type change
+/// of an unchanged-looking value (`1` vs `"1"`) is a change, and a large
+/// payload is stored whole.
+#[tokio::test]
+async fn valkey_payload_values_are_stored_as_text_when_available() {
+ let Some(live) = Live::new("payload").await else {
+ return;
+ };
+ let big = "y".repeat(2 * 1024 * 1024);
+ let declare = |price: PayloadValue, big: String| -> Declare {
+ Arc::new(move |ctx, target| {
+ target.declare_document(
+ ctx,
+ Document::new("p", vec![1.0, 0.0, 0.0]).with_payload([
+ ("text", PayloadValue::from("héllo 🙂 \"q\" \n")),
+ ("price", price.clone()),
+ ("neg", PayloadValue::from(i64::MIN)),
+ ("float", PayloadValue::from(0.1f64)),
+ ("empty", PayloadValue::from("")),
+ ("big", PayloadValue::from(big.clone())),
+ ]),
+ )
+ })
+ };
+ live.run(
+ schema().await,
+ declare(PayloadValue::from(1i64), big.clone()),
+ )
+ .await
+ .unwrap();
+ let key = format!("{}:p", live.index);
+ assert_eq!(
+ hget(&live.uri, &key, "text").await.as_deref(),
+ Some("héllo 🙂 \"q\" \n")
+ );
+ assert_eq!(hget(&live.uri, &key, "price").await.as_deref(), Some("1"));
+ assert_eq!(
+ hget(&live.uri, &key, "neg").await.as_deref(),
+ Some("-9223372036854775808")
+ );
+ assert_eq!(hget(&live.uri, &key, "float").await.as_deref(), Some("0.1"));
+ assert_eq!(hget(&live.uri, &key, "empty").await.as_deref(), Some(""));
+ assert_eq!(
+ hget(&live.uri, &key, "big").await.map(|s| s.len()),
+ Some(big.len())
+ );
+
+ // `1.5` replaces `1`: the document is rewritten.
+ live.run(schema().await, declare(PayloadValue::from(1.5f64), big))
+ .await
+ .unwrap();
+ assert_eq!(hget(&live.uri, &key, "price").await.as_deref(), Some("1.5"));
+ assert_eq!(live.indexed().await, (1, 0));
+ live.cleanup().await;
+}
+
+/// Changing the dimension or the indexed fields recreates the index and
+/// writes its documents again; an unchanged schema keeps it.
+#[tokio::test]
+async fn valkey_index_schema_change_recreates_and_refills_when_available() {
+ let Some(live) = Live::new("schema").await else {
+ return;
+ };
+ live.run(schema().await, n_docs(5, "v1")).await.unwrap();
+ assert_eq!(live.indexed().await, (5, 0));
+
+ // A new TAG field: the index is rebuilt, the documents written again.
+ let with_tag = || async {
+ schema_with(
+ 3,
+ vec![
+ FieldDef::new("text", FieldType::Text),
+ FieldDef::new("price", FieldType::Numeric),
+ FieldDef::new("kind", FieldType::Tag).sortable(),
+ ],
+ )
+ .await
+ };
+ live.run(with_tag().await, n_docs(5, "v1")).await.unwrap();
+ assert_eq!(live.indexed().await, (5, 0));
+
+ // Dimension 3 -> 4: every document carries the new dimension.
+ live.run(
+ schema_with(4, vec![FieldDef::new("text", FieldType::Text)]).await,
+ Arc::new(|ctx, target| {
+ for i in 0..4 {
+ target.declare_document(
+ ctx,
+ doc(&format!("d{i}"), vec![1.0, 0.0, 0.0, i as f32], "v2"),
+ )?;
+ }
+ Ok(())
+ }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(live.indexed().await, (4, 0), "old documents are purged");
+ assert_eq!(doc_count(&live.uri, &live.index).await, 4);
+ live.cleanup().await;
+}
+
+/// An index dropped behind CocoIndex's back leaves its documents unindexed
+/// until a full reprocess, which recreates it over the stored hashes.
+#[tokio::test]
+async fn valkey_index_dropped_out_of_band_is_restored_by_full_reprocess_when_available() {
+ let Some(live) = Live::new("oob").await else {
+ return;
+ };
+ live.run(schema().await, n_docs(4, "v1")).await.unwrap();
+ live.drop_index_out_of_band().await;
+ assert!(!index_exists(&live.uri, &live.index).await);
+ live.run_with(
+ UpdateOptions {
+ full_reprocess: true,
+ ..Default::default()
+ },
+ schema().await,
+ n_docs(4, "v1"),
+ )
+ .await
+ .unwrap();
+ assert!(index_exists(&live.uri, &live.index).await);
+ // The search module indexes existing hashes in the background.
+ for _ in 0..100 {
+ if live.indexed().await.0 == 4 {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert_eq!(live.indexed().await, (4, 0));
+ live.cleanup().await;
+}
+
+/// Batches on both sides of the 1000-document pipeline chunk, growing and
+/// shrinking.
+#[tokio::test]
+async fn valkey_batches_around_pipeline_chunks_when_available() {
+ let Some(live) = Live::new("batch").await else {
+ return;
+ };
+ for n in [999usize, 1000, 1001, 2500, 500, 0, 1001] {
+ live.run(schema().await, n_docs(n, "v1")).await.unwrap();
+ assert_eq!(doc_count(&live.uri, &live.index).await, n, "{n} documents");
+ assert_eq!(live.indexed().await, (n as i64, 0), "{n} documents indexed");
+ }
+ live.run(schema().await, n_docs(1001, "v2")).await.unwrap();
+ assert_eq!(
+ hget(&live.uri, &format!("{}:d1000", live.index), "text")
+ .await
+ .as_deref(),
+ Some("v2")
+ );
+ live.cleanup().await;
+}
+
+/// A very large batch: 50k documents in one run, then all deleted. Slow; run
+/// with
+/// VALKEY_URI=redis://localhost:6379 cargo test -p cocoindex --features valkey \
+/// --test valkey_target valkey_very_large_batch -- --ignored
+#[tokio::test]
+#[ignore]
+async fn valkey_very_large_batch_when_available() {
+ let Some(live) = Live::new("huge").await else {
+ return;
+ };
+ let start = std::time::Instant::now();
+ live.run(schema().await, n_docs(50_000, "v1"))
+ .await
+ .unwrap();
+ eprintln!("wrote 50k documents in {:?}", start.elapsed());
+ assert_eq!(doc_count(&live.uri, &live.index).await, 50_000);
+ let start = std::time::Instant::now();
+ live.run(schema().await, n_docs(0, "v1")).await.unwrap();
+ eprintln!("deleted 50k documents in {:?}", start.elapsed());
+ assert_eq!(doc_count(&live.uri, &live.index).await, 0);
+ live.cleanup().await;
+}
+
+static VALKEY_ARG_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+#[cocoindex::function]
+async fn declare_valkey_doc_in_component(ctx: &Ctx, id: String, index: IndexTarget) -> Result<()> {
+ VALKEY_ARG_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ index.declare_document(ctx, doc(&id, vec![1.0, 0.0, 0.0], "arg"))
+}
+
+/// An index handle is a `mount_each!` argument, keyed by its index.
+#[tokio::test]
+async fn valkey_index_target_is_a_mount_argument_when_available() {
+ let Some(live) = Live::new("arg").await else {
+ return;
+ };
+ let calls = || VALKEY_ARG_CALLS.load(std::sync::atomic::Ordering::SeqCst);
+ for round in 0..2 {
+ let index = live.index.clone();
+ live.app
+ .run(move |ctx| async move {
+ let target = valkey::mount_index_target(&ctx, &VK, index, schema().await).await?;
+ cocoindex::use_mount_each!(
+ vec![
+ ("a".to_string(), "a".to_string()),
+ ("b".to_string(), "b".to_string())
+ ],
+ |id| declare_valkey_doc_in_component(ctx, id, target.clone())
+ )
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert_eq!(calls(), 2, "round {round}: unchanged children are skipped");
+ assert_eq!(doc_count(&live.uri, &live.index).await, 2);
+ }
+ live.cleanup().await;
+}