Skip to content

vector-store: separate concurrent insert/search operations - #339

Merged
ewienik merged 2 commits into
scylladb:masterfrom
ewienik:vector-474-separate-concurrent-operations
Jan 19, 2026
Merged

ewienik merged 2 commits into
scylladb:masterfrom
ewienik:vector-474-separate-concurrent-operations

Conversation

@ewienik

@ewienik ewienik commented Jan 13, 2026 •

Copy link
Copy Markdown
Collaborator

While testing we can see seldom crash in usearch running concurrent_add_and_search test. The crash is in the search path.

According to #330 and unum-cloud/USearch#697 we can run concurrently only one family of operations: add/insert is the first, search/count is the second. This patch introduces two family operations: insert and search. Each operation increases counter for operations as a flag that some task is running and decreases it at finish.

I've run 4000 times the concurrent_add_and_search test without crash.

Fixes: VECTOR-474

@QuerthDP

Copy link
Copy Markdown
Member

According to #330 and unum-cloud/USearch#697 we can run concurrently only one family of operations: add/insert is the first, search/count is the second. This patch introduces two family operations: insert and search.

According to unum-cloud/USearch#697 (comment) there are 3 operation families. What is the 3rd one in our case or we don't have such?

@ewienik

ewienik commented Jan 13, 2026

Copy link
Copy Markdown
Collaborator Author

According to #330 and unum-cloud/USearch#697 we can run concurrently only one family of operations: add/insert is the first, search/count is the second. This patch introduces two family operations: insert and search.

According to unum-cloud/USearch#697 (comment) there are 3 operation families. What is the 3rd one in our case or we don't have such?

The 3rd family (remove, resize) is handled separately as exclusive (not concurrent) operations.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses concurrency crashes in the usearch vector index by implementing a mechanism to separate concurrent insert and search operations into two distinct operation families, preventing them from running simultaneously. According to the USearch library constraints, only operations within the same family (insert/add or search/count) can run concurrently.

Changes:

  • Introduces an Operation enum to categorize operations as either Insert or Search
  • Adds synchronization fields to IndexState: current_operation (tracks active family) and operations (counts active tasks)
  • Implements wait_for_operation() to enforce operation family separation before spawning tasks
  • Adds finish_operation() cleanup calls in both tokio and rayon task paths

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ewienik
ewienik marked this pull request as draft January 14, 2026 11:20
While testing we can see seldom crashes in usearch running
concurrent_add_and_search test. The crash is in the search path.

According to scylladb#330 and unum-cloud/USearch#697 we can run concurrently only one
family of operations: add/insert is the first, search/count is the second. This
patch introduces two family operations: insert and search. The commit
introduces Operation type to synchronise between them. Each operation needs to
get permit to proceed, and getting the permit is an async task (it could wait
if the operation is different than requested).

The Permit contains counter and notifier - in Drop if counter decreses to 0 the
listener will be notified.

Fixes: VECTOR-474
@ewienik

ewienik commented Jan 14, 2026

Copy link
Copy Markdown
Collaborator Author

Changelog for f2a3262

  • rebase to master
  • implement Operation structure as a synchronizing abstraction
