paimon 0.2.0

The rust implementation of Apache Paimon
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use libloading::{Library, Symbol};
use std::collections::HashMap;
use std::ffi::{c_char, c_float, c_int, c_void, CStr, CString};
use std::io::{Read, Seek, SeekFrom};
use std::sync::{Mutex, OnceLock};

const ERR_BUF_SIZE: usize = 4096;

static LIBRARY: OnceLock<Library> = OnceLock::new();
static LIBRARY_LOAD_LOCK: Mutex<()> = Mutex::new(());

fn load_library() -> crate::Result<&'static Library> {
    if let Some(lib) = LIBRARY.get() {
        return Ok(lib);
    }

    let _guard = LIBRARY_LOAD_LOCK
        .lock()
        .map_err(|_| crate::Error::UnexpectedError {
            message: "Lumina library load lock poisoned".to_string(),
            source: None,
        })?;
    if let Some(lib) = LIBRARY.get() {
        return Ok(lib);
    }

    let lib_path = std::env::var("LUMINA_LIB_PATH").unwrap_or_else(|_| {
        if cfg!(target_os = "macos") {
            "liblumina_py.dylib".to_string()
        } else if cfg!(target_os = "windows") {
            "lumina_py.dll".to_string()
        } else {
            "liblumina_py.so".to_string()
        }
    });
    let lib = unsafe {
        Library::new(&lib_path).map_err(|e| crate::Error::DataInvalid {
            message: format!("Failed to load lumina library from '{}': {}", lib_path, e),
            source: None,
        })?
    };
    LIBRARY
        .set(lib)
        .map_err(|_| crate::Error::UnexpectedError {
            message: "Lumina library was initialized unexpectedly while holding load lock"
                .to_string(),
            source: None,
        })?;
    Ok(LIBRARY
        .get()
        .expect("Lumina library should be initialized after successful set"))
}

fn check_error(ret: c_int, err_buf: &[u8; ERR_BUF_SIZE]) -> crate::Result<()> {
    if ret != 0 {
        let c_str = unsafe { CStr::from_ptr(err_buf.as_ptr() as *const c_char) };
        let msg = c_str.to_string_lossy().to_string();
        return Err(crate::Error::DataInvalid {
            message: format!("Lumina error: {}", msg),
            source: None,
        });
    }
    Ok(())
}

fn options_to_json(options: &HashMap<String, String>) -> crate::Result<CString> {
    let json = serde_json::to_string(options).map_err(|e| crate::Error::DataInvalid {
        message: format!("Failed to serialize options: {}", e),
        source: None,
    })?;
    CString::new(json).map_err(|e| crate::Error::DataInvalid {
        message: format!("Failed to create CString: {}", e),
        source: None,
    })
}

pub struct LuminaSearcher {
    handle: *mut c_void,
    /// Keeps the stream context alive while C-side holds a raw pointer to it.
    stream_ctx_keepalive: Option<Box<StreamContext>>,
}

// SAFETY: Each LuminaSearcher owns its handle exclusively and is not Sync.
// Send allows moving the searcher to another thread.
unsafe impl Send for LuminaSearcher {}

