velesdb-mobile 5.2.0

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
//! Mobile types and enums module (EPIC-061/US-005 refactoring).
//!
//! Extracted from lib.rs to improve modularity.

use velesdb_core::DistanceMetric as CoreDistanceMetric;
use velesdb_core::FusionStrategy as CoreFusionStrategy;

// ============================================================================
// Error Types
// ============================================================================

/// Errors that can occur when using VelesDB on mobile.
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum VelesError {
    /// Database operation failed.
    ///
    /// `code` carries the canonical core taxonomy code (e.g. `"VELES-006"`)
    /// when the error originated in `velesdb-core`, or an empty string for
    /// binding-level failures (JSON parsing, runtime setup) that have no core
    /// code. `recoverable` mirrors core's [`velesdb_core::Error::is_recoverable`].
    #[error("[{code}] Database error: {message}")]
    Database {
        message: String,
        code: String,
        recoverable: bool,
    },

    /// Collection operation failed.
    #[error("Collection error: {message}")]
    Collection { message: String },

    /// Vector dimension mismatch.
    #[error("Dimension mismatch: expected {expected}, got {actual}")]
    DimensionMismatch { expected: u32, actual: u32 },
}

impl VelesError {
    /// Constructs a binding-level `Database` error with no core taxonomy code.
    ///
    /// Use for failures that originate in the mobile binding itself (JSON
    /// parsing, runtime creation, configuration) rather than in `velesdb-core`.
    /// Binding-level errors are treated as recoverable.
    #[must_use]
    pub fn database(message: String) -> Self {
        VelesError::Database {
            message,
            code: String::new(),
            recoverable: true,
        }
    }
}

impl From<velesdb_core::Error> for VelesError {
    fn from(err: velesdb_core::Error) -> Self {
        let code = err.code().to_string();
        let recoverable = err.is_recoverable();
        match err {
            velesdb_core::Error::DimensionMismatch { expected, actual } =>
            {
                #[allow(clippy::cast_possible_truncation)]
                VelesError::DimensionMismatch {
                    expected: expected as u32,
                    actual: actual as u32,
                }
            }
            velesdb_core::Error::CollectionNotFound(name) => VelesError::Collection {
                message: format!("Collection not found: {name}"),
            },
            velesdb_core::Error::CollectionExists(name) => VelesError::Collection {
                message: format!("Collection already exists: {name}"),
            },
            other => VelesError::Database {
                message: other.to_string(),
                code,
                recoverable,
            },
        }
    }
}

// ============================================================================
// Enums
// ============================================================================

/// Distance metric for vector similarity.
#[derive(Debug, Clone, Copy, uniffi::Enum)]
pub enum DistanceMetric {
    /// Cosine similarity (1 - cosine_distance). Higher is more similar.
    Cosine,
    /// Euclidean (L2) distance. Lower is more similar.
    Euclidean,
    /// Dot product. Higher is more similar (for normalized vectors).
    DotProduct,
    /// Hamming distance for binary vectors. Lower is more similar.
    Hamming,
    /// Jaccard similarity for set-like vectors. Higher is more similar.
    Jaccard,
}

impl From<DistanceMetric> for CoreDistanceMetric {
    fn from(metric: DistanceMetric) -> Self {
        match metric {
            DistanceMetric::Cosine => CoreDistanceMetric::Cosine,
            DistanceMetric::Euclidean => CoreDistanceMetric::Euclidean,
            DistanceMetric::DotProduct => CoreDistanceMetric::DotProduct,
            DistanceMetric::Hamming => CoreDistanceMetric::Hamming,
            DistanceMetric::Jaccard => CoreDistanceMetric::Jaccard,
        }
    }
}

/// Storage mode for vector quantization (IoT/Edge optimization).
#[derive(Debug, Clone, Copy, uniffi::Enum)]
pub enum StorageMode {
    /// Full f32 precision (4 bytes/dimension). Best recall.
    Full,
    /// SQ8: 8-bit scalar quantization (1 byte/dimension). 4x compression, ~1% recall loss.
    Sq8,
    /// Binary: 1-bit quantization (1 bit/dimension). 32x compression, ~5-10% recall loss.
    Binary,
    /// Product Quantization (PQ): aggressive lossy compression (8x-16x typical).
    ProductQuantization,
    /// `RaBitQ`: 1-bit with rotation + scalar correction. 32x compression, ~1-2% recall loss.
    Rabitq,
}

