cognis 0.2.1

LLM application framework built on cognis-core
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
//! Pinecone vector store implementation.
//!
//! Provides a `PineconeVectorStore` that implements the `VectorStore` trait,
//! backed by a pluggable `PineconeClient` trait for abstracting API calls.
//! Includes a `MockPineconeClient` for testing without a running Pinecone instance.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::RwLock;
use uuid::Uuid;

use cognis_core::documents::Document;
use cognis_core::embeddings::Embeddings;
use cognis_core::error::Result;
use cognis_core::vectorstores::base::VectorStore;

// ---------------------------------------------------------------------------
// Distance metric
// ---------------------------------------------------------------------------

/// Distance metric used by a Pinecone index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum PineconeMetric {
    /// Cosine similarity.
    #[default]
    Cosine,
    /// Euclidean (L2) distance.
    Euclidean,
    /// Dot product (inner product).
    DotProduct,
}

// ---------------------------------------------------------------------------
// PineconeConfig
// ---------------------------------------------------------------------------

/// Configuration for connecting to a Pinecone index.
#[derive(Debug, Clone)]
pub struct PineconeConfig {
    /// Pinecone API key.
    pub api_key: String,
    /// Pinecone environment (e.g. "us-east-1-aws").
    pub environment: String,
    /// Name of the Pinecone index.
    pub index_name: String,
    /// Optional namespace for vector isolation.
    pub namespace: Option<String>,
    /// Distance metric for the index.
    pub metric: PineconeMetric,
    /// Dimensionality of vectors in the index.
    pub dimension: usize,
}

impl PineconeConfig {
    /// Create a new config with the given index name and required fields.
    pub fn new(
        api_key: impl Into<String>,
        environment: impl Into<String>,
        index_name: impl Into<String>,
        dimension: usize,
    ) -> Self {
        Self {
            api_key: api_key.into(),
            environment: environment.into(),
            index_name: index_name.into(),
            namespace: None,
            metric: PineconeMetric::default(),
            dimension,
        }
    }

    /// Set the namespace.
    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// Set the distance metric.
    pub fn with_metric(mut self, metric: PineconeMetric) -> Self {
        self.metric = metric;
        self
    }
}

// ---------------------------------------------------------------------------
// PineconeVector
// ---------------------------------------------------------------------------

/// A vector stored in a Pinecone index.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeVector {
    /// Unique identifier for the vector.
    pub id: String,
    /// The embedding values.
    pub values: Vec<f32>,
    /// Arbitrary metadata associated with the vector.
    pub metadata: HashMap<String, Value>,
    /// Optional sparse vector values (for hybrid search).
    pub sparse_values: Option<PineconeSparseValues>,
}

/// Sparse vector representation for hybrid search.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeSparseValues {
    /// Indices of non-zero dimensions.
    pub indices: Vec<u32>,
    /// Values at those indices.
    pub values: Vec<f32>,
}

// ---------------------------------------------------------------------------
// PineconeQueryResult
// ---------------------------------------------------------------------------

/// A single result from a Pinecone query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeQueryResult {
    /// The vector ID.
    pub id: String,
    /// Similarity score.
    pub score: f32,
    /// Metadata associated with the vector.
    pub metadata: HashMap<String, Value>,
}

// ---------------------------------------------------------------------------
// PineconeFilter
// ---------------------------------------------------------------------------

/// Metadata filter for Pinecone queries.
///
/// Supports Pinecone's metadata filtering operators:
/// `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeFilter {
    /// Filter conditions: field name -> operator -> value.
    pub conditions: Vec<PineconeFilterCondition>,
}

/// A single filter condition on a metadata field.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeFilterCondition {
    /// The metadata field name.
    pub field: String,
    /// The filter operator.
    pub operator: PineconeFilterOperator,
    /// The value to compare against.
    pub value: Value,
}