range diff
1:  7f1d247e ! 1:  78aa7d56 vector-store: separate concurrent insert/search operations
    @@ Metadata
      ## Commit message ##
         vector-store: separate concurrent insert/search operations
     
    -    While testing we can see seldom crash in usearch running
    +    While testing we can see seldom crashes in usearch running
         concurrent_add_and_search test. The crash is in the search path.
     
         According to #330 and unum-cloud/USearch#697 we can run concurrently only one
         family of operations: add/insert is the first, search/count is the second. This
    -    patch introduces two family operations: insert and search. Each operation
    -    increases counter for operations as a flag that some task is running and
    -    decreases it at finish.
    +    patch introduces two family operations: insert and search. The commit
    +    introduces Operation type to synchronise between them. Each operation needs to
    +    get permit to proceed, and getting the permit is an async task (it could wait
    +    if the operation is different than requested).
    +
    +    The Permit contains counter and notifier - in Drop if counter decreses to 0 the
    +    listener will be notified.
     
         Fixes: VECTOR-474
     
    @@ crates/vector-store/src/index/usearch.rs: impl From<SpaceType> for MetricKind {
          }
      }
      
    -+#[derive(PartialEq)]
    -+enum Operation {
    -+    Insert,
    -+    Search,
    -+}
    ++mod operation {
    ++    use super::Index;
    ++    use std::sync::Arc;
    ++    use std::sync::atomic::AtomicUsize;
    ++    use std::sync::atomic::Ordering;
    ++    use tokio::sync::Notify;
     +
    - struct IndexState<I: UsearchIndex + Send + Sync + 'static> {
    -     idx: Arc<I>,
    -     keys: RwLock<BiMap<PrimaryKey, Key>>,
    -     dimensions: Dimensions,
    -     usearch_key: AtomicU64,
    -+    current_operation: RwLock<Operation>,
    -+    operations: AtomicU64,
    - }
    - 
    - impl<I: UsearchIndex + Send + Sync + 'static> IndexState<I> {
    -@@ crates/vector-store/src/index/usearch.rs: impl<I: UsearchIndex + Send + Sync + 'static> IndexState<I> {
    -             keys: RwLock::new(BiMap::new()),
    -             dimensions,
    -             usearch_key: AtomicU64::new(0),
    -+            current_operation: RwLock::new(Operation::Insert),
    -+            operations: AtomicU64::new(0),
    -         }
    -     }
    - 
    -+    /// Wait until it will be possible to spawn operation.
    -+    ///
    -+    /// The function must be called before spawning insert/search tasks as it blocks
    -+    /// until only requested family of operations is in progress.
    -+    async fn wait_for_operation(&self, msg: &Index) {
    -+        let operation = if matches!(msg, &Index::Add { .. }) {
    -+            Operation::Insert
    -+        } else {
    -+            Operation::Search
    -+        };
    ++    #[derive(PartialEq)]
    ++    enum Mode {
    ++        Insert,
    ++        Search,
    ++    }
     +
    -+        while *self.current_operation.read().unwrap() != operation {
    -+            if self.operations.load(Ordering::Relaxed) == 0 {
    -+                // it is safe to switch to the operation because there are no spawned tasks
    -+                // and self.operations won't be changed
    -+                *self.current_operation.write().unwrap() = operation;
    -+                break;
    ++    pub(super) struct Permit {
    ++        notify: Arc<Notify>,
    ++        counter: Arc<AtomicUsize>,
    ++    }
    ++
    ++    impl Drop for Permit {
    ++        fn drop(&mut self) {
    ++            let previous = self.counter.fetch_sub(1, Ordering::Relaxed);
    ++            if previous == 1 {
    ++                self.notify.notify_one();
     +            }
    -+            tokio::task::yield_now().await;
     +        }
    -+        self.operations.fetch_add(1, Ordering::Relaxed);
     +    }
     +
    -+    fn finish_operation(&self) {
    -+        self.operations.fetch_sub(1, Ordering::Relaxed);
    ++    pub(super) struct Operation {
    ++        mode: Mode,
    ++        notify: Arc<Notify>,
    ++        counter: Arc<AtomicUsize>,
     +    }
     +
    -     fn stop(&self) {
    -         self.idx.stop();
    -     }
    ++    impl Operation {
    ++        pub(super) fn new() -> Self {
    ++            Self {
    ++                mode: Mode::Insert,
    ++                notify: Arc::new(Notify::new()),
    ++                counter: Arc::new(AtomicUsize::new(0)),
    ++            }
    ++        }
    ++
    ++        /// Wait until it will be possible to spawn operation.
    ++        ///
    ++        /// The function must be called before spawning operation tasks as it blocks
    ++        /// until only requested family of operations is in progress.
    ++        pub(super) async fn permit(&mut self, msg: &Index) -> Permit {
    ++            let mode = mode(msg);
    ++
    ++            while self.mode != mode {
    ++                if self.counter.load(Ordering::Relaxed) == 0 {
    ++                    // it is safe to switch to the operation because there are no spawned tasks
    ++                    // and self.counter won't be changed
    ++                    self.mode = mode;
    ++                    break;
    ++                }
    ++                self.notify.notified().await;
    ++            }
    ++            self.counter.fetch_add(1, Ordering::Relaxed);
    ++            Permit {
    ++                notify: Arc::clone(&self.notify),
    ++                counter: Arc::clone(&self.counter),
    ++            }
    ++        }
    ++    }
    ++
    ++    fn mode(msg: &Index) -> Mode {
    ++        match msg {
    ++            Index::Ann { .. } | Index::FilteredAnn { .. } | Index::Count { .. } => Mode::Search,
    ++            Index::Add { .. } => Mode::Insert,
    ++            _ => unreachable!(),
    ++        }
    ++    }
    ++}
    ++
    + struct IndexState<I: UsearchIndex + Send + Sync + 'static> {
    +     idx: Arc<I>,
    +     keys: RwLock<BiMap<PrimaryKey, Key>>,
    +@@ crates/vector-store/src/index/usearch.rs: fn new<I: UsearchIndex + Send + Sync + 'static>(
    +                 ));
    + 
    +                 let mut allocate_prev = Allocate::Can;
    ++                let mut operation = operation::Operation::new();
    + 
    +                 while let Some(msg) = rx.recv().await {
    +                     if !check_memory_allocation(&msg, &memory, &mut allocate_prev, &id).await {
    +@@ crates/vector-store/src/index/usearch.rs: fn new<I: UsearchIndex + Send + Sync + 'static>(
    +                     }
    + 
    +                     dispatch_task(
    ++                        &mut operation,
    +                         msg,
    +                         Arc::clone(&idx),
    +                         Arc::clone(&primary_key_columns),
    +@@ crates/vector-store/src/index/usearch.rs: fn get_index_concurrency(
    + }
    + 
    + async fn dispatch_task(
    ++    operation: &mut operation::Operation,
    +     msg: Index,
    +     idx: Arc<TokioRwLock<IndexState<impl UsearchIndex + Send + Sync + 'static>>>,
    +     primary_key_columns: Arc<Vec<ColumnName>>,
     @@ crates/vector-store/src/index/usearch.rs: async fn dispatch_task(
              return;
          }
          let lock = idx.read_owned().await;
    -+    lock.wait_for_operation(&msg).await;
    ++    let operation_permit = operation.permit(&msg).await;
          if should_run_on_tokio(&msg) {
              let permit = Arc::clone(tokio_semaphore).acquire_owned().await.unwrap();
              tokio::spawn(async move {
    -             crate::move_to_the_end_of_async_runtime_queue().await;
    +@@ crates/vector-store/src/index/usearch.rs: async fn dispatch_task(
                  process(msg, &lock, &primary_key_columns);
    -+            lock.finish_operation();
                  drop(permit);
                  drop(lock);
    ++            drop(operation_permit);
              });
    -@@ crates/vector-store/src/index/usearch.rs: async fn dispatch_task(
    +     } else {
              let permit = Arc::clone(rayon_semaphore).acquire_owned().await.unwrap();
    -         rayon::spawn(move || {
    +@@ crates/vector-store/src/index/usearch.rs: async fn dispatch_task(
                  process(msg, &lock, &primary_key_columns);
    -+            lock.finish_operation();
                  drop(permit);
                  drop(lock);
    ++            drop(operation_permit);
              });
    +     }
    + }
-:  -------- > 2:  f2a32629 vector-store: refactor tokio rwlock into operation

@ewienik
ewienik force-pushed the vector-474-separate-concurrent-operations branch from 7f1d247 to f2a3262 Compare January 14, 2026 14:57
@ewienik
ewienik marked this pull request as ready for review January 14, 2026 14:57

@knowack1 knowack1 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting solution—I like it! By the way, while reading the unum-cloud/USearch#697 (comment) comment, I hadn't noticed that constraint, but I see it now. Thanks!

Requesting changes, as I think there is one synchronization issue related to capacity, please take a look.

Operation synchroniziation struct introduced in a previous commit opened a
possibility to get rid of tokio rwlock. The same functionality (semaphore for
exclusive access to the usearch index) could be now reached by using the
Operation struct. Operation::permit_* functions are now responsible for waiting
until operation could be done concurrently or exclusively.

The commit refactors Operation by adding two separate functions:
permit_for_message and permit_for_reserve, for additional operation (reserve)
which is dynamically checked during add operation.

The commit refactors reserve operation to allow running spawn directly in
dispatch_task. needs_more_capacity function is now run directly in
dispatch_task to limit needs for Arc::clone and to be able to use &mut
operation.

The commit refactors needs_more_capacity function to use keys.len() without
asking idx for count() (to be able to check count during concurrent add/remove
operation).

The commit removes not needed newtype Semaphore as there is no more tokio
RwLock.
@ewienik
ewienik force-pushed the vector-474-separate-concurrent-operations branch from f2a3262 to fcd5eb9 Compare January 16, 2026 21:35
@ewienik
ewienik requested a review from knowack1 January 16, 2026 21:36
@ewienik
ewienik added this pull request to the merge queue Jan 19, 2026
Merged via the queue into scylladb:master with commit 7136c19 Jan 19, 2026
@ewienik
ewienik deleted the vector-474-separate-concurrent-operations branch January 19, 2026 08:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants