rig-vectorize 0.2.4

Cloudflare Vectorize vector store implementation for the Rig framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Integration tests for rig-vectorize.
//!
//! These tests require a real Cloudflare Vectorize index and valid credentials.
//!
//! Required environment variables:
//! - `CLOUDFLARE_ACCOUNT_ID`: Your Cloudflare account ID
//! - `CLOUDFLARE_API_TOKEN`: API token with Vectorize read/write permissions
//! - `VECTORIZE_INDEX_NAME`: Name of the test index (must exist, 1536 dimensions)
//!
//! To run these tests:
//! ```bash
//! export CLOUDFLARE_ACCOUNT_ID="your-account-id"
//! export CLOUDFLARE_API_TOKEN="your-api-token"
//! export VECTORIZE_INDEX_NAME="rig-integration-test"
//! cargo test --package rig-vectorize --test integration_tests
//! ```

use rig::embeddings::{EmbedError, Embedding, EmbeddingModel, TextEmbedder};
use rig::vector_store::request::{SearchFilter, VectorSearchRequest};
use rig::vector_store::{InsertDocuments, VectorStoreIndex};
use rig::{Embed, OneOrMany};
use rig_vectorize::{VectorizeClient, VectorizeFilter, VectorizeVectorStore};
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Vectorize has eventual consistency - documents may not be immediately queryable after insert.
const EVENTUAL_CONSISTENCY_DELAY: Duration = Duration::from_secs(5);

#[tokio::test]
async fn test_insert_documents() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);

    let docs = vec![
        TestDocument {
            id: "doc-1".to_string(),
            content: "Rust is a systems programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-3".to_string(),
            content: "Cloudflare Vectorize is a globally distributed vector database".to_string(),
            category: "database".to_string(),
        },
    ];

    let embeddings = model
        .embed_texts(docs.iter().map(|d| d.content.clone()))
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings: Vec<(TestDocument, OneOrMany<Embedding>)> = docs
        .into_iter()
        .zip(embeddings.into_iter())
        .map(|(doc, emb)| (doc, OneOrMany::one(emb)))
        .collect();

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Insert should succeed");
}

#[tokio::test]
async fn test_insert_and_query() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);

    let doc = TestDocument {
        id: "test-doc".to_string(),
        content: "Rig is a Rust library for building AI applications".to_string(),
        category: "ai".to_string(),
    };

    let embeddings = model
        .embed_texts(vec![doc.content.clone()])
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings = vec![(
        doc.clone(),
        OneOrMany::one(embeddings.into_iter().next().unwrap()),
    )];

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Failed to insert document");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    let request = VectorSearchRequest::builder()
        .query(&doc.content)
        .samples(5)
        .build()
        .expect("Failed to build request");

    let results = vector_store
        .top_n_ids(request)
        .await
        .expect("Query should succeed");

    assert!(!results.is_empty(), "Should return at least one result");
}

#[tokio::test]
async fn test_top_n_returns_full_documents() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);
    let doc = TestDocument {
        id: "doc-rust".to_string(),
        content: "Rust is a systems programming language".to_string(),
        category: "programming".to_string(),
    };

    let embeddings = model
        .embed_texts(vec![doc.content.clone()])
        .await
        .expect("Failed to generate embeddings");

    vector_store
        .insert_documents(vec![(
            doc.clone(),
            OneOrMany::one(embeddings.into_iter().next().unwrap()),
        )])
        .await
        .expect("Failed to insert document");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    let request = VectorSearchRequest::builder()
        .query("Rust programming language systems")
        .samples(5)
        .build()
        .expect("Failed to build request");

    let results = vector_store
        .top_n::<TestDocument>(request)
        .await
        .expect("top_n should succeed");

    assert!(!results.is_empty(), "Should return at least one result");

    for (_score, _id, document) in &results {
        assert!(!document.id.is_empty(), "Document should have an id");
        assert!(!document.content.is_empty(), "Document should have content");
        assert!(
            !document.category.is_empty(),
            "Document should have a category"
        );
    }
}

#[tokio::test]
async fn test_top_n_with_multiple_documents() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);
    let docs = vec![
        TestDocument {
            id: "doc-rust".to_string(),
            content: "Rust is a systems programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-python".to_string(),
            content: "Python is a dynamic programming language".to_string(),
            category: "programming".to_string(),
        },
    ];

    let embeddings = model
        .embed_texts(docs.iter().map(|d| d.content.clone()))
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings: Vec<(TestDocument, OneOrMany<Embedding>)> = docs
        .into_iter()
        .zip(embeddings.into_iter())
        .map(|(doc, emb)| (doc, OneOrMany::one(emb)))
        .collect();

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Failed to insert documents");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    let request = VectorSearchRequest::builder()
        .query("programming language")
        .samples(10)
        .build()
        .expect("Failed to build request");

    let results = vector_store
        .top_n::<TestDocument>(request)
        .await
        .expect("top_n should succeed");

    assert!(
        results.len() >= 2,
        "Should return at least 2 results, got {}",
        results.len()
    );
}

