velesdb-mobile 1.9.1

VelesDB mobile bindings for iOS and Android via UniFFI
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
// Mobile SDK - pedantic/nursery lints relaxed for UniFFI FFI boundary
#![allow(clippy::pedantic)]
#![allow(clippy::nursery)]
#![allow(clippy::needless_pass_by_value)]
// FFI boundary - pedantic lints relaxed for UniFFI compatibility
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::similar_names)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::wildcard_imports)]
#![allow(clippy::redundant_closure_for_method_calls)]

//! VelesDB Mobile - Native bindings for iOS and Android
//!
//! This crate provides UniFFI bindings for VelesDB, enabling native integration
//! with Swift (iOS) and Kotlin (Android) applications.
//!
//! # Architecture
//!
//! - **iOS**: Generates Swift bindings + XCFramework (arm64 device, arm64/x86_64 simulator)
//! - **Android**: Generates Kotlin bindings + AAR (arm64-v8a, armeabi-v7a, x86_64)
//!
//! # Build Commands
//!
//! ```bash
//! # iOS - build for device and simulator
//! cargo build --release --target aarch64-apple-ios
//! cargo build --release --target aarch64-apple-ios-sim
//! cargo build --release --target x86_64-apple-ios  # Intel simulator
//!
//! # iOS - create universal binary + XCFramework
//! lipo -create \
//!   target/aarch64-apple-ios-sim/release/libvelesdb_mobile.a \
//!   target/x86_64-apple-ios/release/libvelesdb_mobile.a \
//!   -output target/universal-sim/libvelesdb_mobile.a
//! xcodebuild -create-xcframework \
//!   -library target/aarch64-apple-ios/release/libvelesdb_mobile.a \
//!   -library target/universal-sim/libvelesdb_mobile.a \
//!   -output VelesDB.xcframework
//!
//! # Android (requires cargo-ndk: cargo install cargo-ndk)
//! cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 build --release
//! ```

uniffi::setup_scaffolding!();

mod agent;
mod graph;
mod types;

pub use agent::{SemanticResult, VelesSemanticMemory};
pub use graph::{MobileGraphEdge, MobileGraphNode, MobileGraphStore, TraversalResult};
pub use types::{
    DistanceMetric, FusionStrategy, IndividualSearchRequest, MobileCollectionStats,
    MobileIndexInfo, PqTrainConfig, SearchResult, StorageMode, VelesError, VelesPoint,
    VelesSparseVector,
};

use std::sync::Arc;
use velesdb_core::Database as CoreDatabase;
use velesdb_core::FusionStrategy as CoreFusionStrategy;
use velesdb_core::VectorCollection as CoreCollection;

#[cfg(test)]
use velesdb_core::DistanceMetric as CoreDistanceMetric;

// NOTE: VelesError, DistanceMetric, StorageMode, FusionStrategy, SearchResult,
// VelesPoint, IndividualSearchRequest moved to types.rs (EPIC-061/US-005 refactoring)

// ============================================================================
// Database
// ============================================================================

/// VelesDB database instance.
///
/// Thread-safe handle to a VelesDB database. Can be shared across threads.
#[derive(uniffi::Object)]
pub struct VelesDatabase {
    inner: CoreDatabase,
}

#[uniffi::export]
impl VelesDatabase {
    /// Opens or creates a database at the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the database directory (will be created if needed)
    ///
    /// # Errors
    ///
    /// Returns an error if the path is invalid or cannot be accessed.
    #[uniffi::constructor]
    pub fn open(path: String) -> Result<Arc<Self>, VelesError> {
        let db = CoreDatabase::open(&path)?;
        Ok(Arc::new(Self { inner: db }))
    }

    /// Creates a new collection with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection
    /// * `dimension` - Vector dimension (e.g., 384, 768, 1536)
    /// * `metric` - Distance metric for similarity calculations
    pub fn create_collection(
        &self,
        name: String,
        dimension: u32,
        metric: DistanceMetric,
    ) -> Result<(), VelesError> {
        self.inner.create_collection(
            &name,
            usize::try_from(dimension).unwrap_or(usize::MAX),
            metric.into(),
        )?;
        Ok(())
    }