/// Supported Pinecone metadata filter operators.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PineconeFilterOperator {
    /// Equal to.
    #[serde(rename = "$eq")]
    Eq,
    /// Not equal to.
    #[serde(rename = "$ne")]
    Ne,
    /// Greater than.
    #[serde(rename = "$gt")]
    Gt,
    /// Greater than or equal to.
    #[serde(rename = "$gte")]
    Gte,
    /// Less than.
    #[serde(rename = "$lt")]
    Lt,
    /// Less than or equal to.
    #[serde(rename = "$lte")]
    Lte,
    /// In set.
    #[serde(rename = "$in")]
    In,
    /// Not in set.
    #[serde(rename = "$nin")]
    Nin,
}

impl PineconeFilter {
    /// Create an empty filter.
    pub fn new() -> Self {
        Self {
            conditions: Vec::new(),
        }
    }

    /// Add a filter condition.
    pub fn condition(
        mut self,
        field: impl Into<String>,
        operator: PineconeFilterOperator,
        value: Value,
    ) -> Self {
        self.conditions.push(PineconeFilterCondition {
            field: field.into(),
            operator,
            value,
        });
        self
    }

    /// Shorthand for `$eq`.
    pub fn eq(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Eq, value)
    }

    /// Shorthand for `$ne`.
    pub fn ne(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Ne, value)
    }

    /// Shorthand for `$gt`.
    pub fn gt(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Gt, value)
    }

    /// Shorthand for `$gte`.
    pub fn gte(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Gte, value)
    }

    /// Shorthand for `$lt`.
    pub fn lt(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Lt, value)
    }

    /// Shorthand for `$lte`.
    pub fn lte(self, field: impl Into<String>, value: Value) -> Self {
        self.condition(field, PineconeFilterOperator::Lte, value)
    }

    /// Shorthand for `$in`.
    pub fn r#in(self, field: impl Into<String>, values: Vec<Value>) -> Self {
        self.condition(field, PineconeFilterOperator::In, Value::Array(values))
    }

    /// Shorthand for `$nin`.
    pub fn nin(self, field: impl Into<String>, values: Vec<Value>) -> Self {
        self.condition(field, PineconeFilterOperator::Nin, Value::Array(values))
    }

    /// Returns true if this filter has no conditions.
    pub fn is_empty(&self) -> bool {
        self.conditions.is_empty()
    }
}

impl Default for PineconeFilter {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// IndexStats
// ---------------------------------------------------------------------------

/// Statistics about a Pinecone index.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PineconeIndexStats {
    /// Total number of vectors across all namespaces.
    pub total_vector_count: usize,
    /// Vector count per namespace.
    pub namespaces: HashMap<String, usize>,
    /// Dimensionality of vectors in the index.
    pub dimension: usize,
}

// ---------------------------------------------------------------------------
// PineconeClient trait
// ---------------------------------------------------------------------------

/// Abstraction over Pinecone API calls, enabling mocking for tests.
#[async_trait]
pub trait PineconeClient: Send + Sync {
    /// Upsert vectors into a namespace.
    async fn upsert(&self, namespace: &str, vectors: Vec<PineconeVector>) -> Result<()>;

    /// Query for similar vectors.
    async fn query(
        &self,
        namespace: &str,
        vector: &[f32],
        top_k: usize,
        filter: Option<&PineconeFilter>,
        include_metadata: bool,
    ) -> Result<Vec<PineconeQueryResult>>;

    /// Delete vectors by their IDs.
    async fn delete(&self, namespace: &str, ids: &[String]) -> Result<()>;

    /// Fetch vectors by their IDs.
    async fn fetch(&self, namespace: &str, ids: &[String]) -> Result<Vec<PineconeVector>>;

    /// Describe index statistics.
    async fn describe_index_stats(&self) -> Result<PineconeIndexStats>;
}

// ---------------------------------------------------------------------------
// MockPineconeClient
// ---------------------------------------------------------------------------

/// In-memory mock implementation of `PineconeClient` for testing.
///
/// Vectors are stored per namespace, providing full namespace isolation.
pub struct MockPineconeClient {
    /// Vectors stored per namespace.
    namespaces: RwLock<HashMap<String, Vec<PineconeVector>>>,
    /// Distance metric to use for scoring.
    metric: PineconeMetric,
    /// Dimensionality of vectors.
    dimension: usize,
}

impl MockPineconeClient {
    /// Create a new empty mock client.
    pub fn new(metric: PineconeMetric, dimension: usize) -> Self {
        Self {
            namespaces: RwLock::new(HashMap::new()),
            metric,
            dimension,
        }
    }
}

