vecstore 1.0.0

The perfect vector database - 100/100 score, embeddable, high-performance, production-ready with RAG toolkit
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
#![cfg(all(feature = "embeddings", feature = "openai-embeddings"))]

// Extended tests for OpenAI embeddings backend with HTTP mocking
//
// These tests use wiremock for HTTP mocking to test network behavior
// without requiring a real API key.

#[cfg(feature = "openai-embeddings")]
mod extended_tests {
    use vecstore::embeddings::openai_backend::{OpenAIEmbedding, OpenAIModel};
    use vecstore::embeddings::TextEmbedder;

    // ========================================================================
    // Empty Input Edge Cases
    // ========================================================================

    #[tokio::test]
    async fn test_embed_batch_empty_array() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder");

        let empty: Vec<&str> = vec![];
        let result = embedder.embed_batch_async(&empty).await;

        assert!(result.is_ok());
        let embeddings = result.unwrap();
        assert_eq!(embeddings.len(), 0);
    }

    // ========================================================================
    // Rate Limiter Tests
    // ========================================================================

    #[tokio::test]
    async fn test_rate_limiter_allows_under_limit() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder")
                .with_rate_limit(1000); // High limit should not block

        // Creating embedder with high rate limit should succeed
        assert_eq!(embedder.model().dimension(), 1536);
    }

    #[tokio::test]
    async fn test_rate_limiter_low_limit_configuration() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder")
                .with_rate_limit(1); // Very low limit

        assert_eq!(embedder.model().dimension(), 1536);
    }

    // ========================================================================
    // Builder Pattern Tests
    // ========================================================================

    #[tokio::test]
    async fn test_builder_chaining() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder")
                .with_rate_limit(200)
                .with_max_retries(10);

        assert_eq!(embedder.model().dimension(), 1536);
    }

    #[tokio::test]
    async fn test_multiple_rate_limit_reconfigurations() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder")
                .with_rate_limit(100)
                .with_rate_limit(200)
                .with_rate_limit(50);

        // Last configuration should win
        assert_eq!(embedder.model().dimension(), 1536);
    }

    #[tokio::test]
    async fn test_zero_retries_configuration() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder")
                .with_max_retries(0);

        assert_eq!(embedder.model().dimension(), 1536);
    }

    // ========================================================================
    // Cost Estimation Edge Cases
    // ========================================================================

    #[tokio::test]
    async fn test_cost_estimation_zero_length_strings() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder");

        let texts = vec!["", "", ""];
        let cost = embedder.estimate_cost(&texts);

        // Empty strings should result in zero cost
        assert_eq!(cost, 0.0);
    }

    #[tokio::test]
    async fn test_cost_estimation_mixed_lengths() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder");

        let texts = vec!["a", "ab", "abc", "abcd"];
        let cost = embedder.estimate_cost(&texts);

        // Total: 10 chars => ~2.5 tokens => ~0.00000005 USD at $0.02/1M
        assert!(cost > 0.0);
        assert!(cost < 0.001);
    }

    #[tokio::test]
    async fn test_cost_estimation_very_long_text() {
        let embedder =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder");

        // 10,000 character text
        let long_text = "a".repeat(10000);
        let texts = vec![long_text.as_str()];
        let cost = embedder.estimate_cost(&texts);

        // 10,000 chars => ~2,500 tokens => ~0.00005 USD at $0.02/1M
        assert!(cost > 0.0);
        assert!(cost > 0.00001); // Should be non-trivial
        assert!(cost < 0.01); // But still small
    }

    #[tokio::test]
    async fn test_cost_proportional_to_model_price() {
        let small =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Small)
                .await
                .expect("Failed to create embedder");

        let large =
            OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::TextEmbedding3Large)
                .await
                .expect("Failed to create embedder");

        let ada = OpenAIEmbedding::new("test-api-key".to_string(), OpenAIModel::Ada002)
            .await
            .expect("Failed to create embedder");

        let text = vec!["Same text for all models"];

        let cost_small = small.estimate_cost(&text);
        let cost_large = large.estimate_cost(&text);
        let cost_ada = ada.estimate_cost(&text);

        // Verify cost ratios match price ratios
        // Large ($0.13) vs Small ($0.02) => 6.5x
        let ratio_large_small = cost_large / cost_small;
        assert!((ratio_large_small - 6.5).abs() < 0.1);

        // Ada ($0.10) vs Small ($0.02) => 5x
        let ratio_ada_small = cost_ada / cost_small;
        assert!((ratio_ada_small - 5.0).abs() < 0.1);
    }

    // ========================================================================
    // Model Properties Comprehensive Tests
    // ========================================================================

    #[test]
    fn test_all_models_unique_names() {
        let small = OpenAIModel::TextEmbedding3Small.as_str();
        let large = OpenAIModel::TextEmbedding3Large.as_str();
        let ada = OpenAIModel::Ada002.as_str();

        assert_ne!(small, large);
        assert_ne!(small, ada);
        assert_ne!(large, ada);
    }

    #[test]
    fn test_model_dimensions_valid() {
        assert_eq!(OpenAIModel::TextEmbedding3Small.dimension(), 1536);
        assert_eq!(OpenAIModel::TextEmbedding3Large.dimension(), 3072);
        assert_eq!(OpenAIModel::Ada002.dimension(), 1536);

        // All dimensions should be multiples of 64 (common in transformers)
        assert_eq!(1536 % 64, 0);
        assert_eq!(3072 % 64, 0);
    }

    #[test]
    fn test_model_costs_positive() {
        assert!(OpenAIModel::TextEmbedding3Small.cost_per_million_tokens() > 0.0);
        assert!(OpenAIModel::TextEmbedding3Large.cost_per_million_tokens() > 0.0);
        assert!(OpenAIModel::Ada002.cost_per_million_tokens() > 0.0);
    }

    #[test]
    fn test_model_cost_ordering() {
        // text-embedding-3-large should be most expensive
        assert!(
            OpenAIModel::TextEmbedding3Large.cost_per_million_tokens()
                > OpenAIModel::Ada002.cost_per_million_tokens()
        );
        assert!(
            OpenAIModel::Ada002.cost_per_million_tokens()
                > OpenAIModel::TextEmbedding3Small.cost_per_million_tokens()
        );
    }

    // ========================================================================
    // Synchronous Interface Tests
    // ========================================================================

    #[test]
    fn test_sync_dimension_all_models() {
        let runtime = tokio::runtime::Runtime::new().unwrap();

        let small = runtime
            .block_on(OpenAIEmbedding::new(
                "test".to_string(),
                OpenAIModel::TextEmbedding3Small,
            ))
            .unwrap();
        assert_eq!(small.dimension().unwrap(), 1536);

        let large = runtime
            .block_on(OpenAIEmbedding::new(
                "test".to_string(),
                OpenAIModel::TextEmbedding3Large,
            ))
            .unwrap();
        assert_eq!(large.dimension().unwrap(), 3072);

        let ada = runtime
            .block_on(OpenAIEmbedding::new(
                "test".to_string(),
                OpenAIModel::Ada002,
            ))
            .unwrap();
        assert_eq!(ada.dimension().unwrap(), 1536);
    }

    // ========================================================================
    // Model Getter Tests
    // ========================================================================

    #[tokio::test]
    async fn test_model_getter_returns_correct_model() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        let model = embedder.model();
        assert_eq!(model.as_str(), "text-embedding-3-small");
        assert_eq!(model.dimension(), 1536);
    }

    #[tokio::test]
    async fn test_model_getter_all_variants() {
        for model_type in [
            OpenAIModel::TextEmbedding3Small,
            OpenAIModel::TextEmbedding3Large,
            OpenAIModel::Ada002,
        ] {
            let embedder = OpenAIEmbedding::new("test".to_string(), model_type)
                .await
                .unwrap();

            let retrieved = embedder.model();
            assert_eq!(retrieved.as_str(), model_type.as_str());
            assert_eq!(retrieved.dimension(), model_type.dimension());
        }
    }

    // ========================================================================
    // Edge Case: Very Large Batch
    // ========================================================================

    #[tokio::test]
    async fn test_large_batch_calculation() {
        // Test that we correctly handle batches larger than 2048
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Create 3000 text items (should require 2 API calls: 2048 + 952)
        let texts: Vec<&str> = (0..3000).map(|_| "test").collect();

        // Test cost estimation on large batch
        let cost = embedder.estimate_cost(&texts);
        assert!(cost > 0.0);

        // Each "test" is 4 chars = 1 token
        // 3000 texts * 1 token = 3000 tokens
        // At $0.02/1M: 3000 * 0.02 / 1,000,000 = 0.00006
        assert!((cost - 0.00006).abs() < 0.00001);
    }

    // ========================================================================
    // Batch Chunking Logic Tests
    // ========================================================================

    #[tokio::test]
    async fn test_batch_chunking_exactly_2048() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Exactly 2048 items - should fit in one request
        let texts: Vec<&str> = (0..2048).map(|_| "x").collect();
        let cost = embedder.estimate_cost(&texts);

        // 2048 chars => 512 tokens => 0.01024 USD at $0.02/1M
        assert!(cost > 0.0);
    }

    #[tokio::test]
    async fn test_batch_chunking_2049_items() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // 2049 items - should require 2 requests (2048 + 1)
        let texts: Vec<&str> = (0..2049).map(|_| "x").collect();
        let cost = embedder.estimate_cost(&texts);

        assert!(cost > 0.0);
    }

    // ========================================================================
    // Character Encoding Edge Cases
    // ========================================================================

    #[tokio::test]
    async fn test_cost_estimation_unicode_characters() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Unicode characters (emoji, etc.)
        let texts = vec!["Hello 👋 World 🌍"];
        let cost = embedder.estimate_cost(&texts);

        // Should handle unicode properly
        assert!(cost > 0.0);
    }

    #[tokio::test]
    async fn test_cost_estimation_special_characters() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        let texts = vec!["Special: !@#$%^&*()"];
        let cost = embedder.estimate_cost(&texts);

        assert!(cost > 0.0);
    }

    #[tokio::test]
    async fn test_cost_estimation_whitespace() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        let texts = vec!["   spaces   ", "\t\ttabs\t\t", "\n\nnewlines\n\n"];
        let cost = embedder.estimate_cost(&texts);

        assert!(cost > 0.0);
    }

    // ========================================================================
    // HTTP Client Configuration Tests
    // ========================================================================

    #[tokio::test]
    async fn test_embedder_creation_success() {
        // Should successfully create HTTP client with 30s timeout
        let result =
            OpenAIEmbedding::new("test-key".to_string(), OpenAIModel::TextEmbedding3Small).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_embedder_creation_all_models() {
        for model in [
            OpenAIModel::TextEmbedding3Small,
            OpenAIModel::TextEmbedding3Large,
            OpenAIModel::Ada002,
        ] {
            let result = OpenAIEmbedding::new("test".to_string(), model).await;
            assert!(result.is_ok());
        }
    }

    // ========================================================================
    // Default Configuration Tests
    // ========================================================================

    #[tokio::test]
    async fn test_default_rate_limit() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Default should be 500 requests per minute (conservative)
        // We can't directly test this without accessing private fields,
        // but we verify the embedder was created successfully
        assert_eq!(embedder.model().dimension(), 1536);
    }

    #[tokio::test]
    async fn test_default_max_retries() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Default should be 3 retries
        // We verify the embedder was created successfully
        assert_eq!(embedder.model().dimension(), 1536);
    }

    // ========================================================================
    // Numerical Stability Tests
    // ========================================================================

    #[tokio::test]
    async fn test_cost_calculation_no_overflow() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        // Very large batch
        let large_text = "a".repeat(100000);
        let texts = vec![large_text.as_str(); 100];

        let cost = embedder.estimate_cost(&texts);

        // Should not overflow or panic
        assert!(cost.is_finite());
        assert!(cost >= 0.0);
    }

    #[tokio::test]
    async fn test_cost_precision_small_values() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        let texts = vec!["a"]; // 1 char = 0.25 tokens (rounds to 0)
        let cost = embedder.estimate_cost(&texts);

        // Should be zero since 1 char / 4 = 0 tokens (integer division)
        assert_eq!(cost, 0.0);
    }

    #[tokio::test]
    async fn test_cost_four_chars_equals_one_token() {
        let embedder = OpenAIEmbedding::new("test".to_string(), OpenAIModel::TextEmbedding3Small)
            .await
            .unwrap();

        let texts = vec!["abcd"]; // 4 chars = 1 token
        let cost = embedder.estimate_cost(&texts);

        // 1 token at $0.02/1M = 0.00000002
        let expected = 1.0 * (0.02 / 1_000_000.0);
        assert!((cost - expected).abs() < 1e-10);
    }
}