impl From<StorageMode> for velesdb_core::StorageMode {
    fn from(mode: StorageMode) -> Self {
        match mode {
            StorageMode::Full => velesdb_core::StorageMode::Full,
            StorageMode::Sq8 => velesdb_core::StorageMode::SQ8,
            StorageMode::Binary => velesdb_core::StorageMode::Binary,
            StorageMode::ProductQuantization => velesdb_core::StorageMode::ProductQuantization,
            StorageMode::Rabitq => velesdb_core::StorageMode::RaBitQ,
        }
    }
}

/// Search quality profile controlling the recall/latency tradeoff.
///
/// Maps to core [`velesdb_core::SearchQuality`]. In HNSW-backed collections,
/// this controls the `ef_search` parameter. Higher quality means better recall
/// at the cost of increased latency.
#[derive(Debug, Clone, Default, uniffi::Enum)]
pub enum SearchQuality {
    /// Fast search (`ef_search=96`). ~95% recall, lowest latency.
    Fast,
    /// Balanced search (`ef_search=160`). ~99.5% recall, production default.
    #[default]
    Balanced,
    /// Accurate search (`ef_search=512`). ~100% recall.
    Accurate,
    /// Perfect recall mode (`ef_search=4096`). Guaranteed 100% recall.
    Perfect,
    /// Custom `ef_search` value for fine-grained control.
    Custom {
        /// The `ef_search` expansion factor.
        ef: u32,
    },
    /// Adaptive two-phase search that starts low and doubles if needed.
    Adaptive {
        /// Minimum `ef_search` (starting point).
        min_ef: u32,
        /// Maximum `ef_search` (cap).
        max_ef: u32,
    },
    /// Auto-tuned adaptive search based on collection statistics.
    AutoTune,
}

impl From<SearchQuality> for velesdb_core::SearchQuality {
    fn from(quality: SearchQuality) -> Self {
        match quality {
            SearchQuality::Fast => velesdb_core::SearchQuality::Fast,
            SearchQuality::Balanced => velesdb_core::SearchQuality::Balanced,
            SearchQuality::Accurate => velesdb_core::SearchQuality::Accurate,
            SearchQuality::Perfect => velesdb_core::SearchQuality::Perfect,
            SearchQuality::Custom { ef } => {
                velesdb_core::SearchQuality::Custom(usize::try_from(ef).unwrap_or(usize::MAX))
            }
            SearchQuality::Adaptive { min_ef, max_ef } => velesdb_core::SearchQuality::Adaptive {
                min_ef: usize::try_from(min_ef).unwrap_or(usize::MAX),
                max_ef: usize::try_from(max_ef).unwrap_or(usize::MAX),
            },
            SearchQuality::AutoTune => velesdb_core::SearchQuality::AutoTune,
        }
    }
}

/// Fusion strategy for combining results from multiple vector searches.
#[derive(Debug, Clone, uniffi::Enum)]
pub enum FusionStrategy {
    /// Average scores across all queries.
    Average,
    /// Take the maximum score for each document.
    Maximum,
    /// Reciprocal Rank Fusion with configurable k parameter.
    Rrf {
        /// RRF k parameter (default: 60). Lower k emphasizes top ranks more.
        k: u32,
    },
    /// Weighted combination of average, maximum, and hit ratio.
    Weighted {
        /// Weight for average score (0.0-1.0).
        avg_weight: f32,
        /// Weight for maximum score (0.0-1.0).
        max_weight: f32,
        /// Weight for hit ratio (0.0-1.0).
        hit_weight: f32,
    },
    /// Relative Score Fusion for dense + sparse hybrid search.
    RelativeScore {
        /// Weight for the dense (vector) branch (0.0-1.0).
        dense_weight: f32,
        /// Weight for the sparse branch (0.0-1.0).
        sparse_weight: f32,
    },
}