    /// Creates a new collection with custom storage mode for IoT/Edge devices.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection
    /// * `dimension` - Vector dimension
    /// * `metric` - Distance metric
    /// * `storage_mode` - Storage optimization (Full, Sq8, Binary)
    ///
    /// # Storage Modes
    ///
    /// - **Full**: Best recall, 4 bytes/dimension
    /// - **Sq8**: 4x compression, ~1% recall loss (recommended for mobile)
    /// - **Binary**: 32x compression, ~5-10% recall loss (for extreme constraints)
    pub fn create_collection_with_storage(
        &self,
        name: String,
        dimension: u32,
        metric: DistanceMetric,
        storage_mode: StorageMode,
    ) -> Result<(), VelesError> {
        self.inner.create_vector_collection_with_options(
            &name,
            usize::try_from(dimension).unwrap_or(usize::MAX),
            metric.into(),
            storage_mode.into(),
        )?;
        Ok(())
    }

    /// Creates a metadata-only collection (no vectors).
    ///
    /// Useful for storing reference data, lookups, or auxiliary information
    /// that doesn't require vector similarity search.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection
    pub fn create_metadata_collection(&self, name: String) -> Result<(), VelesError> {
        self.inner.create_metadata_collection(&name)?;
        Ok(())
    }

    /// Gets a collection by name.
    ///
    /// Returns `None` if the collection does not exist.
    /// Checks vector, metadata, and graph registries in order.
    pub fn get_collection(&self, name: String) -> Result<Option<Arc<VelesCollection>>, VelesError> {
        // Try typed vector collection first (most common case).
        if let Some(coll) = self.inner.get_vector_collection(&name) {
            return Ok(Some(Arc::new(VelesCollection { inner: coll })));
        }
        // For metadata-only and graph collections, the legacy registry holds the
        // same shared inner Collection. VectorCollection wraps Collection 1:1
        // (same Arc<> fields) so opening it from the same on-disk path is
        // equivalent — but cheaper: just ask get_vector_collection which falls
        // back to disk and checks config type. The disk fallback in
        // get_vector_collection already guards against non-vector types, so we
        // need to open directly from disk for metadata/graph.
        // Simplest correct path: VectorCollection::open the path, which loads all
        // Collection fields regardless of collection type.
        let path = self.inner.data_dir().join(&name);
        if path.join("config.json").exists() {
            match velesdb_core::VectorCollection::open(path) {
                Ok(coll) => return Ok(Some(Arc::new(VelesCollection { inner: coll }))),
                Err(e) => {
                    tracing::warn!(
                        collection = %name,
                        error = %e,
                        "VectorCollection::open failed for existing config; collection skipped"
                    );
                }
            }
        }
        Ok(None)
    }

    /// Lists all collection names.
    pub fn list_collections(&self) -> Vec<String> {
        self.inner.list_collections()
    }

    /// Deletes a collection by name.
    pub fn delete_collection(&self, name: String) -> Result<(), VelesError> {
        self.inner.delete_collection(&name)?;
        Ok(())
    }

    /// Trains a Product Quantizer on a collection.
    ///
    /// PQ training is a database-level operation that requires access to the
    /// VelesQL TRAIN executor.
    ///
    /// # Arguments
    ///
    /// * `collection_name` - Name of the collection to train PQ on
    /// * `config` - PQ training configuration
    ///
    /// # Returns
    ///
    /// Status message from the training process.
    pub fn train_pq(
        &self,
        collection_name: String,
        config: PqTrainConfig,
    ) -> Result<String, VelesError> {
        use std::collections::HashMap;
        use velesdb_core::velesql::{Query, TrainStatement, WithValue};

        let mut params = HashMap::new();
        params.insert("m".to_string(), WithValue::Integer(i64::from(config.m)));
        params.insert("k".to_string(), WithValue::Integer(i64::from(config.k)));
        if config.opq {
            params.insert("type".to_string(), WithValue::Identifier("opq".to_string()));
        }

        let query = Query::new_train(TrainStatement {
            collection: collection_name,
            params,
        });

        let empty_params = HashMap::new();
        self.inner
            .execute_query(&query, &empty_params)
            .map_err(|e| VelesError::Database {
                message: format!("PQ training failed: {e}"),
            })?;

        Ok("PQ training complete".to_string())
    }
}

// ============================================================================
// Collection
// ============================================================================

/// A collection of vectors with associated metadata.
#[derive(uniffi::Object)]
pub struct VelesCollection {
    inner: CoreCollection,
}

#[uniffi::export]
impl VelesCollection {
    /// Searches for the k nearest neighbors to the query vector.
    ///
    /// # Arguments
    ///
    /// * `vector` - Query vector
    /// * `limit` - Maximum number of results to return
    ///
    /// # Returns
    ///
    /// Vector of search results sorted by similarity.
    pub fn search(&self, vector: Vec<f32>, limit: u32) -> Result<Vec<SearchResult>, VelesError> {
        let results = self
            .inner
            .search_ids(&vector, usize::try_from(limit).unwrap_or(usize::MAX))?;

        Ok(results
            .into_iter()
            .map(|sr| SearchResult {
                id: sr.id,
                score: sr.score,
            })
            .collect())
    }

    /// Inserts or updates a single point.
    ///
    /// # Arguments
    ///
    /// * `point` - The point to upsert
    pub fn upsert(&self, point: VelesPoint) -> Result<(), VelesError> {
        let payload = point
            .payload
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| VelesError::Database {
                message: format!("Invalid JSON payload: {e}"),
            })?;

        let core_point = velesdb_core::Point::new(point.id, point.vector, payload);
        self.inner.upsert(vec![core_point])?;
        Ok(())
    }

    /// Inserts or updates multiple points in batch.
    ///
    /// # Arguments
    ///
    /// * `points` - Points to upsert
    pub fn upsert_batch(&self, points: Vec<VelesPoint>) -> Result<(), VelesError> {
        let core_points: Result<Vec<velesdb_core::Point>, VelesError> = points
            .into_iter()
            .map(|p| {
                let payload = p
                    .payload
                    .map(|s| serde_json::from_str(&s))
                    .transpose()
                    .map_err(|e| VelesError::Database {
                        message: format!("Invalid JSON payload: {e}"),
                    })?;
                Ok(velesdb_core::Point::new(p.id, p.vector, payload))
            })
            .collect();

        self.inner.upsert(core_points?)?;
        Ok(())
    }

    /// Deletes a point by ID.
    pub fn delete(&self, id: u64) -> Result<(), VelesError> {
        self.inner.delete(&[id])?;
        Ok(())
    }

    /// Returns the number of points in the collection.
    #[allow(clippy::cast_possible_truncation)]
    pub fn count(&self) -> u64 {
        self.inner.config().point_count as u64
    }

    /// Returns the vector dimension.
    #[allow(clippy::cast_possible_truncation)]
    pub fn dimension(&self) -> u32 {
        self.inner.config().dimension as u32
    }

    /// Gets points by their IDs.
    ///
    /// # Arguments
    ///
    /// * `ids` - List of point IDs to retrieve
    ///
    /// # Returns
    ///
    /// Vector of points found. Missing IDs are silently skipped.
    pub fn get(&self, ids: Vec<u64>) -> Vec<VelesPoint> {
        self.inner
            .get(&ids)
            .into_iter()
            .flatten()
            .map(|p| VelesPoint {
                id: p.id,
                vector: p.vector,
                payload: p.payload.map(|v| v.to_string()),
            })
            .collect()
    }

    /// Gets a single point by ID.
    ///
    /// # Arguments
    ///
    /// * `id` - Point ID to retrieve
    ///
    /// # Returns
    ///
    /// The point if found, None otherwise.
    pub fn get_by_id(&self, id: u64) -> Option<VelesPoint> {
        self.inner
            .get(&[id])
            .into_iter()
            .flatten()
            .next()
            .map(|p| VelesPoint {
                id: p.id,
                vector: p.vector,
                payload: p.payload.map(|v| v.to_string()),
            })
    }

    /// Checks if this is a metadata-only collection.
    pub fn is_metadata_only(&self) -> bool {
        self.inner.config().metadata_only
    }

    /// Performs full-text search using BM25.
    ///
    /// # Arguments
    ///
    /// * `query` - Text query to search for
    /// * `limit` - Maximum number of results to return
    ///
    /// # Returns
    ///
    /// Vector of search results sorted by BM25 score.
    pub fn text_search(&self, query: String, limit: u32) -> Result<Vec<SearchResult>, VelesError> {
        let results = self
            .inner
            .text_search(&query, usize::try_from(limit).unwrap_or(usize::MAX))
            .map_err(|e| VelesError::Database {
                message: format!("Text search failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs hybrid search combining vector similarity and BM25 text search.
    ///
    /// # Arguments
    ///
    /// * `vector` - Query vector for similarity search
    /// * `text_query` - Text query for BM25 search
    /// * `limit` - Maximum number of results
    /// * `vector_weight` - Weight for vector similarity (0.0-1.0)
    ///
    /// # Returns
    ///
    /// Vector of search results sorted by fused score.
    pub fn hybrid_search(
        &self,
        vector: Vec<f32>,
        text_query: String,
        limit: u32,
        vector_weight: f32,
    ) -> Result<Vec<SearchResult>, VelesError> {
        let results = self.inner.hybrid_search(
            &vector,
            &text_query,
            usize::try_from(limit).unwrap_or(usize::MAX),
            Some(vector_weight),
        )?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Searches with metadata filtering.
    ///
    /// # Arguments
    ///
    /// * `vector` - Query vector
    /// * `limit` - Maximum number of results
    /// * `filter_json` - JSON filter string (e.g., `{"condition": {"type": "eq", "field": "category", "value": "tech"}}`)
    ///
    /// # Returns
    ///
    /// Vector of search results matching the filter.
    pub fn search_with_filter(
        &self,
        vector: Vec<f32>,
        limit: u32,
        filter_json: String,
    ) -> Result<Vec<SearchResult>, VelesError> {
        // Parse filter JSON
        let filter: velesdb_core::Filter =
            serde_json::from_str(&filter_json).map_err(|e| VelesError::Database {
                message: format!("Invalid filter JSON: {e}"),
            })?;

        let results = self.inner.search_with_filter(
            &vector,
            usize::try_from(limit).unwrap_or(usize::MAX),
            &filter,
        )?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs batch search for multiple query vectors in parallel.
    ///
    /// # Arguments
    ///
    /// * `searches` - List of search requests
    ///
    /// # Returns
    ///
    /// List of result lists (one per query vector).
    pub fn batch_search(
        &self,
        searches: Vec<IndividualSearchRequest>,
    ) -> Result<Vec<Vec<SearchResult>>, VelesError> {
        let query_refs: Vec<&[f32]> = searches.iter().map(|s| s.vector.as_slice()).collect();

        let filters: Result<Vec<Option<velesdb_core::Filter>>, VelesError> = searches
            .iter()
            .map(|s| {
                s.filter
                    .as_ref()
                    .map(|f_json| {
                        serde_json::from_str(f_json).map_err(|e| VelesError::Database {
                            message: format!("Invalid filter JSON in batch: {e}"),
                        })
                    })
                    .transpose()
            })
            .collect();

        let filters = filters?;
        let max_top_k = searches.iter().map(|s| s.top_k).max().unwrap_or(10);

        let all_results = self.inner.search_batch_with_filters(
            &query_refs,
            usize::try_from(max_top_k).unwrap_or(usize::MAX),
            &filters,
        )?;

        Ok(all_results
            .into_iter()
            .zip(searches)
            .map(
                |(results, s): (Vec<velesdb_core::SearchResult>, IndividualSearchRequest)| {
                    results
                        .into_iter()
                        .take(usize::try_from(s.top_k).unwrap_or(usize::MAX))
                        .map(|r| SearchResult {
                            id: r.point.id,
                            score: r.score,
                        })
                        .collect()
                },
            )
            .collect())
    }

    /// Performs text search with metadata filtering.
    ///
    /// # Arguments
    ///
    /// * `query` - Text query
    /// * `limit` - Maximum number of results
    /// * `filter_json` - JSON filter string
    pub fn text_search_with_filter(
        &self,
        query: String,
        limit: u32,
        filter_json: String,
    ) -> Result<Vec<SearchResult>, VelesError> {
        let filter: velesdb_core::Filter =
            serde_json::from_str(&filter_json).map_err(|e| VelesError::Database {
                message: format!("Invalid filter JSON: {e}"),
            })?;

        let results = self
            .inner
            .text_search_with_filter(
                &query,
                usize::try_from(limit).unwrap_or(usize::MAX),
                &filter,
            )
            .map_err(|e| VelesError::Database {
                message: format!("Text search with filter failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs hybrid search with metadata filtering.
    ///
    /// # Arguments
    ///
    /// * `vector` - Query vector
    /// * `text_query` - Text query
    /// * `limit` - Maximum number of results
    /// * `vector_weight` - Weight for vector similarity (0.0-1.0)
    /// * `filter_json` - JSON filter string
    pub fn hybrid_search_with_filter(
        &self,
        vector: Vec<f32>,
        text_query: String,
        limit: u32,
        vector_weight: f32,
        filter_json: String,
    ) -> Result<Vec<SearchResult>, VelesError> {
        let filter: velesdb_core::Filter =
            serde_json::from_str(&filter_json).map_err(|e| VelesError::Database {
                message: format!("Invalid filter JSON: {e}"),
            })?;

        let results = self.inner.hybrid_search_with_filter(
            &vector,
            &text_query,
            usize::try_from(limit).unwrap_or(usize::MAX),
            Some(vector_weight),
            &filter,
        )?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Executes a VelesQL query.
    ///
    /// # Arguments
    ///
    /// * `query_str` - VelesQL query string
    /// * `params_json` - Optional JSON object with query parameters
    ///
    /// # Returns
    ///
    /// Vector of search results.
    ///
    /// # Example
    ///
    /// ```swift
    /// let results = try collection.query(
    ///     "SELECT * FROM vectors WHERE category = 'tech' LIMIT 10",
    ///     nil
    /// )
    /// ```
    pub fn query(
        &self,
        query_str: String,
        params_json: Option<String>,
    ) -> Result<Vec<SearchResult>, VelesError> {
        // Parse the VelesQL query
        let parsed =
            velesdb_core::velesql::Parser::parse(&query_str).map_err(|e| VelesError::Database {
                message: format!("VelesQL parse error: {}", e.message),
            })?;

        // Parse params from JSON if provided
        let params: std::collections::HashMap<String, serde_json::Value> = params_json
            .map(|json| serde_json::from_str(&json))
            .transpose()
            .map_err(|e| VelesError::Database {
                message: format!("Invalid params JSON: {e}"),
            })?
            .unwrap_or_default();

        // Execute the query
        let results =
            self.inner
                .execute_query(&parsed, &params)
                .map_err(|e| VelesError::Database {
                    message: format!("Query execution failed: {e}"),
                })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs multi-query search with result fusion.
    ///
    /// Executes parallel searches for multiple query vectors and fuses
    /// results using the specified strategy. Ideal for Multiple Query
    /// Generation (MQG) pipelines on mobile.
    ///
    /// # Arguments
    ///
    /// * `vectors` - List of query vectors
    /// * `limit` - Maximum number of results after fusion
    /// * `strategy` - Fusion strategy to use
    ///
    /// # Returns
    ///
    /// Vector of fused search results sorted by relevance.
    ///
    /// # Example
    ///
    /// ```swift
    /// let results = try collection.multiQuerySearch(
    ///     vectors: [query1, query2, query3],
    ///     limit: 10,
    ///     strategy: .rrf(k: 60)
    /// )
    /// ```
    pub fn multi_query_search(
        &self,
        vectors: Vec<Vec<f32>>,
        limit: u32,
        strategy: FusionStrategy,
    ) -> Result<Vec<SearchResult>, VelesError> {
        if vectors.is_empty() {
            return Err(VelesError::Database {
                message: "multi_query_search requires at least one vector".to_string(),
            });
        }

        let query_refs: Vec<&[f32]> = vectors.iter().map(|v| v.as_slice()).collect();
        let core_strategy: CoreFusionStrategy = strategy.into();

        let results = self
            .inner
            .multi_query_search(
                &query_refs,
                usize::try_from(limit).unwrap_or(usize::MAX),
                core_strategy,
                None,
            )
            .map_err(|e| VelesError::Database {
                message: format!("Multi-query search failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs multi-query search with metadata filtering.
    ///
    /// # Arguments
    ///
    /// * `vectors` - List of query vectors
    /// * `limit` - Maximum number of results after fusion
    /// * `strategy` - Fusion strategy to use
    /// * `filter_json` - JSON filter string
    pub fn multi_query_search_with_filter(
        &self,
        vectors: Vec<Vec<f32>>,
        limit: u32,
        strategy: FusionStrategy,
        filter_json: String,
    ) -> Result<Vec<SearchResult>, VelesError> {
        if vectors.is_empty() {
            return Err(VelesError::Database {
                message: "multi_query_search requires at least one vector".to_string(),
            });
        }

        let filter: velesdb_core::Filter =
            serde_json::from_str(&filter_json).map_err(|e| VelesError::Database {
                message: format!("Invalid filter JSON: {e}"),
            })?;

        let query_refs: Vec<&[f32]> = vectors.iter().map(|v| v.as_slice()).collect();
        let core_strategy: CoreFusionStrategy = strategy.into();

        let results = self
            .inner
            .multi_query_search(
                &query_refs,
                usize::try_from(limit).unwrap_or(usize::MAX),
                core_strategy,
                Some(&filter),
            )
            .map_err(|e| VelesError::Database {
                message: format!("Multi-query search failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Flushes collection data to durable storage.
    pub fn flush(&self) -> Result<(), VelesError> {
        self.inner.flush()?;
        Ok(())
    }

    /// Returns all point IDs currently present in the collection.
    pub fn all_ids(&self) -> Vec<u64> {
        self.inner.all_ids()
    }

    /// Creates a secondary metadata index for a payload field.
    pub fn create_index(&self, field_name: String) -> Result<(), VelesError> {
        self.inner.create_index(&field_name)?;
        Ok(())
    }

    /// Checks whether a secondary metadata index exists for a field.
    pub fn has_secondary_index(&self, field_name: String) -> bool {
        self.inner.has_secondary_index(&field_name)
    }

    /// Creates a graph/property index for equality lookups.
    pub fn create_property_index(&self, label: String, property: String) -> Result<(), VelesError> {
        self.inner.create_property_index(&label, &property)?;
        Ok(())
    }

    /// Creates a graph/range index for range queries.
    pub fn create_range_index(&self, label: String, property: String) -> Result<(), VelesError> {
        self.inner.create_range_index(&label, &property)?;
        Ok(())
    }

    /// Checks if a property index exists.
    pub fn has_property_index(&self, label: String, property: String) -> bool {
        self.inner.has_property_index(&label, &property)
    }

    /// Checks if a range index exists.
    pub fn has_range_index(&self, label: String, property: String) -> bool {
        self.inner.has_range_index(&label, &property)
    }

    /// Lists all index definitions on this collection.
    pub fn list_indexes(&self) -> Vec<MobileIndexInfo> {
        self.inner
            .list_indexes()
            .into_iter()
            .map(MobileIndexInfo::from)
            .collect()
    }

    /// Drops an index and returns true when something was removed.
    pub fn drop_index(&self, label: String, property: String) -> Result<bool, VelesError> {
        Ok(self.inner.drop_index(&label, &property)?)
    }

    /// Returns total memory usage used by indexes.
    pub fn indexes_memory_usage(&self) -> u64 {
        u64::try_from(self.inner.indexes_memory_usage()).unwrap_or(u64::MAX)
    }

    /// Runs ANALYZE and returns fresh statistics for this collection.
    pub fn analyze(&self) -> Result<MobileCollectionStats, VelesError> {
        Ok(self.inner.analyze()?.into())
    }

    /// Returns the latest known collection statistics snapshot.
    pub fn get_stats(&self) -> MobileCollectionStats {
        self.inner.get_stats().into()
    }

    // ========================================================================
    // Sparse Vector Operations
    // ========================================================================

    /// Performs sparse-only search using an inverted index.
    ///
    /// # Arguments
    ///
    /// * `sparse_vector` - Query sparse vector (parallel arrays of indices/values)
    /// * `limit` - Maximum number of results
    /// * `index_name` - Name of the sparse index (empty string for default)
    ///
    /// # Returns
    ///
    /// Vector of search results sorted by sparse similarity.
    pub fn sparse_search(
        &self,
        sparse_vector: VelesSparseVector,
        limit: u32,
        index_name: Option<String>,
    ) -> Result<Vec<SearchResult>, VelesError> {
        let core_sv = Self::to_core_sparse_vector(&sparse_vector);
        let idx_name = index_name.unwrap_or_default();

        let results = self
            .inner
            .sparse_search(
                &core_sv,
                usize::try_from(limit).unwrap_or(usize::MAX),
                &idx_name,
            )
            .map_err(|e| VelesError::Database {
                message: format!("Sparse search failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Performs hybrid dense+sparse search with RRF fusion.
    ///
    /// Combines vector similarity search with sparse (keyword) search
    /// using Reciprocal Rank Fusion.
    ///
    /// # Arguments
    ///
    /// * `vector` - Dense query vector
    /// * `sparse_vector` - Sparse query vector (parallel arrays)
    /// * `limit` - Maximum number of results
    /// * `index_name` - Name of the sparse index (empty string or `None` for default)
    ///
    /// # Returns
    ///
    /// Vector of fused search results.
    pub fn hybrid_sparse_search(
        &self,
        vector: Vec<f32>,
        sparse_vector: VelesSparseVector,
        limit: u32,
        index_name: Option<String>,
    ) -> Result<Vec<SearchResult>, VelesError> {
        let core_sv = Self::to_core_sparse_vector(&sparse_vector);
        let strategy = velesdb_core::fusion::FusionStrategy::RRF { k: 60 };
        let idx_name = index_name.unwrap_or_default();

        let results = self
            .inner
            .hybrid_sparse_search(
                &vector,
                &core_sv,
                usize::try_from(limit).unwrap_or(usize::MAX),
                &idx_name,
                &strategy,
            )
            .map_err(|e| VelesError::Database {
                message: format!("Hybrid sparse search failed: {e}"),
            })?;

        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                id: r.point.id,
                score: r.score,
            })
            .collect())
    }

    /// Inserts or updates a point with an associated sparse vector.
    ///
    /// # Arguments
    ///
    /// * `point` - The point to upsert (dense vector + payload)
    /// * `sparse_vector` - Sparse vector to associate with this point
    pub fn upsert_with_sparse(
        &self,
        point: VelesPoint,
        sparse_vector: VelesSparseVector,
    ) -> Result<(), VelesError> {
        let payload = point
            .payload
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| VelesError::Database {
                message: format!("Invalid JSON payload: {e}"),
            })?;

        let core_sv = Self::to_core_sparse_vector(&sparse_vector);
        let mut sparse_map = std::collections::BTreeMap::new();
        sparse_map.insert(String::new(), core_sv);

        let core_point =
            velesdb_core::Point::with_sparse(point.id, point.vector, payload, Some(sparse_map));
        self.inner.upsert(vec![core_point])?;
        Ok(())
    }
}

impl VelesCollection {
    /// Converts a `VelesSparseVector` (UniFFI-safe parallel arrays) to the
    /// core `SparseVector` type.
    fn to_core_sparse_vector(sv: &VelesSparseVector) -> velesdb_core::sparse_index::SparseVector {
        let pairs: Vec<(u32, f32)> = sv
            .indices
            .iter()
            .copied()
            .zip(sv.values.iter().copied())
            .collect();
        velesdb_core::sparse_index::SparseVector::new(pairs)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;