#[tokio::test]
async fn test_query_with_eq_filter() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);
    let docs = vec![
        TestDocument {
            id: "doc-rust".to_string(),
            content: "Rust is a systems programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-vectorize".to_string(),
            content: "Cloudflare Vectorize is a vector database".to_string(),
            category: "database".to_string(),
        },
    ];

    let embeddings = model
        .embed_texts(docs.iter().map(|d| d.content.clone()))
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings: Vec<(TestDocument, OneOrMany<Embedding>)> = docs
        .into_iter()
        .zip(embeddings.into_iter())
        .map(|(doc, emb)| (doc, OneOrMany::one(emb)))
        .collect();

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Failed to insert documents");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    let filter = VectorizeFilter::eq("category", serde_json::json!("programming"));

    let request = VectorSearchRequest::builder()
        .query("language")
        .samples(10)
        .filter(filter)
        .build()
        .expect("Failed to build request");

    match vector_store.top_n::<TestDocument>(request).await {
        Ok(results) => {
            if results.is_empty() {
                eprintln!(
                    "Filter test inconclusive - no results returned (metadata index may not exist)"
                );
                return;
            }
            for (_score, _id, document) in &results {
                assert_eq!(
                    document.category, "programming",
                    "Filter should only return programming documents"
                );
            }
        }
        Err(e) => {
            eprintln!("Filter test skipped - metadata may not be indexed: {:?}", e);
        }
    }
}

#[tokio::test]
async fn test_query_with_combined_filters() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);
    let docs = vec![
        TestDocument {
            id: "doc-rust".to_string(),
            content: "Rust is a systems programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-python".to_string(),
            content: "Python is a dynamic programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-vectorize".to_string(),
            content: "Cloudflare Vectorize is a vector database".to_string(),
            category: "database".to_string(),
        },
    ];

    let embeddings = model
        .embed_texts(docs.iter().map(|d| d.content.clone()))
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings: Vec<(TestDocument, OneOrMany<Embedding>)> = docs
        .into_iter()
        .zip(embeddings.into_iter())
        .map(|(doc, emb)| (doc, OneOrMany::one(emb)))
        .collect();

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Failed to insert documents");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    // category = "programming" AND id != "doc-rust"
    let filter = VectorizeFilter::eq("category", serde_json::json!("programming"))
        .and(VectorizeFilter::ne("id", serde_json::json!("doc-rust")));

    let request = VectorSearchRequest::builder()
        .query("programming")
        .samples(10)
        .filter(filter)
        .build()
        .expect("Failed to build request");

    match vector_store.top_n::<TestDocument>(request).await {
        Ok(results) => {
            if results.is_empty() {
                eprintln!(
                    "Filter test inconclusive - no results returned (metadata index may not exist)"
                );
                return;
            }
            for (_score, _id, document) in &results {
                assert_ne!(document.id, "doc-rust", "Filter should exclude doc-rust");
                assert_eq!(
                    document.category, "programming",
                    "Filter should only return programming documents"
                );
            }
        }
        Err(e) => {
            eprintln!("Filter test skipped - metadata may not be indexed: {:?}", e);
        }
    }
}

