#4052·atuin

Search Index Race Conditions in the Daemon

Author: markovejnovicCreated Sep 3, 2026Updated Sep 23, 2026
Labelstype:bugarea:daemon

The search index in the daemon has a couple pretty nasty race conditions that we need to address at some point. The functions which are to blame are:

Function Notes Bugs
SearchGrpcService::maybe_rebuild_index(shells) Takes an existing search index, and returns None if the shells the index is scoped for same, or Some(new_index) if the new given shells are a larger set than those that the index currently contains. -
SearchComponent::rebuild_index_only Creates a new index object and then performs an atomic swap of the index. The race condition here is between building an index and any other operation which adds history indices into the index.
SearchComponent::prepare_index gRPC-facing rebuild_index_only equivalent, Same as the aforementioned, since it calls maybe_rebuild_index.
SearchGrpcService::search Searches for gRPC entries. Rebuilds the index when the client sends out a new shell. Same as the aforementioned.

rebuild_index_only

The code is

rust
    async fn rebuild_index_only(&self) {
        let Some(handle) = self.handle.as_ref() else {
            error!("Component not initialized");
            return;
        };
        info!("Rebuilding search index from database");

        // Create a new index
        let new_index = SearchIndex::new(self.index.read().await.shells.clone());
        if build_index_only(async || &new_index, handle).await.is_err() {
            return;
        }

        // Note that **any** add_history calls go through the .read() side of self.index which
        // is an rwlock.
        // If we get a new history here, it would hit the **old** index, rather than the
        // new one.

        info!("Search index rebuild complete; {} unique commands", new_index.command_count());
        *self.index.write().await = new_index;
    }

I think the correct design here is to have something like a new type which wraps the shell index and acts as its guard. I am imagining something like

rust
struct SearchIndexBuilder {
  missed_history: mpsc::Queue<History>,
  output: ArcSwap<SearchIndex>,
}

impl SearchIndexBuilder {
  fn spawn(output: ArcSwap<SearchIndex>) {
    tokio::spawn(async || {
       let new_idx = do_the_rebuild_logic_with_the_database();

       // more thread safe, but not completely.
       // need a final lock on something to ensure we fully exhaust missed_history
       // this implementation is still racy:
       // the queue might get something added to it while we're exhausting it
       for h in self.missed_history { new_idx.add_history(history); }
       self.output.swap(new_idx);
    });
  }

  fn push(&self, history: History) {
    self.missed_history.push(history);
  }
}

pub struct SearchIndexOuter {
  // note the arc-swap crate seems to have some problems (seqcst feels wrong, in their docs)
  active_idx: ArcSwap<SearchIndex>,
  active_builder: Option<SearchIndexBuilder>,
}

impl SearchIndexOuter {
  pub async fn rebuild(&self) {
    // obviously this debug assert shouldn't need to exist.
    // really i think what rebuild should do is actually have two builders:
    // one rebuilder is considered the "active one", ie. the one that's currently running
    // another rebuilder is actually a mailbox (1-sized overwriting queue) which contains another rebuilder
    // if no active rebuilder exists, we can simply pull the rebuilder from the mailbox and fire it off.
    // if an active rebuilder exists -- when it is done, it can pull the scheduled rebuilder.
    //
    // This is to support non-blocking operation where someone might reasonably want to fire-and-forget rebuilding.
    // maybe there's a cleaner way, I didn't think about this too much.
    debug_assert!(self.active_builder.is_none());

    self.active_builder = Some(SearchIndexBuilder::spawn())
  }

  // Push a new entry into the search index.
  pub async fn push(&self, history: &History) {
    self.active_idx.add_history(history);
    if let Some(b) = self.active_builder {
      b.push(history);
    }
  }

}

I'm using the word SearchIndexOuter here, but I'd really like to see SearchIndex be renamed to ActiveSearchIndex and SearchIndexOuter to be called SearchIndex and act as a facade into it.


See greptile comments on https://github.com/atuinsh/atuin/pull/4045