[bug] File-backed metastore blocks index reads during each metadata polling reload

Ouverte
#7,003 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
48/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
rust

Piste de recherche

Start with quickwit-metastore/src/metastore/file_backed/lazy_file_backed_index.rs, tracing poll_index_metadata_once and the polling task; then read the default URI setup in quickwit-config/src/node_config/serialize.rs and the shared read guard in quickwit-metastore/src/metastore/file_backed/mod.rs. Run the supplied reproduction as described in the issue. Done means periodic metadata refresh no longer blocks index reads in the reported scenario while the intended multi-writer behavior is preserved.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

area:metastore area:performance needs-triage

Describe the bug

The file-backed metastore starts one metadata polling task per index as soon as that index is first loaded, because the default metastore URI carries #polling_interval=30s. Every interval, the task takes the same per-index tokio::sync::Mutex<FileBackedIndex> that serves reads, downloads {index}/metastore.json from the storage backend, deserializes the whole index, and replaces the cached copy. The guard is held for the entire download and parse, so every list_splits call that a search issues while resolving its splits waits behind a background refresh it did not request.

The path is enabled by default rather than opt-in. quickwit-config builds the default metastore URI with the fragment already attached, and FileBackedMetastoreFactory converts the fragment into Some(Duration) for every LazyFileBackedIndex it constructs from the manifest. In a single-node deployment the reload never observes an external writer, because the same process is the only writer, so the periodic download is pure overhead on the read path. With N loaded indexes the node performs N full metadata downloads every 30 seconds and holds each index's mutex for the duration of its own download.

The download has no deadline. On file:// it is a plain filesystem read, and on S3 it goes through the retry helper (quickwit-storage/src/object_storage/s3_compatible_storage.rs:202, five attempts, jittered backoff up to 20 s) with no operation timeout configured (quickwit-storage/src/object_storage/s3_compatible_storage.rs:165), so a slow or stalled backend turns a periodic refresh into an indefinite hold on the index.

Root cause

The excerpts follow the interval from the default configuration to the polling task and to the readers that share its guard. Line numbers refer to commit 7b256dd3.

1. The default metastore URI enables polling.

// quickwit-config/src/node_config/serialize.rs:134-136
fn default_metastore_uri(data_dir_uri: &Uri) -> Uri {
    data_dir_uri.join("indexes#polling_interval=30s").expect("Failed to create default metastore URI. This should never happen! Please, report on https://github.com/quickwit-oss/quickwit/issues.")
}
// quickwit-config/src/node_config/serialize.rs:342-345
        let metastore_uri = self
            .metastore_uri
            .resolve_optional(env_vars)?
            .unwrap_or_else(|| default_metastore_uri(&data_dir_uri));

The factory strips the fragment and keeps the parsed duration (quickwit-metastore/src/metastore/file_backed/file_backed_metastore_factory.rs:110).

2. Every index from the manifest inherits that interval.

// quickwit-metastore/src/metastore/file_backed/state.rs:50-58
                IndexStatus::Active => {
                    let lazy_index = LazyFileBackedIndex::new(
                        storage.clone(),
                        index_id.clone(),
                        polling_interval_opt,
                        None,
                    );
                    (index_id, LazyIndexStatus::Active(lazy_index))
                }

The last argument is None, so the index starts unloaded and no task exists yet.

3. The first load spawns the polling task.

// quickwit-metastore/src/metastore/file_backed/lazy_file_backed_index.rs:67-86
    pub async fn get(&self) -> MetastoreResult<Arc<Mutex<FileBackedIndex>>> {
        self.lazy_index
            .get_or_try_init(|| async move {
                let index = load_index(&*self.storage, &self.index_id).await?;
                let index_mutex = Arc::new(Mutex::new(index));
                // When the index is loaded lazily, the polling task is not started in the
                // constructor so we do it here when the index is actually loaded.
                if let Some(polling_interval) = self.polling_interval_opt {
                    spawn_index_metadata_polling_task(
                        self.storage.clone(),
                        self.index_id.clone(),
                        Arc::downgrade(&index_mutex),
                        polling_interval,
                    );
                }
                Ok(index_mutex)
            })
            .await
            .cloned()
    }

From this point on, every index that any request has touched is polled for the lifetime of the process.

4. Each tick takes the index mutex before touching storage.

