velesdb-mobile 3.12.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
// 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 collection;
mod collection_sparse;
mod graph;
mod observer;
mod query;
mod streaming_runtime;
mod types;

pub use agent::{SemanticResult, VelesSemanticMemory};
pub use collection::VelesCollection;
pub use graph::{MobileGraphEdge, MobileGraphNode, MobileGraphStore, TraversalResult};
pub use observer::{
    MobileAccessDecision, MobileObserver, MobileQueryContext, MobileQueryOperationKind,
};
pub use query::{QueryResult, QueryResultKind, QueryResultRow};
pub use types::{
    DistanceMetric, FusionStrategy, IndividualSearchRequest, MobileAdvancedConfig,
    MobileAsyncIndexBuilderConfig, MobileCollectionDiagnostics, MobileCollectionStats,
    MobileDeferredIndexerConfig, MobileIndexInfo, MobileQueryLimits, MobileStreamingConfig,
    PqTrainConfig, SearchQuality, SearchResult, StorageMode, VelesError, VelesPoint,
    VelesSparseVector,
};

use std::sync::Arc;
use velesdb_core::{Database as CoreDatabase, DatabaseObserver};

use crate::observer::ForeignObserver;

#[cfg(test)]
use velesdb_core::DistanceMetric as CoreDistanceMetric;
#[cfg(test)]
use velesdb_core::FusionStrategy as CoreFusionStrategy;
#[cfg(test)]
use velesdb_core::SearchQuality as CoreSearchQuality;

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

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