/// Compute similarity score between two vectors using the given metric.
fn compute_score(a: &[f32], b: &[f32], metric: PineconeMetric) -> f32 {
    match metric {
        PineconeMetric::Cosine => {
            let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
            let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
            let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
            if norm_a == 0.0 || norm_b == 0.0 {
                0.0
            } else {
                dot / (norm_a * norm_b)
            }
        }
        PineconeMetric::Euclidean => {
            let dist: f32 = a
                .iter()
                .zip(b.iter())
                .map(|(x, y)| (x - y).powi(2))
                .sum::<f32>()
                .sqrt();
            1.0 / (1.0 + dist)
        }
        PineconeMetric::DotProduct => a.iter().zip(b.iter()).map(|(x, y)| x * y).sum(),
    }
}

/// Check whether a vector's metadata matches a Pinecone filter.
fn matches_filter(metadata: &HashMap<String, Value>, filter: &PineconeFilter) -> bool {
    filter.conditions.iter().all(|cond| {
        let Some(field_val) = metadata.get(&cond.field) else {
            return false;
        };

        match &cond.operator {
            PineconeFilterOperator::Eq => field_val == &cond.value,
            PineconeFilterOperator::Ne => field_val != &cond.value,
            PineconeFilterOperator::Gt => {
                compare_values(field_val, &cond.value) == Some(std::cmp::Ordering::Greater)
            }
            PineconeFilterOperator::Gte => {
                matches!(
                    compare_values(field_val, &cond.value),
                    Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)
                )
            }
            PineconeFilterOperator::Lt => {
                compare_values(field_val, &cond.value) == Some(std::cmp::Ordering::Less)
            }
            PineconeFilterOperator::Lte => {
                matches!(
                    compare_values(field_val, &cond.value),
                    Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
                )
            }
            PineconeFilterOperator::In => {
                if let Value::Array(arr) = &cond.value {
                    arr.contains(field_val)
                } else {
                    false
                }
            }
            PineconeFilterOperator::Nin => {
                if let Value::Array(arr) = &cond.value {
                    !arr.contains(field_val)
                } else {
                    true
                }
            }
        }
    })
}

/// Compare two JSON values numerically or lexicographically.
fn compare_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
    match (a, b) {
        (Value::Number(na), Value::Number(nb)) => {
            let fa = na.as_f64()?;
            let fb = nb.as_f64()?;
            fa.partial_cmp(&fb)
        }
        (Value::String(sa), Value::String(sb)) => Some(sa.cmp(sb)),
        _ => None,
    }
}

#[async_trait]
impl PineconeClient for MockPineconeClient {
    async fn upsert(&self, namespace: &str, vectors: Vec<PineconeVector>) -> Result<()> {
        let mut namespaces = self.namespaces.write().await;
        let ns = namespaces
            .entry(namespace.to_string())
            .or_insert_with(Vec::new);

        for vector in vectors {
            ns.retain(|v| v.id != vector.id);
            ns.push(vector);
        }
        Ok(())
    }

    async fn query(
        &self,
        namespace: &str,
        vector: &[f32],
        top_k: usize,
        filter: Option<&PineconeFilter>,
        _include_metadata: bool,
    ) -> Result<Vec<PineconeQueryResult>> {
        let namespaces = self.namespaces.read().await;
        let Some(ns) = namespaces.get(namespace) else {
            return Ok(vec![]);
        };

        let mut scored: Vec<PineconeQueryResult> = ns
            .iter()
            .filter(|v| {
                filter
                    .map(|f| matches_filter(&v.metadata, f))
                    .unwrap_or(true)
            })
            .map(|v| PineconeQueryResult {
                id: v.id.clone(),
                score: compute_score(vector, &v.values, self.metric),
                metadata: v.metadata.clone(),
            })
            .collect();

        scored.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        scored.truncate(top_k);
        Ok(scored)
    }

    async fn delete(&self, namespace: &str, ids: &[String]) -> Result<()> {
        let mut namespaces = self.namespaces.write().await;
        if let Some(ns) = namespaces.get_mut(namespace) {
            ns.retain(|v| !ids.contains(&v.id));
        }
        Ok(())
    }