// quickwit-metastore/src/metastore/file_backed/lazy_file_backed_index.rs:89-103
async fn poll_index_metadata_once(
    storage: &dyn Storage,
    index_id: &str,
    index_mutex: &Mutex<FileBackedIndex>,
) {
    let mut locked_index = index_mutex.lock().await;
    if locked_index.flip_recently_modified_down() {
        return;
    }
    let load_index_result = load_index(storage, index_id).await;

    match load_index_result {
        Ok(index) => {
            *locked_index = index;
        }

Only a local write since the previous tick skips the reload. An idle index, which is exactly the index whose readers are served from memory, reloads every interval.

5. The task loop repeats the reload once per interval.

// quickwit-metastore/src/metastore/file_backed/lazy_file_backed_index.rs:120-136
fn spawn_index_metadata_polling_task(
    storage: Arc<dyn Storage>,
    index_id: IndexId,
    metastore_weak: Weak<Mutex<FileBackedIndex>>,
    polling_interval: Duration,
) {
    tokio::task::spawn(async move {
        let mut interval = tokio::time::interval(polling_interval);
        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        interval.tick().await; //< this is to prevent fetch right after the first population of the data.

        while let Some(metadata_mutex) = metastore_weak.upgrade() {
            interval.tick().await;
            poll_index_metadata_once(&*storage, &index_id, &metadata_mutex).await;
        }
    });
}

6. The download and the deserialization both run under the guard.

// quickwit-metastore/src/metastore/file_backed/store_operations.rs:45-69
pub(super) async fn load_index(
    storage: &dyn Storage,
    index_id: &str,
) -> MetastoreResult<FileBackedIndex> {
    let metastore_filepath = metastore_filepath(index_id);

    let content = storage
        .get_all(&metastore_filepath)
        .await
        .map_err(|storage_err| convert_error(index_id, storage_err))?;

    let index: FileBackedIndex = serde_utils::from_json_bytes(&content)?;

    if index.index_id() != index_id {
        return Err(MetastoreError::Internal {
            message: "inconsistent manifest: index_id mismatch".to_string(),
            cause: format!(
                "expected index_id `{}`, but found `{}`",
                index_id,
                index.index_id()
            ),
        });
    }
    Ok(index)
}

The hold therefore covers the full GET plus the parse of a payload that grows with the number of splits in the index.

7. Readers acquire the same mutex.

// quickwit-metastore/src/metastore/file_backed/mod.rs:290-302
    async fn get_locked_index(
        &self,
        index_id: &str,
    ) -> MetastoreResult<OwnedMutexGuard<FileBackedIndex>> {
        loop {
            let index = self.index(index_id).await?;
            let locked_index = index.lock_owned().await;

            if !locked_index.discarded {
                return Ok(locked_index);
            }
        }
    }

read_any reaches this function on every metadata read (quickwit-metastore/src/metastore/file_backed/mod.rs:275), and mutate takes the same guard for writes (quickwit-metastore/src/metastore/file_backed/mod.rs:212).

8. Search resolves its splits through that read path.

// quickwit-search/src/lib.rs:253-258
    let list_splits_request = ListSplitsRequest::try_from_list_splits_query(&query)?;
    let splits_metadata: Vec<SplitMetadata> = metastore
        .list_splits(list_splits_request)
        .await?
        .collect_splits_metadata()
        .await?;

Impact

Every loaded index adds one full metadata download per polling interval to the critical section of its own reads. Searches that touch the index wait for that download inside list_splits, so the search tail latency inherits the object-store read latency on a fixed 30 s cadence. The indexer's publish_splits waits as well, because it takes the same guard. On a node that holds many indexes, the polling itself becomes a steady read load: N full metadata GETs every 30 seconds, each holding a per-index lock for its own duration.

The consequence is bounded while the backend is responsive and unbounded when it is not, since the reload carries no deadline and a stalled GET is not cancelled. In a single-node deployment the reload observes no writer other than the local process, so the entire path is overhead there.

Steps to reproduce

The harness below enables polling on a metastore over a MockStorage, holds the polling reload inside get_all with a gate, and compares a list_splits call taken before the first poll with the same call issued while the reload is held. A second test in the same file, omitted here for length, runs the same slow storage with polling_interval = None and shows that the read path stays in memory. Place the file at quickwit-metastore/tests/polling_metastore_reload_blocks_reads.rs and run cargo test -p quickwit-metastore --test polling_metastore_reload_blocks_reads -- --nocapture from the Cargo workspace root.

Test harness
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use quickwit_common::uri::Uri;
use quickwit_config::IndexConfig;
use quickwit_metastore::{CreateIndexRequestExt, FileBackedMetastore, ListSplitsRequestExt};
use quickwit_proto::metastore::{
    CreateIndexRequest, IndexMetadataRequest, ListSplitsRequest, MetastoreService,
};
use quickwit_proto::types::IndexUid;
use quickwit_storage::{MockStorage, RamStorage, Storage};
use tokio::time::{sleep, timeout};

const POLL_INTERVAL: Duration = Duration::from_millis(600);
const HOLD_LIMIT: Duration = Duration::from_secs(10);
const WINDOW: Duration = Duration::from_millis(300);
const MEMORY_READ_LIMIT: Duration = Duration::from_millis(120);

async fn seed_index(metastore: &FileBackedMetastore, index_id: &str) -> IndexUid {
    let index_config = IndexConfig::for_test(index_id, &format!("ram:///indexes/{index_id}"));
    let create_request = CreateIndexRequest::try_from_index_config(&index_config).unwrap();
    metastore
        .create_index(create_request)
        .await
        .unwrap()
        .index_uid
        .expect("create_index must return an index uid")
}

async fn wait_for(flag: &AtomicBool, what: &str) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while !flag.load(Ordering::SeqCst) {
        assert!(Instant::now() < deadline, "timed out waiting for {what}");
        sleep(Duration::from_millis(2)).await;
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn polling_reload_parks_readers_every_interval() {
    let ram_storage = RamStorage::default();
    let seeding_metastore = FileBackedMetastore::try_new(Arc::new(ram_storage.clone()), None)
        .await
        .unwrap();
    let uid = seed_index(&seeding_metastore, "index-polled").await;
    drop(seeding_metastore);

    let manifest_bytes = ram_storage.get_all(Path::new("manifest.json")).await.unwrap();
    let index_path = PathBuf::from(format!("{}/metastore.json", uid.index_id));
    let index_bytes = ram_storage.get_all(&index_path).await.unwrap();

    // The warm-up load runs with the gate disarmed; only the polling reload is held.
    let armed = Arc::new(AtomicBool::new(false));
    let reload_entered = Arc::new(AtomicBool::new(false));
    let hold = Arc::new(AtomicBool::new(true));

    let mut mock_storage = MockStorage::default();
    mock_storage
        .expect_uri()
        .return_const(Uri::for_test("ram:///"));
    mock_storage
        .expect_exists()
        .returning(|path| Ok(path == Path::new("manifest.json")));
    {
        let index_path = index_path.clone();
        let index_bytes = index_bytes.clone();
        let armed = armed.clone();
        let reload_entered = reload_entered.clone();
        let hold = hold.clone();
        mock_storage.expect_get_all().returning(move |path| {
            if path == Path::new("manifest.json") {
                return Ok(manifest_bytes.clone());
            }
            if path == index_path.as_path() {
                if armed.load(Ordering::SeqCst) {
                    // The caller holds the per-index mutex here: stay until released.
                    reload_entered.store(true, Ordering::SeqCst);
                    let deadline = Instant::now() + HOLD_LIMIT;
                    while hold.load(Ordering::SeqCst) && Instant::now() < deadline {
                        std::thread::sleep(Duration::from_millis(1));
                    }
                }
                return Ok(index_bytes.clone());
            }
            panic!("unexpected get_all({})", path.display());
        });
    }
    mock_storage.expect_put().returning(|_, _| Ok(()));

    let metastore = FileBackedMetastore::try_new(Arc::new(mock_storage), Some(POLL_INTERVAL))
        .await
        .unwrap();
    // Warm-up: loads the index once and spawns its polling task.
    metastore
        .index_metadata(IndexMetadataRequest::for_index_uid(uid.clone()))
        .await
        .unwrap();

    let control_started = Instant::now();
    let _ = metastore
        .list_splits(ListSplitsRequest::try_from_index_uid(uid.clone()).unwrap())
        .await
        .unwrap();
    assert!(control_started.elapsed() < MEMORY_READ_LIMIT);
    println!("[control] list_splits before the first poll: {:?}", control_started.elapsed());

    armed.store(true, Ordering::SeqCst);
    wait_for(&reload_entered, "the polling reload").await;

    // The clocks start before the spawn, so a probe that is scheduled late still counts
    // the time it spent waiting.
    let splits_started = Instant::now();
    let splits_probe = {
        let metastore = metastore.clone();
        let request = ListSplitsRequest::try_from_index_uid(uid.clone()).unwrap();
        tokio::spawn(async move {
            let _ = metastore.list_splits(request).await.unwrap();
        })
    };
    let metadata_started = Instant::now();
    let metadata_probe = {
        let metastore = metastore.clone();
        let request = IndexMetadataRequest::for_index_uid(uid.clone());
        tokio::spawn(async move {
            metastore.index_metadata(request).await.unwrap();
        })
    };

    // Inside a fixed window the reload is still gated, so both readers must be pending.
    sleep(WINDOW).await;
    assert!(
        !splits_probe.is_finished(),
        "list_splits returned while the polling reload still held the index mutex"
    );
    assert!(
        !metadata_probe.is_finished(),
        "index_metadata returned while the polling reload still held the index mutex"
    );
    println!("[trigger] both readers still pending after {WINDOW:?}");

    hold.store(false, Ordering::SeqCst);
    timeout(Duration::from_secs(5), splits_probe).await.unwrap().unwrap();
    timeout(Duration::from_secs(5), metadata_probe).await.unwrap().unwrap();
    println!("[trigger] list_splits waited {:?}", splits_started.elapsed());
    println!("[trigger] index_metadata waited {:?}", metadata_started.elapsed());
    assert!(splits_started.elapsed() >= WINDOW);
    assert!(metadata_started.elapsed() >= WINDOW);

    timeout(
        Duration::from_secs(5),
        metastore.index_metadata(IndexMetadataRequest::for_index_uid(uid)),
    )
    .await
    .unwrap()
    .unwrap();
    println!("[recovered] reads are served again after the reload");
}
Observed output

The first block is the harness above. The second block is the same slow storage with polling disabled, which loads the index once and then answers from memory.

[control] list_splits before the first poll: 147.949µs
[trigger] both readers still pending after 300ms
[trigger] list_splits waited 304.839225ms
[trigger] index_metadata waited 304.719636ms
[recovered] reads are served again after the reload

[control] one slow load over the store: 301.504128ms
[control] list_splits round 0: 286.318µs
[control] list_splits round 1: 253.768µs
[control] list_splits round 2: 122.509µs

Both waits of the first block match the gate window rather than the cost of either read, so both readers were parked on the index mutex while the background reload was still in flight. Without polling, the same storage costs one load of 301 ms and every later read returns in hundreds of microseconds.

Expected behavior

A background metadata refresh does not delay reads of the index it refreshes, and a request served from the cache returns without waiting for storage.

Actual behavior

Each polling tick holds the per-index mutex for a full metadata download and parse, so reads of that index wait for the refresh on every interval, and the wait is unbounded when the backend stalls.

Workaround

Configure metastore_uri without the #polling_interval=<n>s fragment. The factory only enables polling when the fragment matches, so a URI without it leaves every index with None and no polling task. This is safe where the local process is the only writer, which is the single-node case. Searchers that rely on a separate writer, including those using use_metastore_read_replica, keep the fragment and stay exposed.

Proposed fix

Fetch the metadata outside the per-index critical section, then re-acquire the guard and install the result only if the entry still matches the generation it was loaded against, the same way the error branch already replaces a stale entry. The reload could also be skipped when the process is the only writer, and the storage read needs an operation deadline so that a stalled backend cannot hold the lock indefinitely.

Environment

Quickwit 0.9.1, main at commit 7b256dd3, Linux x86_64, built and tested with the workspace default toolchain. The reproduction uses no special configuration: it constructs the metastore directly over a mock storage with an explicit polling interval and needs no running node.

Langage dominant
Rust
Étoiles
11.8k
Forks
628
Merge moyen
2 j 22 h
PR mergées (30 j)
50

Préparer son environnement

Ouvrir dans Codespaces

Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de quickwit-oss/quickwit

Toutes les issues de quickwit-oss/quickwit

Issues similaires

Plus d'issues Rust

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.