impl From<FusionStrategy> for CoreFusionStrategy {
    fn from(strategy: FusionStrategy) -> Self {
        match strategy {
            FusionStrategy::Average => CoreFusionStrategy::Average,
            FusionStrategy::Maximum => CoreFusionStrategy::Maximum,
            FusionStrategy::Rrf { k } => CoreFusionStrategy::RRF { k },
            FusionStrategy::Weighted {
                avg_weight,
                max_weight,
                hit_weight,
            } => CoreFusionStrategy::Weighted {
                avg_weight,
                max_weight,
                hit_weight,
            },
            FusionStrategy::RelativeScore {
                dense_weight,
                sparse_weight,
            } => CoreFusionStrategy::RelativeScore {
                dense_weight,
                sparse_weight,
            },
        }
    }
}

impl Default for FusionStrategy {
    fn default() -> Self {
        Self::Rrf { k: 60 }
    }
}

// ============================================================================
// Data Types
// ============================================================================

/// A sparse vector represented as parallel arrays of indices and values.
///
/// Uses parallel `Vec<u32>` / `Vec<f32>` instead of `HashMap` for safe FFI
/// mapping to all mobile targets (Swift arrays, Kotlin IntArray/FloatArray).
#[derive(Debug, Clone, uniffi::Record)]
pub struct VelesSparseVector {
    /// Dimension indices (must be sorted, unique).
    pub indices: Vec<u32>,
    /// Weights corresponding to each index.
    pub values: Vec<f32>,
}

/// Configuration for Product Quantization training.
#[derive(Debug, Clone, uniffi::Record)]
pub struct PqTrainConfig {
    /// Number of sub-quantizers (subspaces).
    pub m: u32,
    /// Number of centroids per sub-quantizer.
    pub k: u32,
    /// Whether to use Optimized Product Quantization.
    pub opq: bool,
}

/// A search result containing an ID and similarity score.
#[derive(Debug, Clone, uniffi::Record)]
pub struct SearchResult {
    /// Vector ID.
    pub id: u64,
    /// Similarity score.
    pub score: f32,
    /// Optional payload as JSON string (populated by `query()` method).
    pub payload: Option<String>,
}

/// A point to insert into the database.
#[derive(Debug, Clone, uniffi::Record)]
pub struct VelesPoint {
    /// Unique identifier.
    pub id: u64,
    /// Vector embedding.
    pub vector: Vec<f32>,
    /// Optional JSON payload as string.
    pub payload: Option<String>,
}

/// Individual search request within a batch.
#[derive(Debug, Clone, uniffi::Record)]
pub struct IndividualSearchRequest {
    /// Query vector.
    pub vector: Vec<f32>,
    /// Number of results.
    pub top_k: u32,
    /// Optional metadata filter as JSON string.
    pub filter: Option<String>,
}

/// Public statistics snapshot for a collection.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileCollectionStats {
    /// Total number of points currently stored.
    pub total_points: u64,
    /// Total payload footprint in bytes.
    pub payload_size_bytes: u64,
    /// Number of rows in storage.
    pub row_count: u64,
    /// Number of deleted/tombstoned rows.
    pub deleted_count: u64,
    /// Mean row size estimate in bytes.
    pub avg_row_size_bytes: u64,
    /// Total collection size estimate in bytes.
    pub total_size_bytes: u64,
    /// Number of tracked fields.
    pub field_stats_count: u32,
    /// Number of tracked columns.
    pub column_stats_count: u32,
    /// Number of tracked indexes.
    pub index_stats_count: u32,
}

impl From<velesdb_core::collection::stats::CollectionStats> for MobileCollectionStats {
    fn from(stats: velesdb_core::collection::stats::CollectionStats) -> Self {
        Self {
            total_points: stats.total_points,
            payload_size_bytes: stats.payload_size_bytes,
            row_count: stats.row_count,
            deleted_count: stats.deleted_count,
            avg_row_size_bytes: stats.avg_row_size_bytes,
            total_size_bytes: stats.total_size_bytes,
            field_stats_count: u32::try_from(stats.field_stats.len()).unwrap_or(u32::MAX),
            column_stats_count: u32::try_from(stats.column_stats.len()).unwrap_or(u32::MAX),
            index_stats_count: u32::try_from(stats.index_stats.len()).unwrap_or(u32::MAX),
        }
    }
}

