-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_db.rs
More file actions
354 lines (320 loc) · 11.8 KB
/
Copy pathasync_db.rs
File metadata and controls
354 lines (320 loc) · 11.8 KB
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
// Copyright 2026 James Gober. Licensed under Apache-2.0 OR MIT.
//! The async surface (`async` feature).
//!
//! The iqdb family is synchronous by design — a nearest-neighbour search is a
//! CPU-bound scan or graph walk, and a durable write is a blocking `fsync`,
//! not async I/O. Wrapping that work in a future buys nothing and blocking it
//! on the executor thread would stall every other task on the runtime.
//!
//! [`AsyncIqdb`] is therefore a thin Tokio adapter, not a re-implementation:
//! it holds an `Arc<Iqdb>` and runs each blocking call on Tokio's dedicated
//! blocking pool via [`tokio::task::spawn_blocking`], so the executor thread
//! is never blocked. The synchronous [`Iqdb`](crate::Iqdb) API is unchanged
//! and remains the source of truth; everything here delegates to it.
//!
//! Cheap, non-blocking accessors (`len`, `dim`, `metric`, …) stay synchronous
//! — there is nothing to offload.
use std::path::Path;
use std::sync::Arc;
use tokio::task::JoinError;
use crate::config::IqdbConfig;
use crate::error::Result;
use crate::{CacheStats, DistanceMetric, Filter, Hit, Iqdb, Metadata, Vector, VectorId};
/// An async handle over an [`Iqdb`](crate::Iqdb) database.
///
/// Every fallible / blocking operation is offloaded to Tokio's blocking pool,
/// so awaiting a search or a write never stalls the executor. Construct one
/// with [`AsyncIqdb::open_in_memory`] or [`AsyncIqdb::open`]; it is `Clone`
/// (cheap — it shares the underlying handle through an `Arc`) and
/// `Send + Sync`.
///
/// # Examples
///
/// ```
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// use iqdb::{AsyncIqdb, DistanceMetric, Vector, VectorId};
///
/// let db = AsyncIqdb::open_in_memory(3, DistanceMetric::Cosine).await?;
/// db.upsert(VectorId::from(1u64), Vector::new(vec![1.0, 0.0, 0.0])?, None).await?;
/// db.upsert(VectorId::from(2u64), Vector::new(vec![0.0, 1.0, 0.0])?, None).await?;
///
/// let hits = db.search(Vector::new(vec![1.0, 0.0, 0.0])?, 1).await?;
/// assert_eq!(hits[0].id, VectorId::from(1u64));
/// db.close().await?;
/// # Ok::<(), iqdb::Error>(())
/// # }).unwrap();
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub struct AsyncIqdb {
inner: Arc<Iqdb>,
}
impl AsyncIqdb {
/// Open an ephemeral, in-memory database (exact flat index).
///
/// In-memory construction does not touch the filesystem, so this resolves
/// without offloading to the blocking pool.
///
/// # Errors
///
/// [`Error::Config`](crate::Error::Config) if `dim` is zero.
pub async fn open_in_memory(dim: usize, metric: DistanceMetric) -> Result<Self> {
Ok(Self {
inner: Arc::new(Iqdb::open_in_memory(dim, metric)?),
})
}
/// Open an in-memory database from a full [`IqdbConfig`].
///
/// # Errors
///
/// As [`Iqdb::open_in_memory_with`](crate::Iqdb::open_in_memory_with).
pub async fn open_in_memory_with(config: IqdbConfig) -> Result<Self> {
Ok(Self {
inner: Arc::new(Iqdb::open_in_memory_with(config)?),
})
}
/// Open or create a durable, file-backed database at `path`. The open
/// (snapshot load + WAL replay) runs on the blocking pool.
///
/// # Errors
///
/// As [`Iqdb::open`](crate::Iqdb::open).
pub async fn open<P: AsRef<Path>>(path: P, dim: usize, metric: DistanceMetric) -> Result<Self> {
let path = path.as_ref().to_path_buf();
let inner =
unwrap_join(tokio::task::spawn_blocking(move || Iqdb::open(path, dim, metric)).await)?;
Ok(Self {
inner: Arc::new(inner),
})
}
/// Open or create a durable, file-backed database from a full
/// [`IqdbConfig`].
///
/// # Errors
///
/// As [`Iqdb::open_with`](crate::Iqdb::open_with).
pub async fn open_with<P: AsRef<Path>>(path: P, config: IqdbConfig) -> Result<Self> {
let path = path.as_ref().to_path_buf();
let inner =
unwrap_join(tokio::task::spawn_blocking(move || Iqdb::open_with(path, config)).await)?;
Ok(Self {
inner: Arc::new(inner),
})
}
/// Insert or replace the record under `id`. See [`Iqdb::upsert`](crate::Iqdb::upsert).
///
/// # Errors
///
/// As [`Iqdb::upsert`](crate::Iqdb::upsert).
pub async fn upsert(
&self,
id: VectorId,
vector: Vector,
metadata: Option<Metadata>,
) -> Result<()> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.upsert(id, vector, metadata)).await)
}
/// Look up the stored vector and metadata for `id`. See [`Iqdb::get`](crate::Iqdb::get).
///
/// # Errors
///
/// As [`Iqdb::get`](crate::Iqdb::get).
pub async fn get(&self, id: VectorId) -> Result<Option<(Vector, Option<Metadata>)>> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.get(&id)).await)
}
/// Delete the record under `id`. See [`Iqdb::delete`](crate::Iqdb::delete).
///
/// # Errors
///
/// As [`Iqdb::delete`](crate::Iqdb::delete).
pub async fn delete(&self, id: VectorId) -> Result<bool> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.delete(&id)).await)
}
/// Top-`k` similarity search. See [`Iqdb::search`](crate::Iqdb::search).
///
/// Takes the query by value because the work runs on another thread; clone
/// the query if you need to keep it.
///
/// # Errors
///
/// As [`Iqdb::search`](crate::Iqdb::search).
///
/// # Examples
///
/// ```
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// use iqdb::{AsyncIqdb, DistanceMetric, Vector, VectorId};
///
/// let db = AsyncIqdb::open_in_memory(2, DistanceMetric::Euclidean).await?;
/// db.upsert(VectorId::from(1u64), Vector::new(vec![0.0, 0.0])?, None).await?;
/// db.upsert(VectorId::from(2u64), Vector::new(vec![9.0, 9.0])?, None).await?;
///
/// let hits = db.search(Vector::new(vec![0.1, 0.1])?, 1).await?;
/// assert_eq!(hits[0].id, VectorId::from(1u64));
/// # Ok::<(), iqdb::Error>(())
/// # }).unwrap();
/// ```
pub async fn search(&self, query: Vector, k: usize) -> Result<Vec<Hit>> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.search(&query, k)).await)
}
/// Top-`k` search filtered by metadata. See [`Iqdb::search_with`](crate::Iqdb::search_with).
///
/// # Errors
///
/// As [`Iqdb::search_with`](crate::Iqdb::search_with).
pub async fn search_with(&self, query: Vector, k: usize, filter: Filter) -> Result<Vec<Hit>> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.search_with(&query, k, filter)).await)
}
/// Batch search, one result list per query. See [`Iqdb::search_batch`](crate::Iqdb::search_batch).
///
/// # Errors
///
/// As [`Iqdb::search_batch`](crate::Iqdb::search_batch).
pub async fn search_batch(&self, queries: Vec<Vector>, k: usize) -> Result<Vec<Vec<Hit>>> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.search_batch(&queries, k)).await)
}
/// Batch search with a shared filter. See [`Iqdb::search_batch_with`](crate::Iqdb::search_batch_with).
///
/// # Errors
///
/// As [`Iqdb::search_batch_with`](crate::Iqdb::search_batch_with).
pub async fn search_batch_with(
&self,
queries: Vec<Vector>,
k: usize,
filter: Filter,
) -> Result<Vec<Vec<Hit>>> {
let db = Arc::clone(&self.inner);
unwrap_join(
tokio::task::spawn_blocking(move || db.search_batch_with(&queries, k, filter)).await,
)
}
/// Rebuild / retrain the approximate index. See [`Iqdb::optimize`](crate::Iqdb::optimize).
///
/// # Errors
///
/// As [`Iqdb::optimize`](crate::Iqdb::optimize).
pub async fn optimize(&self) -> Result<()> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.optimize()).await)
}
/// Flush pending writes to durable storage. See [`Iqdb::flush`](crate::Iqdb::flush).
///
/// # Errors
///
/// As [`Iqdb::flush`](crate::Iqdb::flush).
pub async fn flush(&self) -> Result<()> {
let db = Arc::clone(&self.inner);
unwrap_join(tokio::task::spawn_blocking(move || db.flush()).await)
}
/// Close the database, compacting a file-backed store one final time.
/// Consumes the handle.
///
/// If other clones of this `AsyncIqdb` are still alive, the underlying
/// handle cannot be consumed, so this degrades to a final
/// [`flush`](Self::flush) and releases this clone.
///
/// # Errors
///
/// As [`Iqdb::close`](crate::Iqdb::close).
pub async fn close(self) -> Result<()> {
let db = self.inner;
unwrap_join(
tokio::task::spawn_blocking(move || match Arc::try_unwrap(db) {
Ok(handle) => handle.close(),
Err(shared) => shared.flush(),
})
.await,
)
}
/// The fixed dimensionality.
#[must_use]
pub fn dim(&self) -> usize {
self.inner.dim()
}
/// The fixed distance metric.
#[must_use]
pub fn metric(&self) -> DistanceMetric {
self.inner.metric()
}
/// Number of stored vectors.
#[must_use]
pub fn len(&self) -> usize {
self.inner.len()
}
/// `true` if no vectors are stored.
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Cache hit/miss statistics, or `None` when uncached.
#[must_use]
pub fn cache_stats(&self) -> Option<CacheStats> {
self.inner.cache_stats()
}
}
/// Resolve a `spawn_blocking` join result, re-raising a panic from the
/// blocking closure on the calling task. `spawn_blocking` tasks are not
/// cancellable, so a [`JoinError`] here always carries a panic.
fn unwrap_join<T>(res: std::result::Result<T, JoinError>) -> T {
match res {
Ok(value) => value,
Err(join) => std::panic::resume_unwind(join.into_panic()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vec2(a: f32, b: f32) -> Vector {
Vector::new(vec![a, b]).unwrap()
}
#[tokio::test]
async fn async_crud_round_trip() {
let db = AsyncIqdb::open_in_memory(2, DistanceMetric::Euclidean)
.await
.unwrap();
assert!(db.is_empty());
db.upsert(VectorId::from(1u64), vec2(0.0, 0.0), None)
.await
.unwrap();
db.upsert(VectorId::from(2u64), vec2(3.0, 4.0), None)
.await
.unwrap();
assert_eq!(db.len(), 2);
let (got, _) = db.get(VectorId::from(2u64)).await.unwrap().unwrap();
assert_eq!(got.as_slice(), &[3.0, 4.0]);
let hits = db.search(vec2(0.1, 0.1), 1).await.unwrap();
assert_eq!(hits[0].id, VectorId::from(1u64));
assert!(db.delete(VectorId::from(1u64)).await.unwrap());
assert_eq!(db.len(), 1);
db.close().await.unwrap();
}
#[tokio::test]
async fn async_handle_is_send_sync_and_cloneable() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<AsyncIqdb>();
let db = AsyncIqdb::open_in_memory(2, DistanceMetric::Cosine)
.await
.unwrap();
let clone = db.clone();
db.upsert(VectorId::from(1u64), vec2(1.0, 0.0), None)
.await
.unwrap();
// The clone observes the same shared state.
assert_eq!(clone.len(), 1);
}
#[tokio::test]
async fn async_rejects_zero_dim() {
assert!(
AsyncIqdb::open_in_memory(0, DistanceMetric::Cosine)
.await
.is_err()
);
}
}