    async fn fetch(&self, namespace: &str, ids: &[String]) -> Result<Vec<PineconeVector>> {
        let namespaces = self.namespaces.read().await;
        let Some(ns) = namespaces.get(namespace) else {
            return Ok(vec![]);
        };
        Ok(ns.iter().filter(|v| ids.contains(&v.id)).cloned().collect())
    }

    async fn describe_index_stats(&self) -> Result<PineconeIndexStats> {
        let namespaces = self.namespaces.read().await;
        let mut ns_counts = HashMap::new();
        let mut total = 0;
        for (name, vectors) in namespaces.iter() {
            ns_counts.insert(name.clone(), vectors.len());
            total += vectors.len();
        }
        Ok(PineconeIndexStats {
            total_vector_count: total,
            namespaces: ns_counts,
            dimension: self.dimension,
        })
    }
}

// ---------------------------------------------------------------------------
// PineconeVectorStore
// ---------------------------------------------------------------------------

/// Vector store backed by Pinecone (or a mock thereof).
///
/// Wraps a `PineconeClient` implementation and an `Embeddings` model to provide
/// the full `VectorStore` trait interface.
pub struct PineconeVectorStore {
    client: Arc<dyn PineconeClient>,
    embeddings: Arc<dyn Embeddings>,
    config: PineconeConfig,
}

impl PineconeVectorStore {
    /// Create a new Pinecone vector store.
    pub fn new(
        client: Arc<dyn PineconeClient>,
        embeddings: Arc<dyn Embeddings>,
        config: PineconeConfig,
    ) -> Self {
        Self {
            client,
            embeddings,
            config,
        }
    }

    /// Create a Pinecone vector store pre-populated with documents.
    pub async fn from_documents(
        documents: Vec<Document>,
        client: Arc<dyn PineconeClient>,
        embeddings: Arc<dyn Embeddings>,
        config: PineconeConfig,
    ) -> Result<Self> {
        let store = Self::new(client, embeddings, config);
        store.add_documents(documents, None).await?;
        Ok(store)
    }

    /// Return the effective namespace (defaults to empty string).
    fn namespace(&self) -> &str {
        self.config.namespace.as_deref().unwrap_or("")
    }

    /// Perform a similarity search with an optional metadata filter, returning scores.
    pub async fn similarity_search_with_filter(
        &self,
        query: &str,
        k: usize,
        filter: Option<&PineconeFilter>,
    ) -> Result<Vec<(Document, f32)>> {
        let query_embedding = self.embeddings.embed_query(query).await?;
        let results = self
            .client
            .query(self.namespace(), &query_embedding, k, filter, true)
            .await?;

        Ok(results
            .into_iter()
            .map(|r| {
                let content = r
                    .metadata
                    .get("page_content")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let mut metadata = r.metadata.clone();
                metadata.remove("page_content");

                let doc = Document::new(content).with_id(r.id).with_metadata(metadata);

                (doc, r.score)
            })
            .collect())
    }

    /// Return a reference to the underlying config.
    pub fn config(&self) -> &PineconeConfig {
        &self.config
    }

    /// Get index statistics.
    pub async fn describe_index_stats(&self) -> Result<PineconeIndexStats> {
        self.client.describe_index_stats().await
    }
}

#[async_trait]
impl VectorStore for PineconeVectorStore {
    async fn add_texts(
        &self,
        texts: &[String],
        metadatas: Option<&[HashMap<String, Value>]>,
        ids: Option<&[String]>,
    ) -> Result<Vec<String>> {
        let embeddings_vec = self.embeddings.embed_documents(texts.to_vec()).await?;

        let mut vectors = Vec::with_capacity(texts.len());
        let mut result_ids = Vec::with_capacity(texts.len());

        for (i, text) in texts.iter().enumerate() {
            let id = ids
                .and_then(|id_list| id_list.get(i).cloned())
                .unwrap_or_else(|| Uuid::new_v4().to_string());

            let mut metadata: HashMap<String, Value> = metadatas
                .and_then(|m| m.get(i).cloned())
                .unwrap_or_default();

            metadata.insert("page_content".to_string(), Value::String(text.clone()));

            vectors.push(PineconeVector {
                id: id.clone(),
                values: embeddings_vec[i].clone(),
                metadata,
                sparse_values: None,
            });

            result_ids.push(id);
        }

        self.client.upsert(self.namespace(), vectors).await?;

        Ok(result_ids)
    }