/// Diagnostic snapshot of a collection's health and search readiness.
///
/// FFI mirror of [`velesdb_core::collection::CollectionDiagnostics`]. The
/// `index_health` enum is flattened to a stable lowercase string
/// (`"healthy"`, `"empty"`, `"needs_rebuild"`, `"unknown"`) with an optional
/// detail message, matching the REST and Python bindings.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileCollectionDiagnostics {
    /// Whether the collection contains at least one vector/point.
    pub has_vectors: bool,
    /// Whether the collection is ready to serve search queries.
    pub search_ready: bool,
    /// Whether a valid dimension is configured.
    pub dimension_configured: bool,
    /// Total number of points in the collection.
    pub point_count: u64,
    /// Health status of the primary search index.
    pub index_health: String,
    /// Optional detail message (e.g. the reason a rebuild is needed).
    pub index_health_detail: Option<String>,
}

impl From<velesdb_core::collection::CollectionDiagnostics> for MobileCollectionDiagnostics {
    fn from(diag: velesdb_core::collection::CollectionDiagnostics) -> Self {
        use velesdb_core::collection::IndexHealth;
        let (index_health, index_health_detail) = match diag.index_health {
            IndexHealth::Healthy => ("healthy".to_string(), None),
            IndexHealth::Empty => ("empty".to_string(), None),
            IndexHealth::NeedsRebuild(reason) => ("needs_rebuild".to_string(), Some(reason)),
            _ => ("unknown".to_string(), None),
        };
        Self {
            has_vectors: diag.has_vectors,
            search_ready: diag.search_ready,
            dimension_configured: diag.dimension_configured,
            point_count: u64::try_from(diag.point_count).unwrap_or(u64::MAX),
            index_health,
            index_health_detail,
        }
    }
}

/// Metadata and graph index details.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileIndexInfo {
    /// Node label.
    pub label: String,
    /// Property name.
    pub property: String,
    /// Index type name.
    pub index_type: String,
    /// Number of distinct values.
    pub cardinality: u64,
    /// Approximate memory usage in bytes.
    pub memory_bytes: u64,
}

impl From<velesdb_core::IndexInfo> for MobileIndexInfo {
    fn from(value: velesdb_core::IndexInfo) -> Self {
        Self {
            label: value.label,
            property: value.property,
            index_type: value.index_type,
            cardinality: u64::try_from(value.cardinality).unwrap_or(u64::MAX),
            memory_bytes: u64::try_from(value.memory_bytes).unwrap_or(u64::MAX),
        }
    }
}

/// Runtime query guardrail limits for a collection.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileQueryLimits {
    /// Maximum graph traversal depth.
    pub max_depth: u32,
    /// Maximum intermediate cardinality.
    pub max_cardinality: u64,
    /// Memory limit per query in bytes.
    pub memory_limit_bytes: u64,
    /// Query timeout in milliseconds (0 disables the timeout).
    pub timeout_ms: u64,
    /// Rate limit: max queries per second per client.
    pub rate_limit_qps: u32,
    /// Circuit breaker: failure threshold before tripping.
    pub circuit_failure_threshold: u32,
    /// Circuit breaker: recovery time in seconds.
    pub circuit_recovery_seconds: u64,
}

impl From<velesdb_core::guardrails::QueryLimits> for MobileQueryLimits {
    fn from(v: velesdb_core::guardrails::QueryLimits) -> Self {
        Self {
            max_depth: v.max_depth,
            max_cardinality: u64::try_from(v.max_cardinality).unwrap_or(u64::MAX),
            memory_limit_bytes: u64::try_from(v.memory_limit_bytes).unwrap_or(u64::MAX),
            timeout_ms: v.timeout_ms,
            rate_limit_qps: v.rate_limit_qps,
            circuit_failure_threshold: v.circuit_failure_threshold,
            circuit_recovery_seconds: v.circuit_recovery_seconds,
        }
    }
}

impl From<MobileQueryLimits> for velesdb_core::guardrails::QueryLimits {
    fn from(v: MobileQueryLimits) -> Self {
        Self {
            max_depth: v.max_depth,
            max_cardinality: usize::try_from(v.max_cardinality).unwrap_or(usize::MAX),
            memory_limit_bytes: usize::try_from(v.memory_limit_bytes).unwrap_or(usize::MAX),
            timeout_ms: v.timeout_ms,
            rate_limit_qps: v.rate_limit_qps,
            circuit_failure_threshold: v.circuit_failure_threshold,
            circuit_recovery_seconds: v.circuit_recovery_seconds,
        }
    }
}

/// Deferred indexing configuration (buffers bulk inserts before merging
/// into the HNSW index).
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileDeferredIndexerConfig {
    /// Whether deferred indexing is enabled.
    pub enabled: bool,
    /// Number of buffered points before a merge is triggered.
    pub merge_threshold: u64,
    /// Maximum buffer age in milliseconds before a forced merge. Checked
    /// at write time (no background timer): an expired buffer merges on
    /// the next write. `0` makes every write trigger a merge.
    pub max_buffer_age_ms: u64,
}

impl From<MobileDeferredIndexerConfig>
    for velesdb_core::collection::streaming::DeferredIndexerConfig
{
    fn from(v: MobileDeferredIndexerConfig) -> Self {
        Self {
            enabled: v.enabled,
            merge_threshold: usize::try_from(v.merge_threshold).unwrap_or(usize::MAX),
            max_buffer_age_ms: v.max_buffer_age_ms,
        }
    }
}

/// Async index builder configuration (parallel segment construction for
/// deferred bulk loads).
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileAsyncIndexBuilderConfig {
    /// Number of buffered points before a segment merge is triggered.
    pub merge_threshold: u64,
    /// Reserved — parsed but not yet wired (core issue #488 Task 4):
    /// flushes parallelize on the global thread pool and this knob
    /// changes nothing today.
    pub segment_count: Option<u32>,
}

impl From<MobileAsyncIndexBuilderConfig>
    for velesdb_core::collection::streaming::AsyncIndexBuilderConfig
{
    fn from(v: MobileAsyncIndexBuilderConfig) -> Self {
        Self {
            merge_threshold: usize::try_from(v.merge_threshold).unwrap_or(usize::MAX),
            segment_count: v.segment_count.map(|s| s as usize),
        }
    }
}

/// Configuration for streaming ingestion on a collection.
///
/// FFI mirror of [`velesdb_core::StreamingConfig`]. Fields are `u64` for
/// portable mapping to Swift/Kotlin; they are narrowed to `usize`/`u64` when
/// converted to the core type. Engine defaults are `buffer_size=10000`,
/// `batch_size=128`, `flush_interval_ms=50`.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileStreamingConfig {
    /// Capacity of the bounded channel (backpressure threshold). Default 10000.
    pub buffer_size: u64,
    /// Number of points that trigger an immediate micro-batch flush. Default 128.
    pub batch_size: u64,
    /// Maximum time (ms) before a partial batch is flushed. Default 50.
    pub flush_interval_ms: u64,
}

/// Post-creation overrides for advanced collection configuration.
///
/// Each field uses `Some` to set the value and `None` to leave it
/// unchanged. Unlike the Python binding, mobile cannot express the
/// "clear" state (it maps `None` to "leave unchanged").
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileAdvancedConfig {
    /// PQ rescore oversampling factor; `None` leaves it unchanged.
    pub pq_rescore_oversampling: Option<u32>,
    /// Deferred indexing config; `None` leaves it unchanged.
    pub deferred_indexing: Option<MobileDeferredIndexerConfig>,
    /// Async index builder config; `None` leaves it unchanged.
    pub async_index_builder: Option<MobileAsyncIndexBuilderConfig>,
}

#[cfg(test)]
#[path = "types_tests.rs"]
mod error_tests;