impl LuminaSearcher {
    pub fn create(options: &HashMap<String, String>) -> crate::Result<Self> {
        let lib = load_library()?;
        let opts_json = options_to_json(options)?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let handle: *mut c_void = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(*const c_char, *mut c_char, c_int) -> *mut c_void,
            > = lib
                .get(b"lumina_searcher_create")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_create not found: {}", e),
                    source: None,
                })?;
            func(
                opts_json.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        if handle.is_null() {
            let c_str = unsafe { CStr::from_ptr(err_buf.as_ptr() as *const c_char) };
            let msg = c_str.to_string_lossy().to_string();
            return Err(crate::Error::DataInvalid {
                message: format!("Failed to create Lumina searcher: {}", msg),
                source: None,
            });
        }

        Ok(Self {
            handle,
            stream_ctx_keepalive: None,
        })
    }

    #[allow(clippy::type_complexity)]
    pub fn open_stream<S: Read + Seek + Send + 'static>(&mut self, stream: S) -> crate::Result<()> {
        if self.stream_ctx_keepalive.is_some() {
            return Err(crate::Error::DataInvalid {
                message: "A stream is already open; close the searcher before opening a new stream"
                    .to_string(),
                source: None,
            });
        }

        let lib = load_library()?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ctx = Box::new(StreamContext::new(stream));
        let ctx_ptr = &*ctx as *const StreamContext as *mut c_void;

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(
                    *mut c_void,
                    *mut c_void,
                    unsafe extern "C" fn(*mut c_void, *mut c_char, u64) -> c_int,
                    unsafe extern "C" fn(*mut c_void, u64) -> c_int,
                    unsafe extern "C" fn(*mut c_void) -> u64,
                    unsafe extern "C" fn(*mut c_void) -> u64,
                    *mut c_char,
                    c_int,
                ) -> c_int,
            > = lib
                .get(b"lumina_searcher_open_stream")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_open_stream not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                ctx_ptr,
                stream_read_cb,
                stream_seek_cb,
                stream_tell_cb,
                stream_length_cb,
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)?;
        self.stream_ctx_keepalive = Some(ctx);
        Ok(())
    }

    pub fn open_file(&mut self, path: &str) -> crate::Result<()> {
        if self.stream_ctx_keepalive.is_some() {
            return Err(crate::Error::DataInvalid {
                message: "A stream is already open; close the searcher before opening a file"
                    .to_string(),
                source: None,
            });
        }

        let lib = load_library()?;
        let c_path = CString::new(path).map_err(|e| crate::Error::DataInvalid {
            message: format!("Invalid path: {}", e),
            source: None,
        })?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_char, c_int) -> c_int,
            > = lib
                .get(b"lumina_searcher_open")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_open not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                c_path.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }

    pub fn search(
        &self,
        query: &[f32],
        n: i32,
        k: i32,
        distances: &mut [f32],
        labels: &mut [u64],
        options: &HashMap<String, String>,
    ) -> crate::Result<()> {
        let lib = load_library()?;
        let opts_json = options_to_json(options)?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(
                    *mut c_void,
                    *const c_float,
                    c_int,
                    c_int,
                    *mut c_float,
                    *mut u64,
                    *const c_char,
                    *mut c_char,
                    c_int,
                ) -> c_int,
            > = lib
                .get(b"lumina_searcher_search")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_search not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                query.as_ptr(),
                n,
                k,
                distances.as_mut_ptr(),
                labels.as_mut_ptr(),
                opts_json.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }

    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub fn search_with_filter(
        &self,
        query: &[f32],
        n: i32,
        k: i32,
        distances: &mut [f32],
        labels: &mut [u64],
        filter_ids: &[u64],
        options: &HashMap<String, String>,
    ) -> crate::Result<()> {
        let lib = load_library()?;
        let opts_json = options_to_json(options)?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(
                    *mut c_void,
                    *const c_float,
                    c_int,
                    c_int,
                    *mut c_float,
                    *mut u64,
                    *const u64,
                    u64,
                    *const c_char,
                    *mut c_char,
                    c_int,
                ) -> c_int,
            > = lib
                .get(b"lumina_searcher_search_with_filter")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_search_with_filter not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                query.as_ptr(),
                n,
                k,
                distances.as_mut_ptr(),
                labels.as_mut_ptr(),
                filter_ids.as_ptr(),
                filter_ids.len() as u64,
                opts_json.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }

    pub fn get_count(&self) -> crate::Result<u64> {
        let lib = load_library()?;
        unsafe {
            let func: Symbol<unsafe extern "C" fn(*mut c_void) -> u64> = lib
                .get(b"lumina_searcher_get_count")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_get_count not found: {}", e),
                    source: None,
                })?;
            Ok(func(self.handle))
        }
    }

    pub fn get_dimension(&self) -> crate::Result<u32> {
        let lib = load_library()?;
        unsafe {
            let func: Symbol<unsafe extern "C" fn(*mut c_void) -> u32> = lib
                .get(b"lumina_searcher_get_dimension")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_searcher_get_dimension not found: {}", e),
                    source: None,
                })?;
            Ok(func(self.handle))
        }
    }
}

impl Drop for LuminaSearcher {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            if let Ok(lib) = load_library() {
                unsafe {
                    if let Ok(func) =
                        lib.get::<unsafe extern "C" fn(*mut c_void)>(b"lumina_searcher_destroy")
                    {
                        func(self.handle);
                    }
                }
            }
            self.handle = std::ptr::null_mut();
        }
    }
}

pub struct LuminaBuilder {
    handle: *mut c_void,
}

// SAFETY: Same as LuminaSearcher — exclusively owned, not Sync.
unsafe impl Send for LuminaBuilder {}