#[tokio::test]
async fn test_query_with_in_filter() {
    clear_test_index().await;

    let Some(vector_store) = create_vector_store() else {
        eprintln!("Skipping test: Required environment variables not set");
        return;
    };

    let model = MockEmbeddingModel::new(1536);
    let docs = vec![
        TestDocument {
            id: "doc-rust".to_string(),
            content: "Rust is a systems programming language".to_string(),
            category: "programming".to_string(),
        },
        TestDocument {
            id: "doc-vectorize".to_string(),
            content: "Cloudflare Vectorize is a vector database".to_string(),
            category: "database".to_string(),
        },
        TestDocument {
            id: "doc-ai".to_string(),
            content: "Machine learning and artificial intelligence".to_string(),
            category: "ai".to_string(),
        },
    ];

    let embeddings = model
        .embed_texts(docs.iter().map(|d| d.content.clone()))
        .await
        .expect("Failed to generate embeddings");

    let documents_with_embeddings: Vec<(TestDocument, OneOrMany<Embedding>)> = docs
        .into_iter()
        .zip(embeddings.into_iter())
        .map(|(doc, emb)| (doc, OneOrMany::one(emb)))
        .collect();

    vector_store
        .insert_documents(documents_with_embeddings)
        .await
        .expect("Failed to insert documents");

    // Wait for eventual consistency
    tokio::time::sleep(EVENTUAL_CONSISTENCY_DELAY).await;

    let filter = VectorizeFilter::in_values(
        "category",
        vec![
            serde_json::json!("programming"),
            serde_json::json!("database"),
        ],
    );

    let request = VectorSearchRequest::builder()
        .query("Rust Vectorize")
        .samples(10)
        .filter(filter)
        .build()
        .expect("Failed to build request");

    match vector_store.top_n::<TestDocument>(request).await {
        Ok(results) => {
            if results.is_empty() {
                eprintln!(
                    "Filter test inconclusive - no results returned (metadata index may not exist)"
                );
                return;
            }
            for (_score, _id, document) in &results {
                assert!(
                    document.category == "programming" || document.category == "database",
                    "Filter should only return programming or database documents, got: {}",
                    document.category
                );
            }
        }
        Err(e) => {
            eprintln!("Filter test skipped - metadata may not be indexed: {:?}", e);
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestDocument {
    id: String,
    content: String,
    category: String,
}

impl Embed for TestDocument {
    fn embed(&self, embedder: &mut TextEmbedder) -> Result<(), EmbedError> {
        embedder.embed(self.content.clone());
        Ok(())
    }
}

/// A mock embedding model that returns deterministic embeddings for testing.
#[derive(Clone)]
struct MockEmbeddingModel {
    dimensions: usize,
}

impl MockEmbeddingModel {
    fn new(dimensions: usize) -> Self {
        Self { dimensions }
    }
}

struct MockClient;

impl EmbeddingModel for MockEmbeddingModel {
    const MAX_DOCUMENTS: usize = 100;

    type Client = MockClient;

    fn make(_client: &Self::Client, _model: impl Into<String>, dims: Option<usize>) -> Self {
        Self {
            dimensions: dims.unwrap_or(1536),
        }
    }

    fn ndims(&self) -> usize {
        self.dimensions
    }

    async fn embed_texts(
        &self,
        texts: impl IntoIterator<Item = String> + Send,
    ) -> Result<Vec<rig::embeddings::Embedding>, rig::embeddings::EmbeddingError> {
        let texts: Vec<String> = texts.into_iter().collect();
        let embeddings = texts
            .into_iter()
            .map(|text| {
                let hash = simple_hash(&text);
                let vec: Vec<f64> = (0..self.dimensions)
                    .map(|i| {
                        let val = ((hash.wrapping_add(i as u64)) % 1000) as f64 / 1000.0;
                        val * 2.0 - 1.0
                    })
                    .collect();
                rig::embeddings::Embedding {
                    document: text,
                    vec,
                }
            })
            .collect();
        Ok(embeddings)
    }
}

fn simple_hash(s: &str) -> u64 {
    let mut hash: u64 = 5381;
    for c in s.bytes() {
        hash = hash.wrapping_mul(33).wrapping_add(c as u64);
    }
    hash
}

fn get_env_or_skip(var: &str) -> Option<String> {
    std::env::var(var).ok()
}

fn create_vector_store() -> Option<VectorizeVectorStore<MockEmbeddingModel>> {
    let account_id = get_env_or_skip("CLOUDFLARE_ACCOUNT_ID")?;
    let api_token = get_env_or_skip("CLOUDFLARE_API_TOKEN")?;
    let index_name = get_env_or_skip("VECTORIZE_INDEX_NAME")?;

    let model = MockEmbeddingModel::new(1536);

    Some(VectorizeVectorStore::new(
        model, account_id, index_name, api_token,
    ))
}

async fn clear_test_index() {
    let Some(account_id) = get_env_or_skip("CLOUDFLARE_ACCOUNT_ID") else {
        return;
    };
    let Some(api_token) = get_env_or_skip("CLOUDFLARE_API_TOKEN") else {
        return;
    };
    let Some(index_name) = get_env_or_skip("VECTORIZE_INDEX_NAME") else {
        return;
    };

    let client = VectorizeClient::new(account_id, index_name, api_token);

    let mut cursor: Option<String> = None;
    loop {
        let result = match client.list_vectors(Some(1000), cursor.as_deref()).await {
            Ok(r) => r,
            Err(e) => {
                eprintln!("Warning: Failed to list vectors: {:?}", e);
                return;
            }
        };

        if result.vectors.is_empty() {
            break;
        }

        let ids: Vec<String> = result.vectors.into_iter().map(|v| v.id).collect();
        if let Err(e) = client.delete_by_ids(ids).await {
            eprintln!("Warning: Failed to delete vectors: {:?}", e);
            return;
        }

        if !result.is_truncated {
            break;
        }

        cursor = result.next_cursor;
    }
}