    async fn add_documents(
        &self,
        documents: Vec<Document>,
        ids: Option<Vec<String>>,
    ) -> Result<Vec<String>> {
        let texts: Vec<String> = documents.iter().map(|d| d.page_content.clone()).collect();
        let metadatas: Vec<HashMap<String, Value>> =
            documents.iter().map(|d| d.metadata.clone()).collect();
        let id_refs: Option<Vec<String>> = ids.or_else(|| {
            let doc_ids: Vec<String> = documents.iter().filter_map(|d| d.id.clone()).collect();
            if doc_ids.len() == documents.len() {
                Some(doc_ids)
            } else {
                None
            }
        });
        let id_slice_ref: Option<&[String]> = id_refs.as_deref();
        self.add_texts(&texts, Some(&metadatas), id_slice_ref).await
    }

    async fn delete(&self, ids: Option<&[String]>) -> Result<bool> {
        let Some(ids) = ids else {
            return Ok(false);
        };
        self.client.delete(self.namespace(), ids).await?;
        Ok(true)
    }

    async fn get_by_ids(&self, ids: &[String]) -> Result<Vec<Document>> {
        let vectors = self.client.fetch(self.namespace(), ids).await?;

        Ok(vectors
            .into_iter()
            .map(|v| {
                let content = v
                    .metadata
                    .get("page_content")
                    .and_then(|val| val.as_str())
                    .unwrap_or("")
                    .to_string();

                let mut metadata = v.metadata.clone();
                metadata.remove("page_content");

                Document::new(content).with_id(v.id).with_metadata(metadata)
            })
            .collect())
    }

    async fn similarity_search(&self, query: &str, k: usize) -> Result<Vec<Document>> {
        let results = self.similarity_search_with_score(query, k).await?;
        Ok(results.into_iter().map(|(doc, _)| doc).collect())
    }

    async fn similarity_search_with_score(
        &self,
        query: &str,
        k: usize,
    ) -> Result<Vec<(Document, f32)>> {
        self.similarity_search_with_filter(query, k, None).await
    }

    async fn similarity_search_by_vector(
        &self,
        embedding: &[f32],
        k: usize,
    ) -> Result<Vec<Document>> {
        let results = self
            .client
            .query(self.namespace(), embedding, k, None, true)
            .await?;

        Ok(results
            .into_iter()
            .map(|r| {
                let content = r
                    .metadata
                    .get("page_content")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let mut metadata = r.metadata.clone();
                metadata.remove("page_content");

                Document::new(content).with_id(r.id).with_metadata(metadata)
            })
            .collect())
    }