/// VelesDB database instance.
///
/// Thread-safe handle to a VelesDB database. Can be shared across threads.
#[derive(uniffi::Object)]
pub struct VelesDatabase {
    /// Shared handle to the core database. Held behind an `Arc` so each
    /// [`VelesCollection`] minted from it can carry a clone and route its reads
    /// back through this database's control-plane gate (`gated_search` /
    /// `authorize_read`) rather than hitting its detached collection leaf
    /// directly — the read gate that observer governance depends on
    /// (audit F-5.4, #1392).
    inner: Arc<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: Arc::new(db),
        }))
    }

    /// Opens or creates a database with a read-path [`MobileObserver`] attached.
    ///
    /// The observer is consulted before every governed read (dense / text /
    /// hybrid / sparse / multi-query search and `VelesQL` `SELECT` / `MATCH`):
    /// returning [`MobileAccessDecision::Deny`] aborts the read with that
    /// message and zero results, [`MobileAccessDecision::Allow`] runs it
    /// unmodified. This is the mobile counterpart of the observer gate already
    /// wired on server and Python (audit F-5.4, #1392).
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the database directory (will be created if needed)
    /// * `observer` - A Kotlin/Swift implementation of [`MobileObserver`]
    ///
    /// # Errors
    ///
    /// Returns an error if the path is invalid or cannot be accessed.
    #[uniffi::constructor]
    pub fn open_with_observer(
        path: String,
        observer: Arc<dyn MobileObserver>,
    ) -> Result<Arc<Self>, VelesError> {
        let core_observer: Arc<dyn DatabaseObserver> = Arc::new(ForeignObserver::new(observer));
        let db = CoreDatabase::open_with_observer(&path, core_observer)?;
        Ok(Arc::new(Self {
            inner: Arc::new(db),
        }))
    }

    /// Updates query guardrail limits for every collection in this database.
    ///
    /// This is a full replacement: all fields of `limits` are applied.
    pub fn update_guardrails(&self, limits: MobileQueryLimits) {
        self.inner.update_guardrails(&limits.into());
    }

    /// 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 (see [`StorageMode`])
    ///
    /// # 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)
    /// - **`ProductQuantization`**: 8x-16x compression via trained codebooks
    ///   (requires a training step before upserts)
    /// - **`Rabitq`**: 32x compression with ~1-2% recall loss (1-bit with
    ///   rotation + scalar correction)
    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(())
    }

    /// Creates a graph collection for knowledge graph workloads.
    ///
    /// Creates a schemaless graph collection (no node embeddings).
    /// For graph collections with node embeddings, use
    /// [`create_graph_collection_with_embeddings`](Self::create_graph_collection_with_embeddings).
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection
    pub fn create_graph_collection(&self, name: String) -> Result<(), VelesError> {
        self.inner
            .create_graph_collection(&name, velesdb_core::GraphSchema::schemaless())?;
        Ok(())
    }

    /// Creates a graph collection with node embeddings.
    ///
    /// Nodes in this collection can store vector embeddings and support
    /// similarity search alongside graph traversal.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection
    /// * `dimension` - Vector dimension for node embeddings
    /// * `metric` - Distance metric for similarity calculations
    pub fn create_graph_collection_with_embeddings(
        &self,
        name: String,
        dimension: u32,
        metric: DistanceMetric,
    ) -> Result<(), VelesError> {
        self.inner.create_graph_collection_with_embeddings(
            &name,
            velesdb_core::GraphSchema::schemaless(),
            usize::try_from(dimension).unwrap_or(usize::MAX),
            metric.into(),
        )?;
        Ok(())
    }

    /// Gets a vector collection by name.
    ///
    /// Returns `None` if the collection does not exist.
    /// Returns an error if the collection exists but is not a vector collection.
    /// Graph collections are queried through [`execute_query`](Self::execute_query)
    /// (VelesQL); metadata collections are not retrievable through this accessor.
    pub fn get_collection(&self, name: String) -> Result<Option<Arc<VelesCollection>>, VelesError> {
        match self.inner.get_any_collection(&name) {
            Some(any_coll) => match any_coll.into_vector() {
                Ok(vc) => Ok(Some(Arc::new(VelesCollection {
                    inner: vc,
                    db: self.inner.clone(),
                    name,
                }))),
                Err(_other_variant) => Err(VelesError::Collection {
                    message: format!(
                        "Collection '{name}' is not a vector collection. \
                         Query graph collections through execute_query() (VelesQL)."
                    ),
                }),
            },
            None => 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(format!("PQ training failed: {e}")))?;

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

    /// Executes an arbitrary VelesQL query and returns structured results.
    ///
    /// This is the primary entry point for mobile apps to run the full
    /// VelesQL surface: SELECT, INSERT, UPDATE, DELETE, MATCH, DDL
    /// (CREATE/DROP/ALTER/TRUNCATE), TRAIN QUANTIZER, SHOW, DESCRIBE,
    /// EXPLAIN, ANALYZE, and FLUSH.
    ///
    /// # Arguments
    ///
    /// * `sql` - VelesQL query string
    /// * `params_json` - Optional JSON object with query parameters
    ///   (keys are bare names; use `$name` syntax in SQL).
    ///   Pass `None` or `"{}"` when no parameters are needed.
    ///
    /// # Returns
    ///
    /// A [`QueryResult`] containing the result kind, rows (as JSON strings),
    /// row count, and a human-readable status message.
    ///
    /// # Example (Swift)
    ///
    /// ```swift
    /// let result = try db.executeQuery(
    ///     sql: "SELECT * FROM docs LIMIT 10",
    ///     paramsJson: nil
    /// )
    /// for row in result.rows {
    ///     let json = try JSONSerialization.jsonObject(with: row.dataJson.data(using: .utf8)!)
    ///     print(json)
    /// }
    /// ```
    pub fn execute_query(
        &self,
        sql: String,
        params_json: Option<String>,
    ) -> Result<QueryResult, VelesError> {
        let parsed = velesdb_core::velesql::Parser::parse(&sql)
            .map_err(|e| VelesError::database(format!("VelesQL parse error: {}", e.message)))?;

        let params = query::parse_params(params_json)?;
        let kind = query::classify_query(&parsed);

        let core_results = self
            .inner
            .execute_query(&parsed, &params)
            .map_err(|e| VelesError::database(format!("Query execution failed: {e}")))?;

        let rows: Result<Vec<QueryResultRow>, VelesError> =
            core_results.iter().map(query::to_result_row).collect();
        let rows = rows?;

        #[allow(clippy::cast_possible_truncation)]
        // Reason: row count from a single query will not exceed u32::MAX.
        let row_count = rows.len() as u32;
        let message = query::build_message(&kind, row_count);

        Ok(QueryResult {
            kind,
            rows,
            row_count,
            message,
        })
    }
}

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

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