impl LuminaBuilder {
    pub fn create(options: &HashMap<String, String>) -> crate::Result<Self> {
        let lib = load_library()?;
        let opts_json = options_to_json(options)?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let handle: *mut c_void = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(*const c_char, *mut c_char, c_int) -> *mut c_void,
            > = lib
                .get(b"lumina_builder_create")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_builder_create not found: {}", e),
                    source: None,
                })?;
            func(
                opts_json.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        if handle.is_null() {
            let c_str = unsafe { CStr::from_ptr(err_buf.as_ptr() as *const c_char) };
            let msg = c_str.to_string_lossy().to_string();
            return Err(crate::Error::DataInvalid {
                message: format!("Failed to create Lumina builder: {}", msg),
                source: None,
            });
        }

        Ok(Self { handle })
    }

    pub fn pretrain(&self, vectors: &[f32], n: i32, dim: i32) -> crate::Result<()> {
        let lib = load_library()?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(
                    *mut c_void,
                    *const c_float,
                    c_int,
                    c_int,
                    *mut c_char,
                    c_int,
                ) -> c_int,
            > = lib
                .get(b"lumina_builder_pretrain")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_builder_pretrain not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                vectors.as_ptr(),
                n,
                dim,
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }

    pub fn insert(&self, vectors: &[f32], ids: &[u64], n: i32, dim: i32) -> crate::Result<()> {
        let lib = load_library()?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(
                    *mut c_void,
                    *const c_float,
                    *const u64,
                    c_int,
                    c_int,
                    *mut c_char,
                    c_int,
                ) -> c_int,
            > = lib
                .get(b"lumina_builder_insert")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_builder_insert not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                vectors.as_ptr(),
                ids.as_ptr(),
                n,
                dim,
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }

    pub fn dump(&self, path: &str) -> crate::Result<()> {
        let lib = load_library()?;
        let c_path = CString::new(path).map_err(|e| crate::Error::DataInvalid {
            message: format!("Invalid path: {}", e),
            source: None,
        })?;
        let mut err_buf = [0u8; ERR_BUF_SIZE];

        let ret: c_int = unsafe {
            let func: Symbol<
                unsafe extern "C" fn(*mut c_void, *const c_char, *mut c_char, c_int) -> c_int,
            > = lib
                .get(b"lumina_builder_dump")
                .map_err(|e| crate::Error::DataInvalid {
                    message: format!("Symbol lumina_builder_dump not found: {}", e),
                    source: None,
                })?;
            func(
                self.handle,
                c_path.as_ptr(),
                err_buf.as_mut_ptr() as *mut c_char,
                ERR_BUF_SIZE as c_int,
            )
        };

        check_error(ret, &err_buf)
    }
}

impl Drop for LuminaBuilder {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            if let Ok(lib) = load_library() {
                unsafe {
                    if let Ok(func) =
                        lib.get::<unsafe extern "C" fn(*mut c_void)>(b"lumina_builder_destroy")
                    {
                        func(self.handle);
                    }
                }
            }
            self.handle = std::ptr::null_mut();
        }
    }
}

struct StreamContext {
    inner: std::sync::Mutex<Box<dyn ReadSeekLen + Send>>,
}

trait ReadSeekLen: Read + Seek {
    fn length(&self) -> u64;
}

struct ReadSeekLenImpl<S: Read + Seek + Send> {
    stream: S,
    len: u64,
}

impl<S: Read + Seek + Send> ReadSeekLenImpl<S> {
    fn new(mut stream: S) -> Self {
        let len = stream.seek(SeekFrom::End(0)).unwrap_or(0);
        let _ = stream.seek(SeekFrom::Start(0));
        Self { stream, len }
    }
}

impl<S: Read + Seek + Send> Read for ReadSeekLenImpl<S> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.stream.read(buf)
    }
}

impl<S: Read + Seek + Send> Seek for ReadSeekLenImpl<S> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.stream.seek(pos)
    }
}

impl<S: Read + Seek + Send> ReadSeekLen for ReadSeekLenImpl<S> {
    fn length(&self) -> u64 {
        self.len
    }
}

impl StreamContext {
    fn new<S: Read + Seek + Send + 'static>(stream: S) -> Self {
        Self {
            inner: std::sync::Mutex::new(Box::new(ReadSeekLenImpl::new(stream))),
        }
    }
}

unsafe extern "C" fn stream_read_cb(ctx: *mut c_void, buf: *mut c_char, size: u64) -> c_int {
    let ctx = &*(ctx as *const StreamContext);
    let mut guard = match ctx.inner.lock() {
        Ok(g) => g,
        Err(_) => return -1,
    };
    let clamped_size = std::cmp::min(size, c_int::MAX as u64) as usize;
    let slice = std::slice::from_raw_parts_mut(buf as *mut u8, clamped_size);
    let mut total_read = 0usize;
    while total_read < clamped_size {
        match guard.read(&mut slice[total_read..]) {
            Ok(0) => break,
            Ok(n) => total_read += n,
            Err(_) => return -1,
        }
    }
    std::cmp::min(total_read, c_int::MAX as usize) as c_int
}

unsafe extern "C" fn stream_seek_cb(ctx: *mut c_void, position: u64) -> c_int {
    let ctx = &*(ctx as *const StreamContext);
    let mut guard = match ctx.inner.lock() {
        Ok(g) => g,
        Err(_) => return -1,
    };
    match guard.seek(SeekFrom::Start(position)) {
        Ok(_) => 0,
        Err(_) => -1,
    }
}

unsafe extern "C" fn stream_tell_cb(ctx: *mut c_void) -> u64 {
    let ctx = &*(ctx as *const StreamContext);
    let mut guard = match ctx.inner.lock() {
        Ok(g) => g,
        Err(_) => return 0,
    };
    guard.seek(SeekFrom::Current(0)).unwrap_or(0)
}

unsafe extern "C" fn stream_length_cb(ctx: *mut c_void) -> u64 {
    let ctx = &*(ctx as *const StreamContext);
    let guard = match ctx.inner.lock() {
        Ok(g) => g,
        Err(_) => return 0,
    };
    guard.length()
}