    async fn max_marginal_relevance_search(
        &self,
        query: &str,
        k: usize,
        fetch_k: usize,
        lambda_mult: f32,
    ) -> Result<Vec<Document>> {
        let query_embedding = self.embeddings.embed_query(query).await?;
        let results = self
            .client
            .query(self.namespace(), &query_embedding, fetch_k, None, true)
            .await?;

        if results.is_empty() {
            return Ok(vec![]);
        }

        // Fetch full vectors to get embedding values for MMR computation.
        let result_ids: Vec<String> = results.iter().map(|r| r.id.clone()).collect();
        let full_vectors = self.client.fetch(self.namespace(), &result_ids).await?;

        let candidate_embeddings: Vec<Vec<f64>> = full_vectors
            .iter()
            .map(|v| v.values.iter().map(|&val| val as f64).collect())
            .collect();
        let query_emb_f64: Vec<f64> = query_embedding.iter().map(|&v| v as f64).collect();

        let mmr_indices = cognis_core::vectorstores::utils::maximal_marginal_relevance(
            &query_emb_f64,
            &candidate_embeddings,
            lambda_mult as f64,
            k,
        );

        let docs = mmr_indices
            .into_iter()
            .filter_map(|idx| results.get(idx))
            .map(|r| {
                let content = r
                    .metadata
                    .get("page_content")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let mut metadata = r.metadata.clone();
                metadata.remove("page_content");

                Document::new(content)
                    .with_id(r.id.clone())
                    .with_metadata(metadata)
            })
            .collect();

        Ok(docs)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use cognis_core::embeddings_fake::DeterministicFakeEmbedding;

    fn make_embeddings() -> Arc<dyn Embeddings> {
        Arc::new(DeterministicFakeEmbedding::new(16))
    }

    fn make_client() -> Arc<MockPineconeClient> {
        Arc::new(MockPineconeClient::new(PineconeMetric::Cosine, 16))
    }

    fn make_config() -> PineconeConfig {
        PineconeConfig::new("test-key", "us-east-1-aws", "test-index", 16)
    }

    fn make_store() -> PineconeVectorStore {
        PineconeVectorStore::new(make_client(), make_embeddings(), make_config())
    }

    fn make_store_with_namespace(ns: &str) -> (PineconeVectorStore, Arc<MockPineconeClient>) {
        let client = make_client();
        let config = make_config().with_namespace(ns);
        let store = PineconeVectorStore::new(client.clone(), make_embeddings(), config);
        (store, client)
    }

    // ---- Test 1: Add and search documents ----
    #[tokio::test]
    async fn test_add_and_search_documents() {
        let store = make_store();
        let docs = vec![
            Document::new("Rust is fast").with_id("d1"),
            Document::new("Python is dynamic").with_id("d2"),
            Document::new("Rust has zero-cost abstractions").with_id("d3"),
        ];
        let ids = store.add_documents(docs, None).await.unwrap();
        assert_eq!(ids.len(), 3);

        let results = store.similarity_search("Rust", 2).await.unwrap();
        assert_eq!(results.len(), 2);
    }

    // ---- Test 2: Similarity search with scores ----
    #[tokio::test]
    async fn test_similarity_search_with_scores() {
        let store = make_store();
        let texts = vec!["cat".into(), "dog".into(), "fish".into()];
        store.add_texts(&texts, None, None).await.unwrap();

        let results = store.similarity_search_with_score("cat", 3).await.unwrap();
        assert_eq!(results.len(), 3);
        // First result should be "cat" with highest score.
        assert_eq!(results[0].0.page_content, "cat");
        // Scores in descending order.
        assert!(results[0].1 >= results[1].1);
        assert!(results[1].1 >= results[2].1);
    }

    // ---- Test 3: Namespace isolation ----
    #[tokio::test]
    async fn test_namespace_isolation() {
        let client = make_client();
        let embeddings = make_embeddings();

        let config_a = make_config().with_namespace("ns-a");
        let store_a = PineconeVectorStore::new(client.clone(), embeddings.clone(), config_a);

        let config_b = make_config().with_namespace("ns-b");
        let store_b = PineconeVectorStore::new(client.clone(), embeddings.clone(), config_b);

        store_a
            .add_texts(&["hello from A".into()], None, None)
            .await
            .unwrap();
        store_b
            .add_texts(&["hello from B".into()], None, None)
            .await
            .unwrap();

        let results_a = store_a.similarity_search("hello", 10).await.unwrap();
        assert_eq!(results_a.len(), 1);
        assert_eq!(results_a[0].page_content, "hello from A");

        let results_b = store_b.similarity_search("hello", 10).await.unwrap();
        assert_eq!(results_b.len(), 1);
        assert_eq!(results_b[0].page_content, "hello from B");
    }

    // ---- Test 4: Metadata filtering with $eq ----
    #[tokio::test]
    async fn test_metadata_filter_eq() {
        let store = make_store();
        let texts = vec!["apple".into(), "banana".into(), "cherry".into()];
        let metadatas = vec![
            {
                let mut m = HashMap::new();
                m.insert("color".into(), Value::String("red".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("color".into(), Value::String("yellow".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("color".into(), Value::String("red".into()));
                m
            },
        ];
        store
            .add_texts(&texts, Some(&metadatas), None)
            .await
            .unwrap();

        let filter = PineconeFilter::new().eq("color", Value::String("red".into()));
        let results = store
            .similarity_search_with_filter("fruit", 10, Some(&filter))
            .await
            .unwrap();

        assert_eq!(results.len(), 2);
        for (doc, _) in &results {
            assert_eq!(
                doc.metadata.get("color").unwrap(),
                &Value::String("red".into())
            );
        }
    }

    // ---- Test 5: Metadata filtering with $in ----
    #[tokio::test]
    async fn test_metadata_filter_in() {
        let store = make_store();
        let texts = vec!["a".into(), "b".into(), "c".into()];
        let metadatas = vec![
            {
                let mut m = HashMap::new();
                m.insert("type".into(), Value::String("x".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("type".into(), Value::String("y".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("type".into(), Value::String("z".into()));
                m
            },
        ];
        store
            .add_texts(&texts, Some(&metadatas), None)
            .await
            .unwrap();

        let filter = PineconeFilter::new().r#in(
            "type",
            vec![Value::String("x".into()), Value::String("z".into())],
        );
        let results = store
            .similarity_search_with_filter("query", 10, Some(&filter))
            .await
            .unwrap();

        assert_eq!(results.len(), 2);
        for (doc, _) in &results {
            let t = doc.metadata.get("type").unwrap().as_str().unwrap();
            assert!(t == "x" || t == "z");
        }
    }

    // ---- Test 6: Metadata filtering with $gt ----
    #[tokio::test]
    async fn test_metadata_filter_gt() {
        let store = make_store();
        let texts = vec!["low".into(), "mid".into(), "high".into()];
        let metadatas = vec![
            {
                let mut m = HashMap::new();
                m.insert("score".into(), Value::Number(serde_json::Number::from(10)));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("score".into(), Value::Number(serde_json::Number::from(50)));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("score".into(), Value::Number(serde_json::Number::from(90)));
                m
            },
        ];
        store
            .add_texts(&texts, Some(&metadatas), None)
            .await
            .unwrap();

        let filter = PineconeFilter::new().gt("score", Value::Number(serde_json::Number::from(40)));
        let results = store
            .similarity_search_with_filter("query", 10, Some(&filter))
            .await
            .unwrap();

        assert_eq!(results.len(), 2);
        for (doc, _) in &results {
            let s = doc.metadata.get("score").unwrap().as_i64().unwrap();
            assert!(s > 40);
        }
    }

    // ---- Test 7: Delete documents ----
    #[tokio::test]
    async fn test_delete_documents() {
        let store = make_store();
        let texts = vec!["a".into(), "b".into(), "c".into()];
        let ids = store.add_texts(&texts, None, None).await.unwrap();

        let deleted = store.delete(Some(&[ids[1].clone()])).await.unwrap();
        assert!(deleted);

        let remaining = store.similarity_search("a", 10).await.unwrap();
        assert_eq!(remaining.len(), 2);
        assert!(remaining.iter().all(|d| d.page_content != "b"));
    }

    // ---- Test 8: Config construction ----
    #[tokio::test]
    async fn test_config_construction() {
        let config = PineconeConfig::new("my-key", "us-west-2-aws", "my-index", 128);
        assert_eq!(config.api_key, "my-key");
        assert_eq!(config.environment, "us-west-2-aws");
        assert_eq!(config.index_name, "my-index");
        assert_eq!(config.dimension, 128);
        assert!(config.namespace.is_none());
        assert_eq!(config.metric, PineconeMetric::Cosine);

        let config = config
            .with_namespace("my-ns")
            .with_metric(PineconeMetric::DotProduct);
        assert_eq!(config.namespace.as_deref(), Some("my-ns"));
        assert_eq!(config.metric, PineconeMetric::DotProduct);
    }

    // ---- Test 9: Fetch by IDs ----
    #[tokio::test]
    async fn test_fetch_by_ids() {
        let store = make_store();
        let texts = vec!["alpha".into(), "beta".into(), "gamma".into()];
        let custom_ids = vec!["id-a".to_string(), "id-b".to_string(), "id-c".to_string()];
        store
            .add_texts(&texts, None, Some(&custom_ids))
            .await
            .unwrap();

        let docs = store
            .get_by_ids(&["id-a".into(), "id-c".into()])
            .await
            .unwrap();
        assert_eq!(docs.len(), 2);

        let contents: Vec<&str> = docs.iter().map(|d| d.page_content.as_str()).collect();
        assert!(contents.contains(&"alpha"));
        assert!(contents.contains(&"gamma"));
    }

    // ---- Test 10: Empty index search ----
    #[tokio::test]
    async fn test_empty_index_search() {
        let store = make_store();
        let results = store.similarity_search("anything", 5).await.unwrap();
        assert!(results.is_empty());
    }

    // ---- Test 11: Default namespace ----
    #[tokio::test]
    async fn test_default_namespace() {
        let store = make_store();
        assert_eq!(store.namespace(), "");

        let texts = vec!["hello".into()];
        store.add_texts(&texts, None, None).await.unwrap();

        let stats = store.describe_index_stats().await.unwrap();
        assert!(stats.namespaces.contains_key(""));
        assert_eq!(stats.total_vector_count, 1);
    }

    // ---- Test 12: Multiple namespaces via describe_index_stats ----
    #[tokio::test]
    async fn test_multiple_namespaces_stats() {
        let client = make_client();
        let embeddings = make_embeddings();

        let config_a = make_config().with_namespace("ns-alpha");
        let store_a = PineconeVectorStore::new(client.clone(), embeddings.clone(), config_a);

        let config_b = make_config().with_namespace("ns-beta");
        let store_b = PineconeVectorStore::new(client.clone(), embeddings.clone(), config_b);

        store_a
            .add_texts(&["doc1".into(), "doc2".into()], None, None)
            .await
            .unwrap();
        store_b
            .add_texts(&["doc3".into()], None, None)
            .await
            .unwrap();

        let stats = store_a.describe_index_stats().await.unwrap();
        assert_eq!(stats.total_vector_count, 3);
        assert_eq!(*stats.namespaces.get("ns-alpha").unwrap(), 2);
        assert_eq!(*stats.namespaces.get("ns-beta").unwrap(), 1);
    }

    // ---- Test 13: from_documents constructor ----
    #[tokio::test]
    async fn test_from_documents_constructor() {
        let client = make_client();
        let embeddings = make_embeddings();
        let config = make_config();

        let docs = vec![
            Document::new("hello world").with_id("h1"),
            Document::new("goodbye world").with_id("g1"),
        ];

        let store = PineconeVectorStore::from_documents(docs, client, embeddings, config)
            .await
            .unwrap();

        let results = store.similarity_search("hello", 1).await.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].page_content, "hello world");
    }

    // ---- Test 14: Batch upsert ----
    #[tokio::test]
    async fn test_batch_upsert() {
        let store = make_store();
        let texts: Vec<String> = (0..100).map(|i| format!("document_{}", i)).collect();
        let ids = store.add_texts(&texts, None, None).await.unwrap();
        assert_eq!(ids.len(), 100);

        let results = store.similarity_search("document_50", 5).await.unwrap();
        assert_eq!(results.len(), 5);

        let stats = store.describe_index_stats().await.unwrap();
        assert_eq!(stats.total_vector_count, 100);
    }

    // ---- Test 15: Delete with None returns false ----
    #[tokio::test]
    async fn test_delete_none_returns_false() {
        let store = make_store();
        let result = store.delete(None).await.unwrap();
        assert!(!result);
    }

    // ---- Test 16: Metadata filtering with $ne ----
    #[tokio::test]
    async fn test_metadata_filter_ne() {
        let store = make_store();
        let texts = vec!["a".into(), "b".into(), "c".into()];
        let metadatas = vec![
            {
                let mut m = HashMap::new();
                m.insert("status".into(), Value::String("draft".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("status".into(), Value::String("published".into()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert("status".into(), Value::String("draft".into()));
                m
            },
        ];
        store
            .add_texts(&texts, Some(&metadatas), None)
            .await
            .unwrap();

        let filter = PineconeFilter::new().ne("status", Value::String("draft".into()));
        let results = store
            .similarity_search_with_filter("query", 10, Some(&filter))
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].0.metadata.get("status").unwrap(),
            &Value::String("published".into())
        );
    }
}