diff --git a/quickwit/Cargo.lock b/quickwit/Cargo.lock index d0548910175..8d2360163e6 100644 --- a/quickwit/Cargo.lock +++ b/quickwit/Cargo.lock @@ -7579,15 +7579,14 @@ dependencies = [ "async-trait", "futures", "postcard", + "proptest", "quickwit-common", "quickwit-storage", "rand 0.10.3", "serde", "tantivy", - "tantivy-common", "tantivy-fst", "tempfile", - "time", "tokio", "tracing", ] @@ -8262,15 +8261,12 @@ dependencies = [ "md5", "metrics", "metrics-util", - "mini-moka", "mixtrics", "mockall", "opendal", "opendal-http-transport-reqwest", "percent-encoding", "pin-project", - "proptest", - "quick_cache", "quickwit-aws", "quickwit-common", "quickwit-config", @@ -8280,12 +8276,12 @@ dependencies = [ "reqsign-core", "reqsign-google", "reqwest 0.13.5", - "rustc-hash", "rustls 0.23.46", "serde", "serde_json", "stable_deref_trait", "tantivy", + "tantivy-common", "tempfile", "thiserror 2.0.21", "tokio", diff --git a/quickwit/quickwit-cli/src/tool.rs b/quickwit/quickwit-cli/src/tool.rs index 5ccac5eb65d..8eeb79d5a67 100644 --- a/quickwit/quickwit-cli/src/tool.rs +++ b/quickwit/quickwit-cli/src/tool.rs @@ -53,7 +53,7 @@ use quickwit_search::{SearchResponseRest, single_node_search}; use quickwit_serve::{ BodyFormat, SearchRequestQueryString, SortBy, search_request_from_api_request, }; -use quickwit_storage::{BundleStorage, Storage}; +use quickwit_storage::BundleFileRanges; use quickwit_transport::ChannelFactory; use thousands::Separable; use tracing::debug; @@ -755,14 +755,15 @@ async fn extract_split_cli(args: ExtractSplitArgs) -> anyhow::Result<()> { let index_storage = storage_resolver.resolve(index_metadata.index_uri()).await?; let split_file = PathBuf::from(format!("{}.split", args.split_id)); let split_bytes = index_storage.get_all(split_file.as_path()).await?; - let (bundle_storage, _hotcache_bytes) = - BundleStorage::open_from_split_bytes(index_storage, split_file, split_bytes)?; + let (file_ranges, _hotcache_bytes) = + BundleFileRanges::open_from_split_bytes(split_bytes.clone())?; std::fs::create_dir_all(&args.target_dir)?; - for path in bundle_storage.iter_files() { + for (path, range) in file_ranges.files { let mut out_path = args.target_dir.to_owned(); - out_path.push(path); + out_path.push(&path); println!("Copying {out_path:?}"); - bundle_storage.copy_to_file(path, &out_path).await?; + let file_slice = &split_bytes.as_slice()[range.start as usize..range.end as usize]; + std::fs::write(&out_path, file_slice)?; } println!("{} Split successfully extracted.", "✔".color(GREEN_COLOR)); diff --git a/quickwit/quickwit-config/src/node_config/mod.rs b/quickwit/quickwit-config/src/node_config/mod.rs index 8108344c69a..e9fcee13a18 100644 --- a/quickwit/quickwit-config/src/node_config/mod.rs +++ b/quickwit/quickwit-config/src/node_config/mod.rs @@ -644,25 +644,6 @@ impl CacheConfig { self.memory_capacity.unwrap_or_default() } - pub fn memory_capacity_for_virtual_cache( - &mut self, - real_memory_capacity: ByteSize, - ) -> ByteSize { - let memory_capacity = self.memory_capacity.unwrap_or(real_memory_capacity); - self.memory_capacity = Some(memory_capacity); - memory_capacity - } - - pub fn policy(&self) -> CachePolicy { - self.policy.unwrap_or_default() - } - - pub fn policy_for_virtual_cache(&mut self, real_policy: CachePolicy) -> CachePolicy { - let policy = self.policy.unwrap_or(real_policy); - self.policy = Some(policy); - policy - } - fn deserialize_with_default<'de, D, const DEFAULT_MEMORY_CAPACITY: u64>( deserializer: D, ) -> Result diff --git a/quickwit/quickwit-directories/Cargo.toml b/quickwit/quickwit-directories/Cargo.toml index 6ba9b813be7..66f99687807 100644 --- a/quickwit/quickwit-directories/Cargo.toml +++ b/quickwit/quickwit-directories/Cargo.toml @@ -17,16 +17,15 @@ futures = { workspace = true } postcard = { workspace = true } serde = { workspace = true } tantivy = { workspace = true } -tantivy-common = { workspace = true } -time = { workspace = true } -tokio = { workspace = true } tracing = { workspace = true } -quickwit-common = { workspace = true } quickwit-storage = { workspace = true } [dev-dependencies] +proptest = { workspace = true } +quickwit-common = { workspace = true } tantivy-fst = { workspace = true } quickwit-storage = { workspace = true, features = ["testsuite"] } rand = { workspace = true } tempfile = { workspace = true } +tokio = { workspace = true } diff --git a/quickwit/quickwit-directories/src/bundle_directory.rs b/quickwit/quickwit-directories/src/bundle_directory.rs index 3990e9a013a..fd72ea4c8e8 100644 --- a/quickwit/quickwit-directories/src/bundle_directory.rs +++ b/quickwit/quickwit-directories/src/bundle_directory.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use std::{fmt, io}; use quickwit_storage::{ - BundleFileRanges, OwnedBytes, Storage, StorageErrorKind, StorageResult, + BundleFileRanges, OwnedBytes, SplitStorageReader, Storage, StorageErrorKind, StorageResult, locate_split_footer_range, strip_split_footer_trailer, }; use tantivy::directory::error::OpenReadError; @@ -29,7 +29,7 @@ use tantivy::{Directory, HasLen}; /// `BundleDirectory` is a read-only directory that opens a "split bundle" and serves its files /// through Tantivy's [`Directory`] interface. /// -/// It is the `Directory` equivalent of `BundleStorage`. +/// It is the local-file `Directory` counterpart of `SplitBundle`. /// /// A split has the following layout (all integer fields are little-endian): /// @@ -99,11 +99,12 @@ pub async fn read_split_footer( storage: Arc, path: &Path, ) -> StorageResult<(OwnedBytes, OwnedBytes)> { - let split_len = storage.file_num_bytes(path).await?; - let footer_range = locate_split_footer_range(storage.as_ref(), path, split_len) + let reader = SplitStorageReader::new(storage); + let split_len = reader.file_num_bytes(path).await?; + let footer_range = locate_split_footer_range(&reader, path, split_len) .await .map_err(|error| StorageErrorKind::Internal.with_error(error))?; - let split_footer_with_trailer = storage + let split_footer_with_trailer = reader .get_slice(path, footer_range.start as usize..footer_range.end as usize) .await?; let split_footer = diff --git a/quickwit/quickwit-storage/src/cache/byte_range_cache.rs b/quickwit/quickwit-directories/src/byte_range_cache.rs similarity index 93% rename from quickwit/quickwit-storage/src/cache/byte_range_cache.rs rename to quickwit/quickwit-directories/src/byte_range_cache.rs index 6c2525dbb6f..327e68f5425 100644 --- a/quickwit/quickwit-storage/src/cache/byte_range_cache.rs +++ b/quickwit/quickwit-directories/src/byte_range_cache.rs @@ -12,13 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; -use rustc_hash::FxHashMap; use tantivy::directory::OwnedBytes; struct CacheValue { @@ -26,19 +25,13 @@ struct CacheValue { bytes: OwnedBytes, } +#[derive(Default)] struct FileByteRangeCacheState { blocks: BTreeMap, num_bytes: u64, } impl FileByteRangeCacheState { - fn with_infinite_capacity() -> Self { - FileByteRangeCacheState { - blocks: BTreeMap::new(), - num_bytes: 0, - } - } - fn get_slice(&mut self, byte_range: Range) -> Option { if byte_range.start == byte_range.end { return Some(OwnedBytes::empty()); @@ -190,7 +183,7 @@ impl FileByteRangeCacheState { /// Clones share the same cached ranges. Obtain this cache from /// [`ByteRangeCache::get_file_cache`] so that all handles for one path share it. #[derive(Clone)] -pub struct FileByteRangeCache { +pub(crate) struct FileByteRangeCache { state: Arc>, total_num_stored_bytes: Arc, } @@ -198,7 +191,7 @@ pub struct FileByteRangeCache { impl FileByteRangeCache { fn with_total_num_stored_bytes(total_num_stored_bytes: Arc) -> Self { FileByteRangeCache { - state: Arc::new(Mutex::new(FileByteRangeCacheState::with_infinite_capacity())), + state: Arc::new(Mutex::new(FileByteRangeCacheState::default())), total_num_stored_bytes, } } @@ -240,36 +233,26 @@ impl FileByteRangeCache { /// once when opening a file, avoiding a path lookup and cross-file lock /// contention for each range read. /// -/// Contrary to `MemorySizedCache`, it's able to answer subset of known ranges, -/// does not have any eviction, and assumes an infinite capacity. +/// It answers arbitrary sub-ranges of cached slices without eviction, and has no built-in +/// capacity limit. /// /// This cache assume immutable data: if you put a new slice and it overlap with /// cached data, the changes may or may not get recorded. /// /// At the moment this is hardly a cache as it features no eviction policy. -#[derive(Clone)] -pub struct ByteRangeCache { +#[derive(Clone, Default)] +pub(crate) struct ByteRangeCache { inner_arc: Arc, } +#[derive(Default)] struct Inner { total_num_stored_bytes: Arc, // Paths identify virtual Tantivy files within this split, not storage object paths. - file_caches: Mutex>, + file_caches: Mutex>, } impl ByteRangeCache { - /// Creates a slice cache that never removes any entry. - pub fn with_infinite_capacity() -> Self { - let inner = Inner { - total_num_stored_bytes: Arc::new(AtomicU64::default()), - file_caches: Mutex::new(FxHashMap::default()), - }; - ByteRangeCache { - inner_arc: Arc::new(inner), - } - } - /// Returns the shared byte-range cache for `path`. pub fn get_file_cache(&self, path: &Path) -> FileByteRangeCache { let mut file_caches = self @@ -302,9 +285,9 @@ mod tests { use std::path::Path; use proptest::prelude::*; + use tantivy::directory::OwnedBytes; use super::ByteRangeCache; - use crate::OwnedBytes; #[derive(Debug)] enum Operation { @@ -355,7 +338,7 @@ mod tests { state.insert("path1", vec![false; 12]); state.insert("path2", vec![false; 12]); - let cache = ByteRangeCache::with_infinite_capacity(); + let cache = ByteRangeCache::default(); for op in ops { match op { @@ -419,7 +402,7 @@ mod tests { #[test] fn test_byte_range_cache_is_shared_for_same_path() { - let cache = ByteRangeCache::with_infinite_capacity(); + let cache = ByteRangeCache::default(); let first_file_cache = cache.get_file_cache(Path::new("path1")); let second_file_cache = cache.get_file_cache(Path::new("path1")); let other_file_cache = cache.get_file_cache(Path::new("path2")); @@ -433,7 +416,7 @@ mod tests { #[test] fn test_byte_range_cache_put_slice_returns_num_added_bytes() { - let cache = ByteRangeCache::with_infinite_capacity(); + let cache = ByteRangeCache::default(); let file_cache = cache.get_file_cache(Path::new("key")); let bytes = |range: Range| OwnedBytes::new(range.map(|i| i as u8).collect::>()); @@ -451,7 +434,7 @@ mod tests { #[test] fn test_byte_range_cache_doesnt_merge_unnecessarily() { - let cache = ByteRangeCache::with_infinite_capacity(); + let cache = ByteRangeCache::default(); let file_cache = cache.get_file_cache(Path::new("key")); file_cache.put_slice(0..5, OwnedBytes::new((0..5).collect::>())); diff --git a/quickwit/quickwit-directories/src/caching_directory.rs b/quickwit/quickwit-directories/src/caching_directory.rs deleted file mode 100644 index 078c03d13f3..00000000000 --- a/quickwit/quickwit-directories/src/caching_directory.rs +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::ops::Range; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::{fmt, io}; - -use async_trait::async_trait; -use futures::stream::BoxStream; -use quickwit_storage::{ByteRangeCache, FileByteRangeCache}; -use tantivy::directory::error::OpenReadError; -use tantivy::directory::{FileHandle, OwnedBytes}; -use tantivy::{Directory, HasLen}; - -/// Returned when reserving memory would go over the warmup memory limit of a split search. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct OutOfMemoryError; - -impl fmt::Display for OutOfMemoryError { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "out of warmup memory") - } -} - -impl std::error::Error for OutOfMemoryError {} - -impl From for io::Error { - fn from(out_of_memory_error: OutOfMemoryError) -> io::Error { - io::Error::new(io::ErrorKind::OutOfMemory, out_of_memory_error) - } -} - -/// Memory reserved for a read in progress. -/// -/// Released on drop, except the bytes passed to `keep` once the read bytes are in the cache. -/// So the memory is also released if the read fails, panics, or if its future is dropped. -#[must_use = "dropping a memory reservation releases its memory right away"] -pub struct MemoryReservation<'a> { - memory_reserver: &'a dyn MemoryReserver, - /// Bytes released on drop. - num_bytes: u64, -} - -impl<'a> MemoryReservation<'a> { - /// Creates a memory reservation that releases `num_bytes` on drop. - /// - /// Contract: only called by `memory_reserver`, from - /// [`MemoryReserver::reserve_memory`], for `num_bytes` it has just reserved. A reservation - /// created for bytes that were not reserved would release them anyway. - pub fn new(memory_reserver: &'a dyn MemoryReserver, num_bytes: u64) -> MemoryReservation<'a> { - MemoryReservation { - memory_reserver, - num_bytes, - } - } - - /// Keeps `num_kept_bytes` reserved and releases the rest. - pub fn keep(mut self, num_kept_bytes: u64) { - debug_assert!( - num_kept_bytes <= self.num_bytes, - "cannot keep more bytes than reserved" - ); - self.num_bytes = self.num_bytes.saturating_sub(num_kept_bytes); - } -} - -impl Drop for MemoryReservation<'_> { - fn drop(&mut self) { - if self.num_bytes > 0 { - self.memory_reserver.release_memory(self.num_bytes); - } - } -} - -/// Reserves memory for the data a [`CachingDirectory`] downloads and keeps in its cache. -/// -/// Only async reads reserve memory. Sync reads are only used by indexing, where the cache memory -/// is not accounted for. -#[async_trait] -pub trait MemoryReserver: Send + Sync + 'static { - /// Called on each cache miss of an async read, before reading `num_bytes` from the underlying - /// directory. May wait until the memory is available, but must fail right away if the memory - /// can never be available. - /// - /// On success, returns a [`MemoryReservation`], which gives the memory back through - /// `release_memory` when dropped, except for the bytes the read added to the cache. - /// - /// On error, the read fails with an `io::Error` of kind `OutOfMemory`: the underlying directory - /// is not called and nothing is cached. - /// - /// Contract: the memory is reserved before the read starts, so the caller must not hold - /// anything another read waits on. - async fn reserve_memory( - &self, - num_bytes: u64, - ) -> Result, OutOfMemoryError>; - - /// Gives back `num_bytes` reserved by `reserve_memory` that a read did not add to the cache: - /// the read failed, panicked, its future was dropped, or the bytes were already cached. - /// - /// Contract: `num_bytes` were reserved by an earlier `reserve_memory` call, and are not - /// released twice. Called from `Drop`, possibly while a panic unwinds, so it must not panic. - fn release_memory(&self, num_bytes: u64); -} - -/// A [`MemoryReserver`] that always succeeds. Used when the cache memory is not accounted for. -struct NoopMemoryReserver; - -#[async_trait] -impl MemoryReserver for NoopMemoryReserver { - async fn reserve_memory( - &self, - num_bytes: u64, - ) -> Result, OutOfMemoryError> { - Ok(MemoryReservation::new(self, num_bytes)) - } - - fn release_memory(&self, _num_bytes: u64) {} -} - -/// The caching directory is a simple cache that wraps another directory. -/// Streaming reads bypass cache lookups, insertion, and memory reservations. -#[derive(Clone)] -pub struct CachingDirectory { - underlying: Arc, - // TODO fixme: that's a pretty ugly cache we have here. - cache: ByteRangeCache, - memory_reserver: Arc, -} - -impl CachingDirectory { - /// Creates a new CachingDirectory. - /// - /// Warning: The resulting CacheDirectory will cache all information without ever - /// removing any item from the cache. - pub fn new_unbounded(underlying: Arc) -> CachingDirectory { - let byte_range_cache = ByteRangeCache::with_infinite_capacity(); - CachingDirectory::new(underlying, byte_range_cache) - } - - /// Creates a new CachingDirectory. - /// - /// Warning: The resulting CacheDirectory will cache all information without ever - /// removing any item from the cache. - pub fn new(underlying: Arc, cache: ByteRangeCache) -> CachingDirectory { - CachingDirectory { - underlying, - cache, - memory_reserver: Arc::new(NoopMemoryReserver), - } - } - - /// Reserves memory in `memory_reserver` before reading each cache miss of an async read. - /// - /// The directory holds `memory_reserver` until it is dropped. - pub fn with_memory_reserver( - mut self, - memory_reserver: Arc, - ) -> CachingDirectory { - self.memory_reserver = memory_reserver; - self - } -} - -impl fmt::Debug for CachingDirectory { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "CachingDirectory({:?})", self.underlying) - } -} - -struct CachingFileHandle { - path: PathBuf, - cache: FileByteRangeCache, - underlying_filehandle: Arc, - memory_reserver: Arc, -} - -impl fmt::Debug for CachingFileHandle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "CachingFileHandle(path={:?}, underlying={:?})", - self.path, - self.underlying_filehandle.as_ref() - ) - } -} - -#[async_trait] -impl FileHandle for CachingFileHandle { - /// Does not reserve memory: sync reads are only used by indexing. - fn read_bytes(&self, byte_range: Range) -> io::Result { - if let Some(bytes) = self.cache.get_slice(byte_range.clone()) { - return Ok(bytes); - } - let owned_bytes = self.underlying_filehandle.read_bytes(byte_range.clone())?; - self.cache.put_slice(byte_range, owned_bytes.clone()); - Ok(owned_bytes) - } - - async fn read_bytes_async(&self, byte_range: Range) -> io::Result { - if let Some(owned_bytes) = self.cache.get_slice(byte_range.clone()) { - return Ok(owned_bytes); - } - let read_reservation = self - .memory_reserver - .reserve_memory(byte_range.len() as u64) - .await?; - let read_bytes = self - .underlying_filehandle - .read_bytes_async(byte_range.clone()) - .await?; - let num_added_bytes = self.cache.put_slice(byte_range, read_bytes.clone()); - read_reservation.keep(num_added_bytes); - Ok(read_bytes) - } - - fn stream_ranges( - &self, - ranges: Box> + Send>, - ) -> BoxStream<'_, io::Result> { - self.underlying_filehandle.stream_ranges(ranges) - } -} - -impl HasLen for CachingFileHandle { - fn len(&self) -> usize { - self.underlying_filehandle.len() - } -} - -impl Directory for CachingDirectory { - fn exists(&self, path: &Path) -> std::result::Result { - self.underlying.exists(path) - } - - fn get_file_handle( - &self, - path: &Path, - ) -> std::result::Result, OpenReadError> { - let underlying_filehandle = self.underlying.get_file_handle(path)?; - let caching_file_handle = CachingFileHandle { - path: path.to_path_buf(), - cache: self.cache.get_file_cache(path), - underlying_filehandle, - memory_reserver: self.memory_reserver.clone(), - }; - Ok(Arc::new(caching_file_handle)) - } - - fn atomic_read(&self, path: &Path) -> std::result::Result, OpenReadError> { - let file_handle = self.get_file_handle(path)?; - let len = file_handle.len(); - let owned_bytes = file_handle - .read_bytes(0..len) - .map_err(|io_error| OpenReadError::wrap_io_error(io_error, path.to_path_buf()))?; - Ok(owned_bytes.as_slice().to_vec()) - } - - crate::read_only_directory!(); -} - -#[cfg(test)] -mod tests { - - use std::io; - use std::ops::Range; - use std::path::Path; - use std::sync::Arc; - use std::sync::atomic::{AtomicU64, Ordering}; - use std::time::Duration; - - use async_trait::async_trait; - use quickwit_storage::ByteRangeCache; - use tantivy::directory::{FileHandle, OwnedBytes, RamDirectory}; - use tantivy::{Directory, HasLen}; - - use super::{CachingDirectory, CachingFileHandle, MemoryReserver, OutOfMemoryError}; - use crate::{DebugProxyDirectory, MemoryReservation}; - - /// Reserves memory up to `limit` bytes. - struct LimitedMemoryReserver { - limit: u64, - reserved: AtomicU64, - } - - impl LimitedMemoryReserver { - fn new(limit: u64) -> Arc { - Arc::new(LimitedMemoryReserver { - limit, - reserved: AtomicU64::new(0), - }) - } - - fn reserved(&self) -> u64 { - self.reserved.load(Ordering::Relaxed) - } - } - - #[async_trait] - impl MemoryReserver for LimitedMemoryReserver { - async fn reserve_memory( - &self, - num_bytes: u64, - ) -> Result, OutOfMemoryError> { - self.reserved - .try_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| { - let new_reserved = reserved + num_bytes; - (new_reserved <= self.limit).then_some(new_reserved) - }) - .map_err(|_| OutOfMemoryError)?; - Ok(MemoryReservation::new(self, num_bytes)) - } - - fn release_memory(&self, num_bytes: u64) { - self.reserved.fetch_sub(num_bytes, Ordering::Relaxed); - } - } - - /// How the reads of a [`FailingFileHandle`] fail. - #[derive(Debug, Clone, Copy)] - enum ReadFailure { - Error, - Panic, - /// The async read never completes. The sync read fails with an error. - Pending, - } - - /// A file handle whose reads never succeed. - #[derive(Debug)] - struct FailingFileHandle(ReadFailure); - - impl HasLen for FailingFileHandle { - fn len(&self) -> usize { - 100 - } - } - - #[async_trait] - impl FileHandle for FailingFileHandle { - fn read_bytes(&self, _byte_range: Range) -> io::Result { - match self.0 { - ReadFailure::Error | ReadFailure::Pending => Err(io::Error::other("read failed")), - ReadFailure::Panic => panic!("read panicked"), - } - } - - async fn read_bytes_async(&self, byte_range: Range) -> io::Result { - if let ReadFailure::Pending = self.0 { - std::future::pending::<()>().await; - } - self.read_bytes(byte_range) - } - } - - fn failing_caching_file_handle( - read_failure: ReadFailure, - memory_reserver: Arc, - ) -> CachingFileHandle { - let path = Path::new("test"); - CachingFileHandle { - path: path.to_path_buf(), - cache: ByteRangeCache::with_infinite_capacity().get_file_cache(path), - underlying_filehandle: Arc::new(FailingFileHandle(read_failure)), - memory_reserver, - } - } - - #[tokio::test] - async fn test_caching_file_handle_releases_memory_on_async_read_panic() { - let memory_reserver = LimitedMemoryReserver::new(100); - let file_handle = Arc::new(failing_caching_file_handle( - ReadFailure::Panic, - memory_reserver.clone(), - )); - let join_res = tokio::spawn(async move { file_handle.read_bytes_async(0..5).await }).await; - assert!(join_res.unwrap_err().is_panic()); - assert_eq!(memory_reserver.reserved(), 0); - } - - #[tokio::test] - async fn test_caching_file_handle_releases_memory_when_read_future_is_dropped() { - let memory_reserver = LimitedMemoryReserver::new(100); - let file_handle = - failing_caching_file_handle(ReadFailure::Pending, memory_reserver.clone()); - let read_future = file_handle.read_bytes_async(0..5); - let timeout_res = tokio::time::timeout(Duration::from_millis(10), read_future).await; - assert!(timeout_res.is_err()); - // The timeout dropped the read future. - assert_eq!(memory_reserver.reserved(), 0); - } - - #[tokio::test] - async fn test_caching_file_handle_releases_memory_on_async_read_error() { - let memory_reserver = LimitedMemoryReserver::new(100); - let file_handle = failing_caching_file_handle(ReadFailure::Error, memory_reserver.clone()); - assert!(file_handle.read_bytes_async(0..5).await.is_err()); - assert_eq!(memory_reserver.reserved(), 0); - } - - fn debug_proxy_directory_with_file( - path: &Path, - content: &[u8], - ) -> Arc> { - let ram_directory = RamDirectory::default(); - ram_directory.atomic_write(path, content).unwrap(); - Arc::new(DebugProxyDirectory::wrap(ram_directory)) - } - - #[test] - fn test_caching_directory() -> tantivy::Result<()> { - let ram_directory = RamDirectory::default(); - let test_path = Path::new("test"); - ram_directory.atomic_write(test_path, &b"test"[..])?; - let debug_proxy_directory = Arc::new(DebugProxyDirectory::wrap(ram_directory)); - let caching_directory = CachingDirectory::new_unbounded(debug_proxy_directory.clone()); - caching_directory.atomic_read(test_path)?; - caching_directory.atomic_read(test_path)?; - assert_eq!(debug_proxy_directory.drain_read_operations().count(), 1); - Ok(()) - } - - #[test] - fn test_caching_directory_sync_read_does_not_reserve_memory() { - let test_path = Path::new("test"); - let debug_proxy_directory = debug_proxy_directory_with_file(test_path, b"hello world"); - let memory_reserver = LimitedMemoryReserver::new(4); - let caching_directory = CachingDirectory::new_unbounded(debug_proxy_directory.clone()) - .with_memory_reserver(memory_reserver.clone()); - let file_handle = caching_directory.get_file_handle(test_path).unwrap(); - - // Would go over the limit of the memory reserver if it was accounted for. - file_handle.read_bytes(0..5).unwrap(); - file_handle.read_bytes(0..5).unwrap(); - assert_eq!(memory_reserver.reserved(), 0); - assert_eq!(debug_proxy_directory.drain_read_operations().count(), 1); - } - - #[tokio::test] - async fn test_caching_directory_reserves_overlapping_bytes_once() { - let test_path = Path::new("test"); - let debug_proxy_directory = debug_proxy_directory_with_file(test_path, b"hello world"); - let memory_reserver = LimitedMemoryReserver::new(100); - let byte_range_cache = ByteRangeCache::with_infinite_capacity(); - let caching_directory = - CachingDirectory::new(debug_proxy_directory.clone(), byte_range_cache.clone()) - .with_memory_reserver(memory_reserver.clone()); - let file_handle = caching_directory.get_file_handle(test_path).unwrap(); - - file_handle.read_bytes_async(0..5).await.unwrap(); - // A cache miss: 3..5 is cached, but not 5..8. Only 5..8 stays reserved. - file_handle.read_bytes_async(3..8).await.unwrap(); - assert_eq!(debug_proxy_directory.drain_read_operations().count(), 2); - assert_eq!(byte_range_cache.get_num_bytes(), 8); - assert_eq!(memory_reserver.reserved(), 8); - } - - #[tokio::test] - async fn test_caching_directory_reserves_memory_on_async_cache_miss() { - let test_path = Path::new("test"); - let debug_proxy_directory = debug_proxy_directory_with_file(test_path, b"hello world"); - let memory_reserver = LimitedMemoryReserver::new(100); - let caching_directory = CachingDirectory::new_unbounded(debug_proxy_directory.clone()) - .with_memory_reserver(memory_reserver.clone()); - let file_handle = caching_directory.get_file_handle(test_path).unwrap(); - - file_handle.read_bytes_async(0..5).await.unwrap(); - assert_eq!(memory_reserver.reserved(), 5); - file_handle.read_bytes_async(0..5).await.unwrap(); - assert_eq!(memory_reserver.reserved(), 5); - assert_eq!(debug_proxy_directory.drain_read_operations().count(), 1); - } - - #[tokio::test] - async fn test_automaton_bitset_bypasses_directory_cache_and_memory_budget() - -> tantivy::Result<()> { - use tantivy::schema::{STRING, Schema}; - use tantivy::{Index, IndexWriter, doc}; - use tantivy_fst::Regex; - use tantivy_fst::automaton::AlwaysMatch; - - let directory = RamDirectory::create(); - let mut schema = Schema::builder(); - let field = schema.add_text_field("field", STRING); - let index = Index::create(directory.clone(), schema.build(), Default::default())?; - let mut writer: IndexWriter = index.writer_with_num_threads(1, 15_000_000)?; - for value in ["a", "m", "z"] { - writer.add_document(doc!(field => value))?; - } - writer.commit()?; - - let cache = ByteRangeCache::with_infinite_capacity(); - let budget_bytes = 32 * 1024 * 1024; - let reserver = LimitedMemoryReserver::new(budget_bytes); - let directory = DebugProxyDirectory::wrap( - CachingDirectory::new(Arc::new(directory), cache.clone()) - .with_memory_reserver(reserver.clone()), - ); - let index = Index::open(directory.clone())?; - let searcher = index.reader()?.searcher(); - let segment = searcher.segment_reader(0); - let inverted_index = segment.inverted_index(field)?; - // Opening the index caches metadata. Exhaust remaining budget before streaming reads. - let _ = directory.drain_read_operations(); - let initial_cached_bytes = cache.get_num_bytes(); - let _reservation = reserver - .reserve_memory(budget_bytes - reserver.reserved()) - .await - .unwrap(); - let subset_bitset = inverted_index - .create_bitset_for_automaton( - Regex::new("a|z").unwrap(), - segment.max_doc(), - |task| async move { task() }, - ) - .await?; - assert!(subset_bitset.len() == 2 && subset_bitset.contains(0) && subset_bitset.contains(2)); - let all_docs_bitset = - inverted_index - .create_bitset_for_automaton(AlwaysMatch, segment.max_doc(), |task| async move { - task() - }) - .await?; - assert_eq!(all_docs_bitset.len(), 3); - assert_eq!(cache.get_num_bytes(), initial_cached_bytes); - assert_eq!(directory.drain_read_operations().count(), 0); - Ok(()) - } - - #[tokio::test] - async fn test_caching_directory_memory_reservation_failure() { - let test_path = Path::new("test"); - let debug_proxy_directory = debug_proxy_directory_with_file(test_path, b"hello world"); - let memory_reserver = LimitedMemoryReserver::new(4); - let caching_directory = CachingDirectory::new_unbounded(debug_proxy_directory.clone()) - .with_memory_reserver(memory_reserver.clone()); - let file_handle = caching_directory.get_file_handle(test_path).unwrap(); - - let io_error = file_handle.read_bytes_async(0..5).await.unwrap_err(); - assert_eq!(io_error.kind(), io::ErrorKind::OutOfMemory); - assert_eq!(io_error.to_string(), "out of warmup memory"); - // The underlying directory is never called and nothing is cached. - assert_eq!(debug_proxy_directory.drain_read_operations().count(), 0); - assert_eq!(memory_reserver.reserved(), 0); - } -} diff --git a/quickwit/quickwit-directories/src/debug_proxy_directory.rs b/quickwit/quickwit-directories/src/debug_proxy_directory.rs deleted file mode 100644 index ba1d48d8d69..00000000000 --- a/quickwit/quickwit-directories/src/debug_proxy_directory.rs +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::ops::Range; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; -use std::{fmt, io, mem}; - -use async_trait::async_trait; -use futures::stream::BoxStream; -use tantivy::directory::error::OpenReadError; -use tantivy::directory::{FileHandle, OwnedBytes}; -use tantivy::{Directory, HasLen}; -use time::OffsetDateTime; - -#[derive(Clone, Default)] -struct OperationBuffer(Arc>>); - -impl fmt::Debug for OperationBuffer { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "OperationBuffer") - } -} - -impl OperationBuffer { - fn drain(&self) -> impl Iterator + 'static { - let mut guard = self.0.lock().expect("Mutex poisoned"); - let ops: Vec = mem::take(guard.as_mut()); - ops.into_iter() - } - - fn push(&self, read_operation: ReadOperation) { - let mut guard = self.0.lock().expect("Mutex poisoned"); - guard.push(read_operation); - } -} - -/// A ReadOperation records meta data about a read operation. -/// It is recorded by the `DebugProxyDirectory`. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct ReadOperation { - /// Path that was read - pub path: PathBuf, - /// If fetching a range of data, the start offset, else 0. - pub offset: usize, - /// The number of bytes fetched - pub num_bytes: usize, - /// The date at which the operation was performed (UTC timezone). - pub start_date: OffsetDateTime, - /// The elapsed time to run the read operatioon. - pub duration: Duration, -} - -struct ReadOperationBuilder { - start_date: OffsetDateTime, - start_instant: Instant, - path: PathBuf, - offset: usize, -} - -impl ReadOperationBuilder { - pub fn new(path: &Path) -> Self { - let start_instant = Instant::now(); - let start_date = OffsetDateTime::now_utc(); - ReadOperationBuilder { - start_date, - start_instant, - path: path.to_path_buf(), - offset: 0, - } - } - - pub fn with_offset(self, offset: usize) -> Self { - ReadOperationBuilder { - start_date: self.start_date, - start_instant: self.start_instant, - path: self.path, - offset, - } - } - - fn terminate(self, num_bytes: usize) -> ReadOperation { - let duration = self.start_instant.elapsed(); - ReadOperation { - path: self.path.clone(), - offset: self.offset, - num_bytes, - start_date: self.start_date, - duration, - } - } -} - -/// The debug proxy wraps another directory and simply acts as a proxy -/// recording its buffered read operations. Streaming reads pass through without recording. -/// -/// It has two purpose -/// - It is used when building our hotcache, to identify the file sections that should be in the -/// hotcache. -/// - It is used in the search-api to provide debugging/performance information. -#[derive(Debug)] -pub struct DebugProxyDirectory { - underlying: Arc, - operations: OperationBuffer, -} - -impl Clone for DebugProxyDirectory { - fn clone(&self) -> Self { - DebugProxyDirectory { - underlying: self.underlying.clone(), - operations: self.operations.clone(), - } - } -} - -impl DebugProxyDirectory { - /// Wraps another directory to log its buffered read operations. - pub fn wrap(directory: D) -> Self { - DebugProxyDirectory { - underlying: Arc::new(directory), - operations: OperationBuffer::default(), - } - } - - /// Returns all of the existing read operations. - /// - /// Calling this "drains" the existing queue of operations. - pub fn drain_read_operations(&self) -> impl Iterator + '_ { - self.operations.drain() - } - - /// Adds a new operation - fn register(&self, read_op: ReadOperation) { - self.operations.push(read_op); - } - - /// Adds a new operation in an async fashion. - async fn register_async(&self, read_op: ReadOperation) { - self.operations.push(read_op); - } -} - -struct DebugProxyFileHandle { - directory: DebugProxyDirectory, - underlying: Arc, - path: PathBuf, -} - -#[async_trait] -impl FileHandle for DebugProxyFileHandle { - fn read_bytes(&self, byte_range: Range) -> io::Result { - let read_operation_builder = - ReadOperationBuilder::new(&self.path).with_offset(byte_range.start); - let payload = self.underlying.read_bytes(byte_range)?; - let read_operation = read_operation_builder.terminate(payload.len()); - self.directory.register(read_operation); - Ok(payload) - } - - async fn read_bytes_async(&self, byte_range: Range) -> io::Result { - let read_operation_builder = - ReadOperationBuilder::new(&self.path).with_offset(byte_range.start); - let payload = self.underlying.read_bytes_async(byte_range).await?; - let read_operation = read_operation_builder.terminate(payload.len()); - self.directory.register_async(read_operation).await; - Ok(payload) - } - - fn stream_ranges( - &self, - ranges: Box> + Send>, - ) -> BoxStream<'_, io::Result> { - self.underlying.stream_ranges(ranges) - } -} - -impl fmt::Debug for DebugProxyFileHandle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "DebugProxyFileHandle({:?})", self.underlying) - } -} - -impl HasLen for DebugProxyFileHandle { - fn len(&self) -> usize { - self.underlying.len() - } -} - -impl Directory for DebugProxyDirectory { - fn get_file_handle(&self, path: &Path) -> Result, OpenReadError> { - let underlying = self.underlying.get_file_handle(path)?; - Ok(Arc::new(DebugProxyFileHandle { - underlying, - directory: self.clone(), - path: path.to_owned(), - })) - } - - fn exists(&self, path: &Path) -> Result { - self.underlying.exists(path) - } - - fn atomic_read(&self, path: &Path) -> Result, OpenReadError> { - let read_operation_builder = ReadOperationBuilder::new(path); - let payload = self.underlying.atomic_read(path)?; - let read_operation = read_operation_builder.terminate(payload.len()); - self.register(read_operation); - Ok(payload.to_vec()) - } - - crate::read_only_directory!(); -} - -#[cfg(test)] -mod tests { - use std::io::Write; - use std::path::Path; - - use tantivy::Directory; - use tantivy::directory::{RamDirectory, TerminatingWrite}; - - use super::DebugProxyDirectory; - - const TEST_PATH: &str = "test.file"; - const TEST_PAYLOAD: &[u8] = b"hello happy tax payer"; - - fn make_test_directory() -> tantivy::Result { - let ram_directory = RamDirectory::create(); - let mut wrt = ram_directory.open_write(Path::new(TEST_PATH))?; - wrt.write_all(TEST_PAYLOAD)?; - wrt.flush()?; - wrt.terminate()?; - Ok(ram_directory) - } - - #[test] - fn test_debug_proxy_atomic_read() -> tantivy::Result<()> { - let debug_proxy = DebugProxyDirectory::wrap(make_test_directory()?); - let test_path = Path::new(TEST_PATH); - let read_data = debug_proxy.atomic_read(test_path)?; - assert_eq!(&read_data[..], TEST_PAYLOAD); - let operations: Vec = debug_proxy.drain_read_operations().collect(); - println!("operations {operations:?}"); - assert_eq!(operations.len(), 1); - let op0 = &operations[0]; - assert_eq!(op0.offset, 0); - assert_eq!(op0.num_bytes, 21); - assert_eq!(op0.path, test_path); - Ok(()) - } - - #[test] - fn test_debug_proxy_open_read_read_sync() -> tantivy::Result<()> { - let test_path = Path::new(TEST_PATH); - let debug_proxy = DebugProxyDirectory::wrap(make_test_directory()?); - let read_data = debug_proxy.open_read(test_path)?; - assert_eq!(read_data.read_bytes_slice(1..3)?.as_slice(), b"el"); - let operations: Vec = debug_proxy.drain_read_operations().collect(); - assert_eq!(operations.len(), 1); - let op = &operations[0]; - assert_eq!(op.path, test_path); - assert_eq!(op.offset, 1); - assert_eq!(op.num_bytes, 2); - Ok(()) - } - - #[tokio::test] - async fn test_debug_proxy_open_read_read_async() { - let test_path = Path::new(TEST_PATH); - let debug_proxy = DebugProxyDirectory::wrap(make_test_directory().unwrap()); - let read_data = debug_proxy.open_read(test_path).unwrap(); - assert_eq!( - read_data - .read_bytes_slice_async(1..3) - .await - .unwrap() - .as_slice(), - b"el" - ); - let operations: Vec = debug_proxy.drain_read_operations().collect(); - assert_eq!(operations.len(), 1); - let op = &operations[0]; - assert_eq!(op.path, test_path); - assert_eq!(op.offset, 1); - assert_eq!(op.num_bytes, 2); - } -} diff --git a/quickwit/quickwit-directories/src/hot_directory.rs b/quickwit/quickwit-directories/src/hotcache.rs similarity index 60% rename from quickwit/quickwit-directories/src/hot_directory.rs rename to quickwit/quickwit-directories/src/hotcache.rs index 1691462f516..1ddf9ecb295 100644 --- a/quickwit/quickwit-directories/src/hot_directory.rs +++ b/quickwit/quickwit-directories/src/hotcache.rs @@ -15,31 +15,30 @@ use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::{fmt, io}; use anyhow::{Context, bail}; use async_trait::async_trait; -use futures::stream::BoxStream; use quickwit_storage::VersionedComponent; use serde::{Deserialize, Serialize}; use tantivy::directory::error::OpenReadError; -use tantivy::directory::{FileHandle, FileSlice, OwnedBytes}; +use tantivy::directory::{FileHandle, OwnedBytes}; use tantivy::error::DataCorruption; use tantivy::{Directory, HasLen, Index, IndexReader, ReloadPolicy, TantivyError}; -use crate::{CachingDirectory, DebugProxyDirectory}; +use crate::byte_range_cache::{ByteRangeCache, FileByteRangeCache}; #[derive(Clone, Copy, Default)] #[repr(u32)] -pub enum HotDirectoryVersions { +pub(crate) enum HotcacheVersions { #[default] V1 = 1, } -impl VersionedComponent for HotDirectoryVersions { +impl VersionedComponent for HotcacheVersions { const MAGIC_NUMBER: u32 = 2_557_869_106u32; - type Component = HotDirectoryMeta; + type Component = HotcacheMeta; fn to_version_code(self) -> u32 { self as u32 @@ -52,17 +51,17 @@ impl VersionedComponent for HotDirectoryVersions { } } - fn deserialize_impl(&self, bytes: &mut OwnedBytes) -> anyhow::Result { + fn deserialize_impl(&self, bytes: &mut OwnedBytes) -> anyhow::Result { match self { Self::V1 => { if bytes.len() < 4 { bail!("data too short (len={})", bytes.len()); } let len = bytes.read_u32() as usize; - let hot_directory_meta = postcard::from_bytes(&bytes.as_slice()[..len]) - .context("failed to deserialize hot directory meta")?; + let hotcache_meta = postcard::from_bytes(&bytes.as_slice()[..len]) + .context("failed to deserialize hotcache meta")?; bytes.advance(len); - Ok(hot_directory_meta) + Ok(hotcache_meta) } } } @@ -75,7 +74,7 @@ impl VersionedComponent for HotDirectoryVersions { } #[derive(Serialize, Deserialize)] -pub struct HotDirectoryMeta { +pub(crate) struct HotcacheMeta { file_lengths: HashMap, slice_offsets: Vec<(PathBuf, u64)>, } @@ -88,28 +87,18 @@ struct SliceCacheIndexEntry { } impl SliceCacheIndexEntry { - pub fn len(&self) -> usize { - self.range().len() - } - pub fn range(&self) -> Range { self.start..self.stop } } #[derive(Serialize, Deserialize, Default)] -pub struct SliceCacheIndex { +struct SliceCacheIndex { total_len: u64, slices: Vec, } -impl SliceCacheIndex { - pub fn is_complete(&self) -> bool { - if self.slices.len() != 1 { - return false; - } - self.slices[0].len() as u64 == self.total_len - } +impl SliceCacheIndex { pub fn get(&self, byte_range: Range) -> Option { let entry_idx = match self .slices @@ -154,11 +143,11 @@ impl StaticDirectoryCacheBuilder { offset += buf.len() as u64; data_buffer.extend_from_slice(&buf); } - let hot_directory_metas = HotDirectoryMeta { + let hotcache_meta = HotcacheMeta { file_lengths: self.file_lengths, slice_offsets: data_idx, }; - let buffer = HotDirectoryVersions::serialize(&hot_directory_metas); + let buffer = HotcacheVersions::serialize(&hotcache_meta); wrt.write_all(&buffer)?; wrt.write_all(&data_buffer)?; Ok(()) @@ -166,17 +155,17 @@ impl StaticDirectoryCacheBuilder { } #[derive(Debug)] -struct StaticDirectoryCache { +pub(crate) struct StaticDirectoryCache { file_lengths: HashMap, slices: HashMap>, } impl StaticDirectoryCache { pub fn open(mut bytes: OwnedBytes) -> anyhow::Result { - let HotDirectoryMeta { + let HotcacheMeta { mut slice_offsets, file_lengths, - } = HotDirectoryVersions::try_read_component(&mut bytes)?; + } = HotcacheVersions::try_read_component(&mut bytes)?; slice_offsets.push((PathBuf::default(), bytes.len() as u64)); let slices = slice_offsets .windows(2) @@ -212,15 +201,15 @@ impl StaticDirectoryCache { } } -/// A SliceCache is a static toring -pub struct StaticSliceCache { +/// Static slice cache for a single file inside a split hotcache. +pub(crate) struct StaticSliceCache { bytes: OwnedBytes, index: SliceCacheIndex, } impl Default for StaticSliceCache { - fn default() -> StaticSliceCache { - StaticSliceCache { + fn default() -> Self { + Self { bytes: OwnedBytes::empty(), index: SliceCacheIndex::default(), } @@ -243,13 +232,6 @@ impl StaticSliceCache { Ok(StaticSliceCache { bytes: body, index }) } - pub fn try_read_all(&self) -> Option { - if !self.index.is_complete() { - return None; - } - Some(self.bytes.clone()) - } - pub fn try_read_bytes(&self, byte_range: Range) -> Option { if byte_range.is_empty() { return Some(OwnedBytes::empty()); @@ -261,6 +243,12 @@ impl StaticSliceCache { } } +impl fmt::Debug for StaticSliceCache { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "StaticSliceCache()") + } +} + struct StaticSliceCacheBuilder { wrt: Vec, slices: Vec, @@ -306,7 +294,6 @@ impl StaticSliceCacheBuilder { if last.stop == segment.range().start && (last.addr + last.range().len() == segment.addr) { - // We merge the current segment with the previous one last.stop += segment.range().len(); } else { slices.push(last); @@ -333,142 +320,90 @@ impl StaticSliceCacheBuilder { } } -impl fmt::Debug for StaticSliceCache { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "SliceCache()") - } -} - -/// The hot directory accelerates a given directory, -/// by placing a static cache in front of a directory. -/// -/// The `HotDirectory` does not implement write operations. It has been -/// designed for quickwit in order to regroup all of the small random -/// read operations required to open an index. -/// All of these operations are gather into a single file called the -/// hotcache. +/// Private recording and caching wrapper used by [`write_hotcache`] so that the recorded byte +/// ranges and the bytes written into the hotcache come from the same index-opening pass. #[derive(Clone)] -pub struct HotDirectory { - inner: Arc, +struct HotcacheRecorder { + underlying: Arc, + cache: ByteRangeCache, + recorded_ranges: Arc>>>>, } -impl HotDirectory { - /// Wraps an index, with a static cache serialized into `hot_cache_bytes`. - pub fn open( - underlying: D, - hot_cache_bytes: OwnedBytes, - ) -> anyhow::Result { - let static_cache = StaticDirectoryCache::open(hot_cache_bytes)?; - Ok(HotDirectory { - inner: Arc::new(InnerHotDirectory { - underlying: Box::new(underlying), - cache: Arc::new(static_cache), - }), - }) - } - - /// Get all the files in the directory and their sizes. - /// - /// The actual cached data is a very small fraction of this length. - pub fn get_file_lengths(&self) -> Vec<(PathBuf, u64)> { - self.inner.cache.get_file_lengths() - } - - /// Sum of the file lengths, the doc store files excluded. - pub fn num_bytes_without_doc_store(&self) -> u64 { - self.get_file_lengths() - .iter() - .filter(|(path, _)| !path.to_string_lossy().ends_with("store")) - .map(|(_, file_length)| *file_length) - .sum() +impl HotcacheRecorder { + fn drain_recorded_ranges(&self) -> HashMap>> { + std::mem::take(&mut self.recorded_ranges.lock().unwrap()) } } -struct FileSliceWithCache { - underlying: FileSlice, - static_cache: Arc, - file_length: u64, -} - -#[async_trait] -impl FileHandle for FileSliceWithCache { - fn read_bytes(&self, byte_range: Range) -> io::Result { - if let Some(found_bytes) = self.static_cache.try_read_bytes(byte_range.clone()) { - return Ok(found_bytes); - } - self.underlying.read_bytes_slice(byte_range) - } - - async fn read_bytes_async(&self, byte_range: Range) -> io::Result { - if let Some(found_bytes) = self.static_cache.try_read_bytes(byte_range.clone()) { - return Ok(found_bytes); - } - self.underlying.read_bytes_slice_async(byte_range).await +impl fmt::Debug for HotcacheRecorder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "HotcacheRecorder({:?})", self.underlying) } +} - fn stream_ranges( - &self, - ranges: Box> + Send>, - ) -> BoxStream<'_, io::Result> { - self.underlying.stream_ranges(ranges) - } +struct HotcacheFileHandle { + path: PathBuf, + underlying: Arc, + cache: FileByteRangeCache, + recorded_ranges: Arc>>>>, } -impl fmt::Debug for FileSliceWithCache { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "FileSliceWithCache({:?})", self.underlying) +impl fmt::Debug for HotcacheFileHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "HotcacheFileHandle({:?})", self.underlying) } } -impl HasLen for FileSliceWithCache { +impl HasLen for HotcacheFileHandle { fn len(&self) -> usize { - self.file_length as usize + self.underlying.len() } } -struct InnerHotDirectory { - underlying: Box, - cache: Arc, -} - -impl fmt::Debug for HotDirectory { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "HotDirectory(dir={:?}, cache={:?})", - self.inner.underlying.as_ref(), - self.inner.cache.as_ref() - ) +#[async_trait] +impl FileHandle for HotcacheFileHandle { + fn read_bytes(&self, byte_range: Range) -> io::Result { + let owned_bytes = if let Some(bytes) = self.cache.get_slice(byte_range.clone()) { + bytes + } else { + let owned_bytes = self.underlying.read_bytes(byte_range.clone())?; + self.cache + .put_slice(byte_range.clone(), owned_bytes.clone()); + owned_bytes + }; + let recorded_range = byte_range.start..byte_range.start + owned_bytes.len(); + self.recorded_ranges + .lock() + .unwrap() + .entry(self.path.clone()) + .or_default() + .insert(recorded_range); + Ok(owned_bytes) } } -impl Directory for HotDirectory { +impl Directory for HotcacheRecorder { fn get_file_handle(&self, path: &Path) -> Result, OpenReadError> { - let file_length = self - .inner - .cache - .get_file_length(path) - .ok_or_else(|| OpenReadError::FileDoesNotExist(path.to_owned()))?; - let underlying_filehandle = self.inner.underlying.get_file_handle(path)?; - let underlying = FileSlice::new_with_num_bytes(underlying_filehandle, file_length as usize); - let file_slice_with_cache = FileSliceWithCache { + let underlying = self.underlying.get_file_handle(path)?; + Ok(Arc::new(HotcacheFileHandle { + path: path.to_path_buf(), underlying, - static_cache: self.inner.cache.get_slice(path), - file_length, - }; - Ok(Arc::new(file_slice_with_cache)) + cache: self.cache.get_file_cache(path), + recorded_ranges: self.recorded_ranges.clone(), + })) } - fn exists(&self, path: &std::path::Path) -> Result { - Ok(self.inner.cache.get_file_length(path).is_some()) + fn exists(&self, path: &Path) -> Result { + self.underlying.exists(path) } - fn atomic_read(&self, path: &std::path::Path) -> Result, OpenReadError> { - let slice_cache = self.inner.cache.get_slice(path); - if let Some(all_bytes) = slice_cache.try_read_all() { - return Ok(all_bytes.as_slice().to_owned()); - } - self.inner.underlying.atomic_read(path) + fn atomic_read(&self, path: &Path) -> Result, OpenReadError> { + let file_handle = self.get_file_handle(path)?; + let len = file_handle.len(); + let owned_bytes = file_handle + .read_bytes(0..len) + .map_err(|io_error| OpenReadError::wrap_io_error(io_error, path.to_path_buf()))?; + Ok(owned_bytes.as_slice().to_vec()) } crate::read_only_directory!(); @@ -482,20 +417,20 @@ fn list_index_files(index: &Index) -> tantivy::Result> { Ok(files) } -/// Given a tantivy directory, automatically identify the parts that should be loaded on startup -/// and writes a static cache file called hotcache in the `output`. -/// -/// See [`HotDirectory`] for more information. +/// Given a tantivy directory, automatically identifies the byte ranges read on startup +/// and writes a static hotcache into `output`. pub fn write_hotcache( directory: D, output: &mut dyn io::Write, ) -> tantivy::Result<()> { - // We use the caching directory here in order to defensively ensure that - // the content of the directory that will be written in the hotcache is precisely - // the same that was read on the first pass. - let caching_directory = CachingDirectory::new_unbounded(Arc::new(directory)); - let debug_proxy_directory = DebugProxyDirectory::wrap(caching_directory); - let index = Index::open(debug_proxy_directory.clone())?; + // Record read ranges and cache their bytes defensively so the bytes written into the hotcache + // are identical to those read during the index-opening pass. + let recorder = HotcacheRecorder { + underlying: Arc::new(directory), + cache: ByteRangeCache::default(), + recorded_ranges: Arc::new(Mutex::new(HashMap::default())), + }; + let index = Index::open(recorder.clone())?; let schema = index.schema(); let reader: IndexReader = index .reader_builder() @@ -511,18 +446,11 @@ pub fn write_hotcache( } } let mut cache_builder = StaticDirectoryCacheBuilder::default(); - let read_operations = debug_proxy_directory.drain_read_operations(); - let mut per_file_slices: HashMap>> = HashMap::default(); - for read_operation in read_operations { - per_file_slices - .entry(read_operation.path) - .or_default() - .insert(read_operation.offset..read_operation.offset + read_operation.num_bytes); - } + let per_file_slices = recorder.drain_recorded_ranges(); let index_files = list_index_files(&index)?; for file_path in index_files { - let file_slice_res = debug_proxy_directory.open_read(&file_path); - if let Err(tantivy::directory::error::OpenReadError::FileDoesNotExist(_)) = file_slice_res { + let file_slice_res = recorder.open_read(&file_path); + if let Err(OpenReadError::FileDoesNotExist(_)) = file_slice_res { continue; } let file_slice = file_slice_res?; @@ -530,12 +458,10 @@ pub fn write_hotcache( if let Some(intervals) = per_file_slices.get(&file_path) { for byte_range in intervals { let len = byte_range.len(); - // We do not want to store slices that are too large in the hotcache, - // but on the other hand, the term dictionray index and the docstore - // index are required for quickwit to work. + // Do not store overly large slices in the hotcache, except for the term + // dictionary index and docstore index which Quickwit requires. // - // Warning: we need to work on string here because `Path::ends_with` - // has very different semantics. + // Warning: work on string because `Path::ends_with` matches path components. let file_path_str = file_path.to_string_lossy(); if file_path_str.ends_with("store") || file_path_str.ends_with("term") @@ -553,14 +479,18 @@ pub fn write_hotcache( } #[cfg(test)] -mod tests { - use rand::RngExt; - use tantivy::directory::RamDirectory; - use tantivy::schema::{ - BytesOptions, FieldEntry, Schema, TextFieldIndexing, TextOptions, Value, - }; - use tantivy::{Index, TantivyDocument}; +pub(crate) fn empty_hotcache_for_files(files: &[(PathBuf, u64)]) -> Vec { + let mut builder = StaticDirectoryCacheBuilder::default(); + for (path, len) in files { + builder.add_file(path, *len); + } + let mut output = Vec::new(); + builder.write(&mut output).unwrap(); + output +} +#[cfg(test)] +mod tests { use super::*; #[test] @@ -678,7 +608,7 @@ mod tests { #[test] fn test_slice_entry_serialization() -> anyhow::Result<()> { - let slice_entry = super::SliceCacheIndexEntry { + let slice_entry = SliceCacheIndexEntry { start: 1, stop: 5, addr: 4, @@ -735,97 +665,4 @@ mod tests { b"name" ); } - - fn create_tantivy_dir_with_hotcache<'a, V>( - field_entry: FieldEntry, - field_value: V, - ) -> (HotDirectory, usize) - where - V: Value<'a>, - { - let field_name = field_entry.name().to_string(); - let mut schema_builder = Schema::builder(); - schema_builder.add_field(field_entry); - let schema = schema_builder.build(); - - let ram_directory = RamDirectory::create(); - let index = Index::open_or_create(ram_directory.clone(), schema.clone()).unwrap(); - - let mut index_writer = index.writer(15_000_000).unwrap(); - let field = schema.get_field(&field_name).unwrap(); - let mut new_doc = TantivyDocument::default(); - new_doc.add_field_value(field, field_value); - index_writer.add_document(new_doc).unwrap(); - index_writer.commit().unwrap(); - - let mut hotcache_bytes: Vec = Vec::new(); - write_hotcache(ram_directory.clone(), &mut hotcache_bytes).unwrap(); - let hotcache_bytes = OwnedBytes::new(hotcache_bytes); - let hot_directory = HotDirectory::open(ram_directory.clone(), hotcache_bytes).unwrap(); - (hot_directory, ram_directory.total_mem_usage()) - } - - #[test] - fn test_num_bytes_without_doc_store_excludes_store() { - // We don't want to make assertions on absolute index sizes (it might - // change in future Tantivy versions), but rather verify that the store - // is properly excluded from the computed size. - - // We use random bytes so that the store can't compress them - let mut payload = vec![0u8; 1024]; - rand::rng().fill(&mut payload[..]); - - let (hotcache_directory_stored_payload, directory_size_stored_payload) = - create_tantivy_dir_with_hotcache( - FieldEntry::new_bytes("payload".to_string(), BytesOptions::default().set_stored()), - &payload, - ); - let size_with_stored_payload = - hotcache_directory_stored_payload.num_bytes_without_doc_store(); - - let (hotcache_directory_index_only, directory_size_index_only) = - create_tantivy_dir_with_hotcache( - FieldEntry::new_bytes("payload".to_string(), BytesOptions::default()), - &payload, - ); - let size_index_only = hotcache_directory_index_only.num_bytes_without_doc_store(); - - assert!(directory_size_stored_payload > directory_size_index_only + 1000); - assert!(size_with_stored_payload.abs_diff(size_index_only) < 10); - } - - #[test] - fn test_num_bytes_without_doc_store_varies_with_data() { - // We don't want to make assertions on absolute index sizes (it might - // change in future Tantivy versions), but rather verify that an index - // with more data is indeed bigger. - - let indexing_options = - TextOptions::default().set_indexing_options(TextFieldIndexing::default()); - - let (hotcache_directory_larger, directory_size_larger) = create_tantivy_dir_with_hotcache( - FieldEntry::new_text("text".to_string(), indexing_options.clone()), - "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium \ - doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore \ - veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam \ - voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur \ - magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, \ - qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non \ - numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat \ - voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis \ - suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum \ - iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, \ - vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?", - ); - let larger_size = hotcache_directory_larger.num_bytes_without_doc_store(); - - let (hotcache_directory_smaller, directory_size_smaller) = create_tantivy_dir_with_hotcache( - FieldEntry::new_text("text".to_string(), indexing_options), - "hi", - ); - let smaller_size = hotcache_directory_smaller.num_bytes_without_doc_store(); - - assert!(directory_size_larger > directory_size_smaller + 100); - assert!(larger_size > smaller_size + 100); - } } diff --git a/quickwit/quickwit-directories/src/lib.rs b/quickwit/quickwit-directories/src/lib.rs index 8e380cd4a90..7562c5801d3 100644 --- a/quickwit/quickwit-directories/src/lib.rs +++ b/quickwit/quickwit-directories/src/lib.rs @@ -12,32 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! This crate contains all of the building pieces that make quickwit's IO possible. +//! Custom Tantivy [`tantivy::Directory`] implementations used by Quickwit. //! -//! - The `StorageDirectory` just wraps a `Storage` trait to make it compatible with tantivy's -//! Directory API. -//! - The `BundleDirectory` bundles multiple files into a single file. -//! - The `HotDirectory` wraps another directory with a static cache. -//! - The `CachingDirectory` wraps a Directory with a dynamic cache. -//! - The `DebugDirectory` acts as a proxy to another directory to instrument it and record all of -//! its IO. +//! - [`SplitDirectory`] provides a static search-path directory over a +//! [`quickwit_storage::SplitBundle`], consulting the hotcache first, an optional short-lived +//! per-split cache second, and streaming ranges directly through the bundle. +//! - [`BundleDirectory`] reads files bundled inside a local split file (used by indexing). +//! - [`UnionDirectory`] merges multiple read-only directories. + #![warn(missing_docs)] #![deny(clippy::disallowed_methods)] mod bundle_directory; -mod caching_directory; -mod debug_proxy_directory; -mod hot_directory; -mod storage_directory; +mod byte_range_cache; +mod hotcache; +mod split_directory; mod union_directory; pub use self::bundle_directory::{BundleDirectory, get_hotcache_from_split, read_split_footer}; -pub use self::caching_directory::{ - CachingDirectory, MemoryReservation, MemoryReserver, OutOfMemoryError, +pub use self::hotcache::write_hotcache; +pub use self::split_directory::{ + MemoryReservation, MemoryReserver, OutOfMemoryError, ShortLivedCache, SplitDirectory, }; -pub use self::debug_proxy_directory::{DebugProxyDirectory, ReadOperation}; -pub use self::hot_directory::{HotDirectory, write_hotcache}; -pub use self::storage_directory::StorageDirectory; pub use self::union_directory::UnionDirectory; macro_rules! read_only_directory { diff --git a/quickwit/quickwit-directories/src/split_directory.rs b/quickwit/quickwit-directories/src/split_directory.rs new file mode 100644 index 00000000000..7a9fa3005b9 --- /dev/null +++ b/quickwit/quickwit-directories/src/split_directory.rs @@ -0,0 +1,587 @@ +// Copyright 2021-Present Datadog, Inc. +// +// Licensed 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 std::ops::Range; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::{fmt, io}; + +use async_trait::async_trait; +use futures::stream::BoxStream; +use quickwit_storage::{OwnedBytes, SplitBundle}; +use tantivy::directory::FileHandle; +use tantivy::directory::error::OpenReadError; +use tantivy::{Directory, HasLen}; +use tracing::{error, instrument}; + +use crate::byte_range_cache::{ByteRangeCache, FileByteRangeCache}; +use crate::hotcache::{StaticDirectoryCache, StaticSliceCache}; + +/// Returned when reserving memory would go over the warmup memory limit of a split search. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OutOfMemoryError; + +impl fmt::Display for OutOfMemoryError { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "out of warmup memory") + } +} + +impl std::error::Error for OutOfMemoryError {} + +impl From for io::Error { + fn from(out_of_memory_error: OutOfMemoryError) -> io::Error { + io::Error::new(io::ErrorKind::OutOfMemory, out_of_memory_error) + } +} + +/// Memory reserved for a read in progress. +/// +/// Released on drop, except the bytes passed to `keep` once the read bytes are in the cache. +/// So the memory is also released if the read fails, panics, or if its future is dropped. +#[must_use = "dropping a memory reservation releases its memory right away"] +pub struct MemoryReservation<'a> { + memory_reserver: &'a dyn MemoryReserver, + /// Bytes released on drop. + num_bytes: u64, +} + +impl<'a> MemoryReservation<'a> { + /// Creates a memory reservation that releases `num_bytes` on drop. + /// + /// Contract: only called by `memory_reserver`, from + /// [`MemoryReserver::reserve_memory`], for `num_bytes` it has just reserved. A reservation + /// created for bytes that were not reserved would release them anyway. + pub fn new(memory_reserver: &'a dyn MemoryReserver, num_bytes: u64) -> MemoryReservation<'a> { + MemoryReservation { + memory_reserver, + num_bytes, + } + } + + /// Keeps `num_kept_bytes` reserved and releases the rest. + pub fn keep(mut self, num_kept_bytes: u64) { + debug_assert!( + num_kept_bytes <= self.num_bytes, + "cannot keep more bytes than reserved" + ); + self.num_bytes = self.num_bytes.saturating_sub(num_kept_bytes); + } +} + +impl Drop for MemoryReservation<'_> { + fn drop(&mut self) { + if self.num_bytes > 0 { + self.memory_reserver.release_memory(self.num_bytes); + } + } +} + +/// Reserves memory for the data a [`SplitDirectory`] downloads and keeps in its +/// short-lived cache. +/// +/// Only async reads reserve memory. +#[async_trait] +pub trait MemoryReserver: Send + Sync + 'static { + /// Called on each cache miss of an async read, before reading `num_bytes` from storage. + /// May wait until the memory is available, but must fail right away if the memory + /// can never be available. + /// + /// On success, returns a [`MemoryReservation`], which gives the memory back through + /// `release_memory` when dropped, except for the bytes the read added to the cache. + /// + /// On error, the read fails with an `io::Error` of kind `OutOfMemory`: storage is not called + /// and nothing is cached. + /// + /// Contract: the memory is reserved before the read starts, so the caller must not hold + /// anything another read waits on. + async fn reserve_memory( + &self, + num_bytes: u64, + ) -> Result, OutOfMemoryError>; + + /// Gives back `num_bytes` reserved by `reserve_memory` that a read did not add to the cache: + /// the read failed, panicked, its future was dropped, or the bytes were already cached. + /// + /// Contract: `num_bytes` were reserved by an earlier `reserve_memory` call, and are not + /// released twice. Called from `Drop`, possibly while a panic unwinds, so it must not panic. + fn release_memory(&self, num_bytes: u64); +} + +/// Configuration for the per-split short-lived cache inside [`SplitDirectory`]. +#[derive(Clone, Default)] +pub enum ShortLivedCache { + /// No short-lived cache. Hotcache misses read directly from [`SplitBundle`]. + #[default] + Disabled, + /// Caches hotcache misses in memory for the lifetime of this split search. + /// + /// When `memory_reserver` is set, async cache misses reserve memory before reading from + /// storage and keep only the bytes actually added to the cache. + Enabled { + /// Optional warmup memory budget reserver held for the lifetime of this directory. + memory_reserver: Option>, + }, +} + +/// Static Tantivy [`Directory`] over a [`SplitBundle`]. +/// +/// Every read passes through a fixed pipeline where the hotcache is consulted first: +/// +/// - Sync `read_bytes`: `hotcache` -> `short_lived_cache` -> unsupported-sync-read error +/// - Async `read_bytes_async`: `hotcache` -> `short_lived_cache` (with optional [`MemoryReserver`]) +/// -> [`SplitBundle::get_slice`] +/// - Streaming `stream_ranges`: bypasses `hotcache` and `short_lived_cache` -> +/// [`SplitBundle::stream_ranges`] +#[derive(Clone)] +pub struct SplitDirectory { + inner: Arc, +} + +struct SplitDirectoryInner { + bundle: SplitBundle, + hotcache: StaticDirectoryCache, + short_lived_cache: Option<(ByteRangeCache, Option>)>, +} + +impl fmt::Debug for SplitDirectory { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "SplitDirectory(bundle={:?}, hotcache={:?})", + self.inner.bundle, self.inner.hotcache + ) + } +} + +impl SplitDirectory { + /// Opens a `SplitDirectory` over `bundle` using its serialized `hotcache_bytes` and an + /// explicit [`ShortLivedCache`] mode. + pub fn open( + bundle: SplitBundle, + hotcache_bytes: OwnedBytes, + short_lived_cache: ShortLivedCache, + ) -> anyhow::Result { + let hotcache = StaticDirectoryCache::open(hotcache_bytes)?; + let short_lived_cache = match short_lived_cache { + ShortLivedCache::Disabled => None, + ShortLivedCache::Enabled { memory_reserver } => { + Some((ByteRangeCache::default(), memory_reserver)) + } + }; + Ok(Self { + inner: Arc::new(SplitDirectoryInner { + bundle, + hotcache, + short_lived_cache, + }), + }) + } + + /// Returns the number of bytes currently held in the per-split short-lived cache, or `0` when + /// the short-lived cache is disabled. + pub fn short_lived_cache_num_bytes(&self) -> u64 { + self.inner + .short_lived_cache + .as_ref() + .map(|(cache, _)| cache.get_num_bytes()) + .unwrap_or(0) + } + + /// Returns all files listed in the hotcache and their byte lengths. + /// + /// The actual hotcache payload is only a small fraction of these lengths. + pub fn get_file_lengths(&self) -> Vec<(PathBuf, u64)> { + self.inner.hotcache.get_file_lengths() + } + + /// Returns the sum of all file lengths excluding doc store files. + pub fn num_bytes_without_doc_store(&self) -> u64 { + self.get_file_lengths() + .iter() + .filter(|(path, _)| !path.to_string_lossy().ends_with("store")) + .map(|(_, file_length)| *file_length) + .sum() + } +} + +struct SplitFileHandle { + path: PathBuf, + file_length: u64, + bundle: SplitBundle, + hotcache: Arc, + short_lived_cache: Option<(FileByteRangeCache, Option>)>, +} + +impl fmt::Debug for SplitFileHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "SplitFileHandle(path={:?}, bundle={:?})", + self.path, self.bundle + ) + } +} + +impl HasLen for SplitFileHandle { + fn len(&self) -> usize { + self.file_length as usize + } +} + +#[async_trait] +impl FileHandle for SplitFileHandle { + fn read_bytes(&self, byte_range: Range) -> io::Result { + if byte_range.is_empty() { + return Ok(OwnedBytes::empty()); + } + if let Some(found_bytes) = self.hotcache.try_read_bytes(byte_range.clone()) { + return Ok(found_bytes); + } + if let Some((cache, _)) = &self.short_lived_cache + && let Some(found_bytes) = cache.get_slice(byte_range) + { + return Ok(found_bytes); + } + Err(unsupported_sync_read(&self.path)) + } + + #[instrument( + level = "debug", + fields(path = %self.path.to_string_lossy(), byte_range_size = byte_range.end - byte_range.start), + skip(self) + )] + async fn read_bytes_async(&self, byte_range: Range) -> io::Result { + if byte_range.is_empty() { + return Ok(OwnedBytes::empty()); + } + if let Some(found_bytes) = self.hotcache.try_read_bytes(byte_range.clone()) { + return Ok(found_bytes); + } + let Some((cache, memory_reserver)) = &self.short_lived_cache else { + return Ok(self.bundle.get_slice(&self.path, byte_range).await?); + }; + if let Some(found_bytes) = cache.get_slice(byte_range.clone()) { + return Ok(found_bytes); + } + let read_reservation = match memory_reserver { + Some(reserver) => Some(reserver.reserve_memory(byte_range.len() as u64).await?), + None => None, + }; + let read_bytes = self + .bundle + .get_slice(&self.path, byte_range.clone()) + .await?; + let num_added_bytes = cache.put_slice(byte_range, read_bytes.clone()); + if let Some(reservation) = read_reservation { + reservation.keep(num_added_bytes); + } + Ok(read_bytes) + } + + fn stream_ranges( + &self, + ranges: Box> + Send>, + ) -> BoxStream<'_, io::Result> { + self.bundle.stream_ranges(&self.path, ranges) + } +} + +impl Directory for SplitDirectory { + fn get_file_handle(&self, path: &Path) -> Result, OpenReadError> { + let file_length = self + .inner + .hotcache + .get_file_length(path) + .ok_or_else(|| OpenReadError::FileDoesNotExist(path.to_owned()))?; + let short_lived_cache = self + .inner + .short_lived_cache + .as_ref() + .map(|(cache, memory_reserver)| (cache.get_file_cache(path), memory_reserver.clone())); + Ok(Arc::new(SplitFileHandle { + path: path.to_path_buf(), + file_length, + bundle: self.inner.bundle.clone(), + hotcache: self.inner.hotcache.get_slice(path), + short_lived_cache, + })) + } + + fn exists(&self, path: &Path) -> Result { + Ok(self.inner.hotcache.get_file_length(path).is_some()) + } + + fn atomic_read(&self, path: &Path) -> Result, OpenReadError> { + let file_handle = self.get_file_handle(path)?; + let len = file_handle.len(); + let owned_bytes = file_handle + .read_bytes(0..len) + .map_err(|io_error| OpenReadError::wrap_io_error(io_error, path.to_path_buf()))?; + Ok(owned_bytes.as_slice().to_vec()) + } + + crate::read_only_directory!(); +} + +fn unsupported_sync_read(path: &Path) -> io::Error { + let error = + "unsupported operation: `SplitDirectory` only supports async reads for uncached data"; + error!(error, ?path); + io::Error::other(format!("{error}: {}", path.display())) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering}; + + use quickwit_common::uri::Uri; + use quickwit_storage::{ + DownloadCounters, MockStorage, PutPayload, RamStorageBuilder, SplitPayloadBuilder, + SplitStorageReader, Storage, StorageErrorKind, + }; + use tantivy::directory::RamDirectory; + use tantivy::schema::{STRING, Schema}; + use tantivy::{Index, IndexWriter, doc}; + use tantivy_fst::Regex; + + use super::*; + use crate::hotcache::{empty_hotcache_for_files, write_hotcache}; + + struct LimitedMemoryReserver { + limit: u64, + reserved: AtomicU64, + } + + impl LimitedMemoryReserver { + fn new(limit: u64) -> Arc { + Arc::new(Self { + limit, + reserved: AtomicU64::new(0), + }) + } + + fn reserved(&self) -> u64 { + self.reserved.load(Ordering::Relaxed) + } + } + + #[async_trait] + impl MemoryReserver for LimitedMemoryReserver { + async fn reserve_memory( + &self, + num_bytes: u64, + ) -> Result, OutOfMemoryError> { + self.reserved + .try_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| { + let new_reserved = reserved + num_bytes; + (new_reserved <= self.limit).then_some(new_reserved) + }) + .map_err(|_| OutOfMemoryError)?; + Ok(MemoryReservation::new(self, num_bytes)) + } + + fn release_memory(&self, num_bytes: u64) { + self.reserved.fetch_sub(num_bytes, Ordering::Relaxed); + } + } + + async fn open_split_directory( + builder: SplitPayloadBuilder, + hotcache_bytes: &[u8], + storage_override: Option>, + short_lived_cache: ShortLivedCache, + ) -> (SplitDirectory, Arc) { + let split_bytes = builder + .finalize(hotcache_bytes) + .unwrap() + .read_all() + .await + .unwrap(); + let backend: Arc = storage_override.unwrap_or_else(|| { + Arc::new( + RamStorageBuilder::default() + .put("split", &split_bytes) + .build(), + ) + }); + let reader = SplitStorageReader::new(backend); + let counters = reader.download_counters().clone(); + let (bundle, hotcache) = + SplitBundle::open_from_split_bytes(reader, PathBuf::from("split"), split_bytes) + .unwrap(); + ( + SplitDirectory::open(bundle, hotcache, short_lived_cache).unwrap(), + counters, + ) + } + + async fn single_file_dir( + storage_override: Option>, + short_lived_cache: ShortLivedCache, + ) -> (SplitDirectory, Arc) { + let hotcache_bytes = empty_hotcache_for_files(&[ + (PathBuf::from("test"), 11), + (PathBuf::from("ignored.store"), 1000), + ]); + let mut builder = SplitPayloadBuilder::default(); + builder.add_payload("test".to_string(), Box::new(b"hello world".to_vec())); + open_split_directory( + builder, + &hotcache_bytes, + storage_override, + short_lived_cache, + ) + .await + } + + #[tokio::test] + async fn test_short_lived_cache_and_memory_reservation() { + let memory_reserver = LimitedMemoryReserver::new(10); + let (dir, counters) = single_file_dir( + None, + ShortLivedCache::Enabled { + memory_reserver: Some(memory_reserver.clone()), + }, + ) + .await; + assert_eq!(dir.num_bytes_without_doc_store(), 11); + let file_handle = dir.get_file_handle(Path::new("test")).unwrap(); + + // Miss reserves memory; repeat read hits cache without another backend request. + file_handle.read_bytes_async(0..5).await.unwrap(); + file_handle.read_bytes_async(0..5).await.unwrap(); + assert_eq!(memory_reserver.reserved(), 5); + assert_eq!(counters.snapshot().1, 1); + + // Overlapping miss: 3..5 is already cached, only 5..8 stays reserved. + file_handle.read_bytes_async(3..8).await.unwrap(); + assert_eq!(counters.snapshot().1, 2); + assert_eq!(dir.short_lived_cache_num_bytes(), 8); + assert_eq!(memory_reserver.reserved(), 8); + + // Warmed ranges can be read synchronously; unwarmed sync reads fail. + assert_eq!( + file_handle.read_bytes(0..8).unwrap().as_slice(), + b"hello wo" + ); + assert!(file_handle.read_bytes(0..11).is_err()); + + // Exceeding the memory limit returns OutOfMemory without touching storage. + let io_error = file_handle.read_bytes_async(8..11).await.unwrap_err(); + assert_eq!(io_error.kind(), io::ErrorKind::OutOfMemory); + assert_eq!(counters.snapshot().1, 2); + assert_eq!(memory_reserver.reserved(), 8); + + // Disabled short-lived cache reads directly from storage every time. + let (uncached_dir, uncached_counters) = + single_file_dir(None, ShortLivedCache::Disabled).await; + let uncached_handle = uncached_dir.get_file_handle(Path::new("test")).unwrap(); + assert_eq!( + uncached_handle + .read_bytes_async(0..5) + .await + .unwrap() + .as_slice(), + b"hello" + ); + uncached_handle.read_bytes_async(0..5).await.unwrap(); + assert_eq!(uncached_counters.snapshot().1, 2); + + // Failed backend reads release their memory reservation. + let mut failing_storage = MockStorage::default(); + failing_storage + .expect_uri() + .return_const(Uri::for_test("ram:///failing")); + failing_storage + .expect_get_slice() + .returning(|_, _| Err(StorageErrorKind::Io.with_error(anyhow::anyhow!("read failed")))); + let error_reserver = LimitedMemoryReserver::new(100); + let (failing_dir, _) = single_file_dir( + Some(Arc::new(failing_storage)), + ShortLivedCache::Enabled { + memory_reserver: Some(error_reserver.clone()), + }, + ) + .await; + let failing_handle = failing_dir.get_file_handle(Path::new("test")).unwrap(); + assert!(failing_handle.read_bytes_async(0..5).await.is_err()); + assert_eq!(error_reserver.reserved(), 0); + } + + #[tokio::test] + async fn test_automaton_bitset_bypasses_short_lived_cache_and_memory_budget() + -> tantivy::Result<()> { + let ram_dir = RamDirectory::create(); + let mut schema = Schema::builder(); + let field = schema.add_text_field("field", STRING); + let index = Index::create(ram_dir.clone(), schema.build(), Default::default())?; + let mut writer: IndexWriter = index.writer_with_num_threads(1, 15_000_000)?; + for value in ["a", "m", "z"] { + writer.add_document(doc!(field => value))?; + } + writer.commit()?; + + let mut hotcache_bytes = Vec::new(); + write_hotcache(ram_dir.clone(), &mut hotcache_bytes).unwrap(); + let metas = Index::open(ram_dir.clone())?.load_metas()?; + let mut builder = SplitPayloadBuilder::default(); + for path in metas + .list_segment_files() + .into_iter() + .chain([PathBuf::from("meta.json"), PathBuf::from(".managed.json")]) + { + if let Ok(bytes) = ram_dir.atomic_read(&path) { + builder.add_payload(path.to_string_lossy().into_owned(), Box::new(bytes)); + } + } + + let budget_bytes = 32 * 1024 * 1024; + let reserver = LimitedMemoryReserver::new(budget_bytes); + let (split_dir, counters) = open_split_directory( + builder, + &hotcache_bytes, + None, + ShortLivedCache::Enabled { + memory_reserver: Some(reserver.clone()), + }, + ) + .await; + + let index = Index::open(split_dir.clone())?; + let searcher = index.reader()?.searcher(); + let segment = searcher.segment_reader(0); + let inverted_index = segment.inverted_index(field)?; + assert_eq!(counters.snapshot().1, 0); + let initial_cached_bytes = split_dir.short_lived_cache_num_bytes(); + let _reservation = reserver + .reserve_memory(budget_bytes - reserver.reserved()) + .await + .unwrap(); + let subset = inverted_index + .create_bitset_for_automaton( + Regex::new("a|z").unwrap(), + segment.max_doc(), + |task| async move { task() }, + ) + .await?; + assert!(subset.len() == 2 && subset.contains(0) && subset.contains(2)); + assert_eq!( + split_dir.short_lived_cache_num_bytes(), + initial_cached_bytes + ); + assert!(counters.snapshot().1 > 0); + Ok(()) + } +} diff --git a/quickwit/quickwit-directories/src/storage_directory.rs b/quickwit/quickwit-directories/src/storage_directory.rs deleted file mode 100644 index e8d2ce7f055..00000000000 --- a/quickwit/quickwit-directories/src/storage_directory.rs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::fmt::Debug; -use std::ops::Range; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::{fmt, io}; - -mod coalesced_range_stream; - -use async_trait::async_trait; -use futures::stream::BoxStream; -use quickwit_common::uri::Uri; -use quickwit_storage::{OwnedBytes, Storage}; -use tantivy::directory::FileHandle; -use tantivy::directory::error::OpenReadError; -use tantivy::{Directory, HasLen}; -use tracing::{error, instrument}; - -struct StorageDirectoryFileHandle { - storage_directory: StorageDirectory, - path: PathBuf, -} - -impl HasLen for StorageDirectoryFileHandle { - fn len(&self) -> usize { - unimplemented!() - } -} - -impl fmt::Debug for StorageDirectoryFileHandle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "StorageDirectoryFileHandle({:?}, dir={:?})", - self.path, self.storage_directory - ) - } -} - -#[async_trait] -impl FileHandle for StorageDirectoryFileHandle { - fn read_bytes(&self, _byte_range: Range) -> io::Result { - Err(unsupported_operation(&self.path)) - } - - #[instrument(level = "debug", fields(path = %self.path.to_string_lossy(), byte_range_size = byte_range.end - byte_range.start), skip(self))] - async fn read_bytes_async(&self, byte_range: Range) -> io::Result { - if byte_range.is_empty() { - return Ok(OwnedBytes::empty()); - } - let object_bytes = self - .storage_directory - .get_slice(&self.path, byte_range) - .await?; - Ok(object_bytes) - } - - fn stream_ranges( - &self, - ranges: Box> + Send>, - ) -> BoxStream<'_, io::Result> { - coalesced_range_stream::download_ranges( - self.storage_directory.storage.as_ref(), - &self.path, - ranges, - ) - } -} - -/// Directory backed a quickwit `Storage` abstraction. -/// -/// It should not be used in a context outside quickwit, as it contains -/// several pitfalls: -/// Fetching data synchronously panics. -/// Writing data panics. -/// -/// This directory is fetch slices of data to a possibly distant storage -/// everytime `read_bytes` is called. -#[derive(Clone)] -pub struct StorageDirectory { - storage: Arc, -} - -impl Debug for StorageDirectory { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "StorageDirectory({:?})", self.uri()) - } -} - -impl StorageDirectory { - /// Creates a new StorageDirectory, backed by the given `storage`. - pub fn new(storage: Arc) -> StorageDirectory { - StorageDirectory { storage } - } - - /// Fetches a slice of byte from a file asynchronously. - pub async fn get_slice(&self, path: &Path, range: Range) -> io::Result { - let payload: OwnedBytes = self.storage.get_slice(path, range).await?; - Ok(payload) - } - - /// Fetches an entire file asynchronously. - pub async fn get_all(&self, path: &Path) -> io::Result { - let payload: OwnedBytes = self.storage.get_all(path).await?; - Ok(payload) - } - - /// Returns the uri associated to the underlying storage. - pub fn uri(&self) -> &Uri { - self.storage.uri() - } -} - -fn unsupported_operation(path: &Path) -> io::Error { - let error = "unsupported operation: `StorageDirectory` only supports async reads"; - error!(error, ?path); - io::Error::other(format!("{error}: {}", path.display())) -} - -impl Directory for StorageDirectory { - fn get_file_handle(&self, path: &Path) -> Result, OpenReadError> { - Ok(Arc::new(StorageDirectoryFileHandle { - storage_directory: self.clone(), - path: path.to_path_buf(), - })) - } - - fn atomic_read(&self, path: &Path) -> Result, OpenReadError> { - Err(OpenReadError::wrap_io_error( - unsupported_operation(path), - path.to_path_buf(), - )) - } - - fn exists(&self, path: &std::path::Path) -> Result { - Err(OpenReadError::wrap_io_error( - unsupported_operation(path), - path.to_path_buf(), - )) - } - - crate::read_only_directory!(); -} diff --git a/quickwit/quickwit-indexing/src/split_recovery_tests.rs b/quickwit/quickwit-indexing/src/split_recovery_tests.rs index 15854c475a1..6190020a0bb 100644 --- a/quickwit/quickwit-indexing/src/split_recovery_tests.rs +++ b/quickwit/quickwit-indexing/src/split_recovery_tests.rs @@ -28,7 +28,7 @@ use quickwit_proto::metastore::{ SplitRecoveryMetadata, StageSplitsRequest, }; use quickwit_proto::types::SplitId; -use quickwit_storage::{BundleStorage, RamStorage, Storage}; +use quickwit_storage::{RamStorage, SplitBundle, SplitStorageReader}; use crate::test_utils::TestSandbox; @@ -42,7 +42,7 @@ async fn recover_and_publish_split( let split_path = Path::new(&split_filename); let storage = test_sandbox.storage(); let (split_bundle, _hotcache, footer_offsets) = - BundleStorage::open_from_storage(storage, split_path.to_path_buf()).await?; + SplitBundle::open(SplitStorageReader::new(storage), split_path.to_path_buf()).await?; let serialized_recovery_metadata = split_bundle .get_all(Path::new(SPLIT_RECOVERY_METADATA_FILE_NAME)) .await?; diff --git a/quickwit/quickwit-metrics-inventory/metrics.yaml b/quickwit/quickwit-metrics-inventory/metrics.yaml index 652e5f73cd2..3c3119f8a1c 100644 --- a/quickwit/quickwit-metrics-inventory/metrics.yaml +++ b/quickwit/quickwit-metrics-inventory/metrics.yaml @@ -154,34 +154,6 @@ quickwit_cache_in_cache_num_bytes: module: quickwit_storage::metrics kind: gauge description: Number of bytes in cache by component -quickwit_cache_virtual_cache_evict_bytes: - module: quickwit_storage::metrics - kind: counter - description: Number of cache entry evicted in bytes by component -quickwit_cache_virtual_cache_evict_total: - module: quickwit_storage::metrics - kind: counter - description: Number of cache entry evicted by component -quickwit_cache_virtual_cache_hits_bytes: - module: quickwit_storage::metrics - kind: counter - description: Number of cache hits in bytes by component -quickwit_cache_virtual_cache_hits_total: - module: quickwit_storage::metrics - kind: counter - description: Number of cache hits by component -quickwit_cache_virtual_cache_misses_total: - module: quickwit_storage::metrics - kind: counter - description: Number of cache misses by component -quickwit_cache_virtual_in_cache_count: - module: quickwit_storage::metrics - kind: gauge - description: Count of in cache by component -quickwit_cache_virtual_in_cache_num_bytes: - module: quickwit_storage::metrics - kind: gauge - description: Number of bytes in cache by component quickwit_cli_thread_unpark_duration_microseconds: module: quickwit_cli::metrics kind: histogram @@ -781,7 +753,7 @@ quickwit_storage_object_storage_get_slice_in_flight_num_bytes: quickwit_storage_object_storage_gets_total: module: quickwit_storage::metrics kind: counter - description: Number of objects fetched. Might be lower than get_slice_timeout_outcome if queries are debounced. + description: Number of objects fetched. Might be higher than get_slice_timeout_outcome if timed-out reads are retried. quickwit_storage_object_storage_put_attempt_errors_total: module: quickwit_storage::metrics kind: counter diff --git a/quickwit/quickwit-search/src/error.rs b/quickwit/quickwit-search/src/error.rs index e1d4c66bef0..0019080bfd5 100644 --- a/quickwit/quickwit-search/src/error.rs +++ b/quickwit/quickwit-search/src/error.rs @@ -202,7 +202,7 @@ impl From for SearchError { } } -/// Hidden contract: in the search path, only the `CachingDirectory` returns +/// Hidden contract: in the search path, only `SplitDirectory` returns /// `io::ErrorKind::OutOfMemory`, when the split search would go over its warmup memory limit. If /// another source ever returned that kind, the split would not be /// retried either, which is fine for a memory problem. diff --git a/quickwit/quickwit-search/src/fetch_docs.rs b/quickwit/quickwit-search/src/fetch_docs.rs index b6dbe147053..7ae7374a00f 100644 --- a/quickwit/quickwit-search/src/fetch_docs.rs +++ b/quickwit/quickwit-search/src/fetch_docs.rs @@ -18,6 +18,7 @@ use std::sync::Arc; use anyhow::{Context, Ok}; use futures::{StreamExt, TryFutureExt, TryStreamExt}; use itertools::Itertools; +use quickwit_directories::ShortLivedCache; use quickwit_doc_mapper::DocMapper; use quickwit_proto::search::{ FetchDocsResponse, PartialHit, SnippetRequest, SplitIdAndFooterOffsets, @@ -30,7 +31,7 @@ use tantivy::snippet::SnippetGenerator; use tantivy::{ReloadPolicy, Score, Searcher, Term}; use tracing::{Instrument, error, instrument}; -use crate::leaf::open_index_with_caches; +use crate::leaf::open_split_index; use crate::service::SearcherContext; use crate::{GlobalDocAddress, convert_document_to_json_string}; @@ -163,15 +164,13 @@ async fn fetch_docs_in_split( snippet_request_opt: Option<&SnippetRequest>, ) -> anyhow::Result> { global_doc_addrs.sort_by_key(|doc| doc.doc_addr); - // Opens the index without the ephemeral unbounded cache, this cache is indeed not useful - // when fetching docs as we will fetch them only once. - let (mut index, _) = open_index_with_caches( - &searcher_context, - index_storage, + // Opens the index without the short-lived cache: fetching docs reads each block once. + let reader = searcher_context.split_storage_reader(index_storage); + let (mut index, _) = open_split_index( + reader, split, Some(doc_mapper.tokenizer_manager()), - None, - None, + ShortLivedCache::Disabled, ) .await .context("open-index-for-split")?; diff --git a/quickwit/quickwit-search/src/leaf.rs b/quickwit/quickwit-search/src/leaf.rs index be125e79f4e..e1b9a15b543 100644 --- a/quickwit/quickwit-search/src/leaf.rs +++ b/quickwit/quickwit-search/src/leaf.rs @@ -31,7 +31,7 @@ use futures::stream::{self, FuturesUnordered}; use quickwit_common::pretty::PrettySample; use quickwit_common::thread_pool::with_priority::Priority; use quickwit_common::uri::Uri; -use quickwit_directories::{CachingDirectory, HotDirectory, MemoryReserver, StorageDirectory}; +use quickwit_directories::{MemoryReserver, ShortLivedCache, SplitDirectory}; use quickwit_doc_mapper::{Automaton, DocMapper, FastFieldWarmupInfo, TermRange, WarmupInfo}; use quickwit_metrics::HistogramTimer; use quickwit_proto::search::lambda_single_split_result::Outcome; @@ -45,10 +45,7 @@ use quickwit_query::query_ast::{ QueryAstTransformer, RangeQuery, TermQuery, get_or_compile_cached_fst_regex, }; use quickwit_query::tokenizers::TokenizerManager; -use quickwit_storage::{ - BundleStorage, ByteRangeCache, CountingStorage, OwnedBytes, SearchSplitCache, Storage, - StorageResolver, TimeoutAndRetryStorage, wrap_storage_with_storage_cache, -}; +use quickwit_storage::{OwnedBytes, SplitBundle, SplitStorageReader, Storage, StorageResolver}; use tantivy::aggregation::AggContextParams; use tantivy::aggregation::agg_req::{AggregationVariants, Aggregations}; use tantivy::collector::Collector; @@ -128,22 +125,13 @@ fn greedy_batch_split( batches } -/// Returns the hotcache bytes and storage for the files inside the split. +/// Returns the hotcache bytes and [`SplitBundle`] for the files inside the split. pub(crate) async fn open_split_bundle( - searcher_context: &SearcherContext, - index_storage: Arc, + reader: SplitStorageReader, split_and_footer_offsets: &SplitIdAndFooterOffsets, -) -> anyhow::Result<(OwnedBytes, BundleStorage)> { +) -> anyhow::Result<(OwnedBytes, SplitBundle)> { let split_file = PathBuf::from(format!("{}.split", split_and_footer_offsets.split_id)); - let index_storage = match &searcher_context.split_cache_opt { - Some(split_cache) => SearchSplitCache::wrap_storage(split_cache.clone(), index_storage), - None => index_storage, - }; - let cached_storage: Arc = match &searcher_context.storage_cache_opt { - Some(cache) => wrap_storage_with_storage_cache(cache.clone(), index_storage), - None => index_storage, - }; - let footer_data = cached_storage + let footer_data = reader .get_slice( &split_file, split_and_footer_offsets.split_footer_start as usize @@ -153,15 +141,15 @@ pub(crate) async fn open_split_bundle( .with_context(|| { format!( "failed to fetch hotcache and footer from {} for split `{}`", - cached_storage.uri(), + reader.uri(), split_and_footer_offsets.split_id ) })?; - let (bundle_storage, hotcache_bytes) = - BundleStorage::open_from_split_bytes(cached_storage, split_file, footer_data)?; + let (split_bundle, hotcache_bytes) = + SplitBundle::open_from_split_bytes(reader, split_file, footer_data)?; - Ok((hotcache_bytes, bundle_storage)) + Ok((hotcache_bytes, split_bundle)) } /// Returns the process-wide expression compilation cache. @@ -183,64 +171,19 @@ fn set_expr_compilation_cache(index: &mut Index) { index.set_expr_compilation_cache(GLOBAL_EXPR_COMPILATION_CACHE.clone()); } -/// Add a storage proxy to retry `get_slice` requests if they are taking too long, -/// if configured in the searcher config. -/// -/// The goal here is too ensure a low latency. -fn configure_storage_retries( - searcher_context: &SearcherContext, - index_storage: Arc, -) -> Arc { - if let Some(storage_timeout_policy) = &searcher_context.searcher_config.storage_timeout_policy { - Arc::new(TimeoutAndRetryStorage::new( - index_storage, - storage_timeout_policy.clone(), - )) - } else { - index_storage - } -} - -/// Opens a `tantivy::Index` for the given split with several cache layers: -/// - The `storage_cache` given by `SearcherContext.storage_cache_opt`, including footer bytes. -/// - An ephemeral unbounded cache directory (whose lifetime is tied to the returned `Index` if no -/// `ByteRangeCache` is provided). -/// -/// If `warmup_memory` is provided, every buffered read that misses the hotcache and the ephemeral -/// cache first reserves memory in it, and fails if the warmup memory limit would be exceeded. -/// Streaming reads bypass the ephemeral cache and its reservations. -pub(crate) async fn open_index_with_caches( - searcher_context: &SearcherContext, - index_storage: Arc, +/// Opens a `tantivy::Index` for the given split over a [`SplitStorageReader`] and an explicit +/// [`ShortLivedCache`] configuration. +pub(crate) async fn open_split_index( + reader: SplitStorageReader, split_and_footer_offsets: &SplitIdAndFooterOffsets, tokenizer_manager: Option<&TokenizerManager>, - ephemeral_unbounded_cache: Option, - warmup_memory: Option>, -) -> crate::Result<(Index, HotDirectory)> { - let index_storage_with_retry_on_timeout = - configure_storage_retries(searcher_context, index_storage); - - let (hotcache_bytes, bundle_storage) = open_split_bundle( - searcher_context, - index_storage_with_retry_on_timeout, - split_and_footer_offsets, - ) - .await?; + short_lived_cache: ShortLivedCache, +) -> crate::Result<(Index, SplitDirectory)> { + let (hotcache_bytes, split_bundle) = + open_split_bundle(reader, split_and_footer_offsets).await?; + let split_directory = SplitDirectory::open(split_bundle, hotcache_bytes, short_lived_cache)?; - let directory = StorageDirectory::new(Arc::new(bundle_storage)); - - let hot_directory = if let Some(cache) = ephemeral_unbounded_cache { - let mut caching_directory = CachingDirectory::new(Arc::new(directory), cache); - // Storage cache hits are also kept in the ephemeral cache, so they count too. - if let Some(warmup_memory) = warmup_memory { - caching_directory = caching_directory.with_memory_reserver(warmup_memory); - } - HotDirectory::open(caching_directory, hotcache_bytes)? - } else { - HotDirectory::open(directory, hotcache_bytes)? - }; - - let mut index = Index::open(hot_directory.clone())?; + let mut index = Index::open(split_directory.clone())?; if let Some(tokenizer_manager) = tokenizer_manager { index.set_tokenizers(tokenizer_manager.tantivy_manager().clone()); } @@ -250,7 +193,7 @@ pub(crate) async fn open_index_with_caches( .clone(), ); set_expr_compilation_cache(&mut index); - Ok((index, hot_directory)) + Ok((index, split_directory)) } /// Runs `fut`, racing it against `cancel`. If cancellation fires first, the @@ -818,19 +761,15 @@ async fn leaf_search_single_split( } let split_id = split.split_id.to_string(); - let byte_range_cache = ByteRangeCache::with_infinite_capacity(); - // Wrap storage at request scope so we observe per-split download volume. - // Cache layers (`storage_cache`, `split_cache`, hotcache, short-lived cache) live - // ABOVE this wrapper, so reads served from cache do not contribute to the - // counters — that is the desired "downloaded from object storage" semantics. - let (storage, download_counters) = CountingStorage::instrument_storage(storage); - let (index, hot_directory) = open_index_with_caches( - &ctx.searcher_context, - storage, + let reader = ctx.searcher_context.split_storage_reader(storage); + let download_counters = reader.download_counters().clone(); + let (index, split_directory) = open_split_index( + reader, &split, Some(ctx.doc_mapper.tokenizer_manager()), - Some(byte_range_cache.clone()), - Some(search_permit.warmup_memory()), + ShortLivedCache::Enabled { + memory_reserver: Some(search_permit.warmup_memory()), + }, ) .await .inspect_err(|_| { @@ -839,7 +778,7 @@ async fn leaf_search_single_split( })?; // The warmup cannot download more than the index, so we do not need to reserve more. - let index_size = ByteSize(hot_directory.num_bytes_without_doc_store()); + let index_size = ByteSize(split_directory.num_bytes_without_doc_store()); search_permit.shrink_memory_allocation(index_size); let searcher = index @@ -893,7 +832,7 @@ async fn leaf_search_single_split( // `download_counters`: opening the index fetches the footer and hotcache through the same // counted storage when `storage_cache` is cold. The short-lived cache is usually // still empty at this point, since index-open reads are served by the hotcache above it. - let cache_bytes_before_warmup = byte_range_cache.get_num_bytes(); + let cache_bytes_before_warmup = split_directory.short_lived_cache_num_bytes(); let downloaded_bytes_before_warmup = download_counters.snapshot().0; leaf_search_state_guard.set_state(SplitSearchState::WarmUp); // Negative cache: a split is provably empty for this query if any required term has @@ -967,8 +906,8 @@ async fn leaf_search_single_split( ); warmup_span.record( "total_mb", - byte_range_cache - .get_num_bytes() + split_directory + .short_lived_cache_num_bytes() .saturating_sub(cache_bytes_before_warmup) as f64 / BYTES_PER_MB, ); @@ -995,7 +934,7 @@ async fn leaf_search_single_split( } let warmup_end = Instant::now(); let warmup_duration: Duration = warmup_end.duration_since(warmup_start); - let warmup_size = ByteSize(byte_range_cache.get_num_bytes()); + let warmup_size = ByteSize(split_directory.short_lived_cache_num_bytes()); LEAF_SEARCH_SINGLE_SPLIT_WARMUP_NUM_BYTES.observe(warmup_size.as_u64() as f64); // The memory for the warmup data was reserved while it was downloaded. We give back what the // reservation holds in excess. @@ -2555,7 +2494,7 @@ async fn leaf_search_single_split_wrapper( .await; // Explicitly drop the permit for readability. // This should always happen after the ephemeral search cache is dropped. The split's - // `CachingDirectory` holds the other reference to the warmup memory, together with the + // `SplitDirectory` holds the other reference to the warmup memory, together with the // ephemeral search cache, so the warmup memory is freed here. std::mem::drop(search_permit); @@ -2615,9 +2554,8 @@ mod tests { split_footer_end: 20, ..Default::default() }; - let error = open_split_bundle(&SearcherContext::for_test(), storage.clone(), &offsets) - .await - .unwrap_err(); + let reader = SearcherContext::for_test().split_storage_reader(storage.clone()); + let error = open_split_bundle(reader, &offsets).await.unwrap_err(); assert_eq!( error.to_string(), format!( @@ -3381,9 +3319,44 @@ mod tests { } writer.commit().unwrap(); - let byte_cache = ByteRangeCache::with_infinite_capacity(); - let caching_dir = CachingDirectory::new(Arc::new(ram_dir), byte_cache.clone()); - let searcher = Index::open(caching_dir) + use quickwit_storage::PutPayload; + use tantivy::Directory; + + let mut hotcache_bytes = Vec::new(); + quickwit_directories::write_hotcache(ram_dir.clone(), &mut hotcache_bytes).unwrap(); + let metas = index.load_metas().unwrap(); + let mut file_paths: Vec = metas.list_segment_files().into_iter().collect(); + file_paths.push(PathBuf::from("meta.json")); + file_paths.push(PathBuf::from(".managed.json")); + let mut split_builder = quickwit_storage::SplitPayloadBuilder::default(); + for path in file_paths { + if let Ok(bytes) = ram_dir.atomic_read(&path) { + split_builder.add_payload(path.to_string_lossy().into_owned(), Box::new(bytes)); + } + } + let split_payload = split_builder.finalize(&hotcache_bytes).unwrap(); + let split_bytes = split_payload.read_all().await.unwrap(); + let ram_storage = Arc::new( + RamStorageBuilder::default() + .put("split", &split_bytes) + .build(), + ); + let (bundle, hotcache) = SplitBundle::open_from_split_bytes( + SplitStorageReader::new(ram_storage), + PathBuf::from("split"), + split_bytes, + ) + .unwrap(); + + let split_dir = SplitDirectory::open( + bundle, + hotcache, + ShortLivedCache::Enabled { + memory_reserver: None, + }, + ) + .unwrap(); + let searcher = Index::open(split_dir.clone()) .unwrap() .reader_builder() .reload_policy(ReloadPolicy::Manual) @@ -3392,7 +3365,7 @@ mod tests { .searcher(); // Opening the inverted index caches its metadata (termdict footer/index). let _ = searcher.segment_reader(0).inverted_index(body).unwrap(); - let initial_cached_bytes = byte_cache.get_num_bytes(); + let initial_cached_bytes = split_dir.short_lived_cache_num_bytes(); let predicate_cache = SearcherContext::for_test().predicate_cache.clone(); let automaton = Automaton::Regex(None, "(?i)a.*".to_string()); @@ -3419,7 +3392,10 @@ mod tests { .await .unwrap(); assert_eq!(hits.len(), 1); - assert_eq!(byte_cache.get_num_bytes(), initial_cached_bytes); + assert_eq!( + split_dir.short_lived_cache_num_bytes(), + initial_cached_bytes + ); let combined_warmup = WarmupInfo { automatons_grouped_by_field: HashMap::from([( @@ -3445,7 +3421,7 @@ mod tests { .await .unwrap(); assert_eq!(hits.len(), 1); - assert!(byte_cache.get_num_bytes() > initial_cached_bytes); + assert!(split_dir.short_lived_cache_num_bytes() > initial_cached_bytes); } fn nz(n: usize) -> std::num::NonZeroUsize { diff --git a/quickwit/quickwit-search/src/list_fields/leaf.rs b/quickwit/quickwit-search/src/list_fields/leaf.rs index 56bb8b5c598..bb8572b6b54 100644 --- a/quickwit/quickwit-search/src/list_fields/leaf.rs +++ b/quickwit/quickwit-search/src/list_fields/leaf.rs @@ -127,7 +127,8 @@ async fn fetch_fields_metadata( storage: Arc, split_footer: &SplitIdAndFooterOffsets, ) -> anyhow::Result { - let (_, split_bundle) = open_split_bundle(searcher_ctx, storage, split_footer).await?; + let reader = searcher_ctx.split_storage_reader(storage); + let (_, split_bundle) = open_split_bundle(reader, split_footer).await?; let serialized_entries = split_bundle .get_all(Path::new(SPLIT_FIELDS_FILE_NAME)) .await diff --git a/quickwit/quickwit-search/src/list_terms.rs b/quickwit/quickwit-search/src/list_terms.rs index 40421b9ce32..9e03d85b83a 100644 --- a/quickwit/quickwit-search/src/list_terms.rs +++ b/quickwit/quickwit-search/src/list_terms.rs @@ -22,6 +22,7 @@ use futures::future::try_join_all; use itertools::{Either, Itertools}; use quickwit_common::pretty::PrettySample; use quickwit_config::build_doc_mapper; +use quickwit_directories::ShortLivedCache; use quickwit_metastore::{ListSplitsRequestExt, MetastoreServiceStreamSplitsExt, SplitMetadata}; use quickwit_metrics::HistogramTimer; use quickwit_proto::metastore::{ListSplitsRequest, MetastoreService, MetastoreServiceClient}; @@ -30,13 +31,13 @@ use quickwit_proto::search::{ SplitIdAndFooterOffsets, SplitSearchError, }; use quickwit_proto::types::IndexUid; -use quickwit_storage::{ByteRangeCache, Storage}; +use quickwit_storage::Storage; use tantivy::schema::{Field, FieldType}; use tantivy::{ReloadPolicy, Term}; use tracing::{debug, error, info, instrument}; use crate::cost::compute_split_query_cost; -use crate::leaf::open_index_with_caches; +use crate::leaf::open_split_index; use crate::metrics::{LEAF_LIST_TERMS_SPLITS_TOTAL, LEAF_SEARCH_SPLIT_DURATION_SECS}; use crate::search_job_placer::group_jobs_by_index_id; use crate::search_permit_provider::{SearchPermit, compute_initial_memory_allocation}; @@ -221,18 +222,18 @@ async fn leaf_list_terms_single_split( split: SplitIdAndFooterOffsets, search_permit: &SearchPermit, ) -> crate::Result { - let cache = ByteRangeCache::with_infinite_capacity(); - let (index, hot_directory) = open_index_with_caches( - searcher_context, - storage, + let reader = searcher_context.split_storage_reader(storage); + let (index, split_directory) = open_split_index( + reader, &split, None, - Some(cache), - Some(search_permit.warmup_memory()), + ShortLivedCache::Enabled { + memory_reserver: Some(search_permit.warmup_memory()), + }, ) .await?; // Listing terms cannot download more than the index, so we do not need to reserve more. - search_permit.shrink_memory_allocation(ByteSize(hot_directory.num_bytes_without_doc_store())); + search_permit.shrink_memory_allocation(ByteSize(split_directory.num_bytes_without_doc_store())); let split_schema = index.schema(); let reader = index .reader_builder() @@ -404,7 +405,7 @@ pub async fn leaf_list_terms( timer.observe_duration(); // Explicitly drop the permit for readability. // This should always happen after the ephemeral search cache is dropped. The - // split's `CachingDirectory` holds the other reference to the warmup memory, + // split's `SplitDirectory` holds the other reference to the warmup memory, // together with the ephemeral search cache, so the warmup memory is freed here. std::mem::drop(leaf_split_search_permit); diff --git a/quickwit/quickwit-search/src/search_permit_provider.rs b/quickwit/quickwit-search/src/search_permit_provider.rs index ca941acb2a8..a027df767cb 100644 --- a/quickwit/quickwit-search/src/search_permit_provider.rs +++ b/quickwit/quickwit-search/src/search_permit_provider.rs @@ -91,7 +91,7 @@ pub enum SearchPermitMessage { /// Sent when a permit is dropped. /// /// The permit memory is freed separately, with a `MemoryFreed` message, once the split's - /// `CachingDirectory` is dropped too. + /// `SplitDirectory` is dropped too. Drop { warmup_slot_freed: bool, }, @@ -485,7 +485,7 @@ impl SearchPermitActor { pub struct SearchPermit { _ongoing_gauge_guard: GaugeGuard, msg_sender: mpsc::WeakUnboundedSender, - /// Shared with the split's `CachingDirectory`, see [`SearchPermit::warmup_memory`]. + /// Shared with the split's `SplitDirectory`, see [`SearchPermit::warmup_memory`]. warmup_memory: Arc, warmup_slot_freed: bool, job_cost: usize, @@ -501,7 +501,7 @@ impl SearchPermit { self.wait_for_acquisition } - /// Warmup memory of this split search, to give to the split's `CachingDirectory`. + /// Warmup memory of this split search, to give to the split's `SplitDirectory`. /// /// The memory is freed when both the permit and all the clones returned here are dropped. pub fn warmup_memory(&self) -> Arc { @@ -1148,7 +1148,7 @@ mod tests { ByteSize::mb(95), ); let permit = get_single_permit(&permit_provider, 95).await; - // Held by the split's `CachingDirectory` in practice. + // Held by the split's `SplitDirectory` in practice. let warmup_memory = permit.warmup_memory(); let mut pending_permit_futs = permit_provider .get_permits(make_splits(10, 2, 5, 0)) diff --git a/quickwit/quickwit-search/src/service.rs b/quickwit/quickwit-search/src/service.rs index a289d550b52..191e6b80465 100644 --- a/quickwit/quickwit-search/src/service.rs +++ b/quickwit/quickwit-search/src/service.rs @@ -29,7 +29,8 @@ use quickwit_proto::search::{ SearchPlanResponse, SearchRequest, SearchResponse, SnippetRequest, }; use quickwit_storage::{ - SearchSplitCache, StorageResolver, attach_storage_cache_access_trace, open_storage_cache, + SearchSplitCache, SplitStorageReader, Storage, StorageDebouncer, StorageResolver, + attach_storage_cache_access_trace, open_storage_cache, }; use tantivy::aggregation::AggregationLimitsGuard; @@ -416,6 +417,8 @@ pub struct SearcherContext { pub split_cache_opt: Option>, /// Cache for split byte ranges, with optional disk storage. pub storage_cache_opt: Option, + /// Node-global debouncer deduplicating concurrent slice and stream reads across splits. + pub storage_debouncer: Arc, /// List fields cache. Caches the raw fields-metadata blob for a given split. pub list_fields_cache: ListFieldsCache, /// The aggregation limits are passed to limit the memory usage. @@ -492,11 +495,29 @@ impl SearcherContext { list_fields_cache, split_cache_opt, storage_cache_opt, + storage_debouncer: Arc::new(StorageDebouncer::default()), aggregation_limit, lambda_invoker, } } + /// Constructs a [`SplitStorageReader`] wired with this searcher's storage cache, optional + /// whole-split cache, global debouncer, and timeout policy. + pub fn split_storage_reader(&self, backend: Arc) -> SplitStorageReader { + let mut reader = + SplitStorageReader::new(backend).with_debouncer(self.storage_debouncer.clone()); + if let Some(storage_cache) = &self.storage_cache_opt { + reader = reader.with_storage_cache(storage_cache.clone()); + } + if let Some(split_cache) = &self.split_cache_opt { + reader = reader.with_split_cache(split_cache.clone()); + } + if let Some(timeout_policy) = &self.searcher_config.storage_timeout_policy { + reader = reader.with_timeout_policy(timeout_policy.clone()); + } + reader + } + /// Open separate storage, partial-response, and predicate caches with shared disk I/O /// queues. Must complete before publishing this context to search tasks. Disk initialization /// failures fall back to memory only. Configuration and access-trace errors remain fatal. diff --git a/quickwit/quickwit-search/src/split_warmup_memory.rs b/quickwit/quickwit-search/src/split_warmup_memory.rs index c0c13501710..7931b51306c 100644 --- a/quickwit/quickwit-search/src/split_warmup_memory.rs +++ b/quickwit/quickwit-search/src/split_warmup_memory.rs @@ -32,7 +32,7 @@ const GROWTH_DENOMINATOR: u64 = 10; /// Warmup memory of a single split search. /// -/// Shared (`Arc`) between the split's `SearchPermit` and its `CachingDirectory`, +/// Shared (`Arc`) between the split's `SearchPermit` and its `SplitDirectory`, /// which reserves memory before each cache miss. The reservation is freed when the last of them /// is dropped, so it lives as long as the cache that holds the warmup data. pub(crate) struct SplitWarmupMemory { diff --git a/quickwit/quickwit-search/src/storage_cache_layer_tests.rs b/quickwit/quickwit-search/src/storage_cache_layer_tests.rs index e7a6d6ebc4b..5386a11390a 100644 --- a/quickwit/quickwit-search/src/storage_cache_layer_tests.rs +++ b/quickwit/quickwit-search/src/storage_cache_layer_tests.rs @@ -18,8 +18,7 @@ use std::sync::Arc; use quickwit_config::SearcherConfig; use quickwit_proto::search::SplitIdAndFooterOffsets; use quickwit_storage::{ - CountingStorage, DownloadCounters, OwnedBytes, PutPayload, RamStorageBuilder, - SplitPayloadBuilder, Storage, StorageResolver, + OwnedBytes, PutPayload, RamStorageBuilder, SplitPayloadBuilder, Storage, StorageResolver, }; use crate::SearcherContext; @@ -30,18 +29,18 @@ const BODY_FILE: &str = "segment.fast"; const BODY_BYTES: &[u8] = b"FASTDATA"; const HOTCACHE_BYTES: &[u8] = b"HOT"; -struct SplitBundle { +struct TestSplit { split_bytes: OwnedBytes, footer_offsets: SplitIdAndFooterOffsets, } -async fn build_split() -> SplitBundle { +async fn build_split() -> TestSplit { let mut builder = SplitPayloadBuilder::default(); builder.add_payload(BODY_FILE.to_string(), Box::new(BODY_BYTES.to_vec())); let payload = builder.finalize(HOTCACHE_BYTES).unwrap(); let footer_range = payload.footer_range.clone(); let split_bytes = payload.read_all().await.unwrap(); - SplitBundle { + TestSplit { split_bytes, footer_offsets: SplitIdAndFooterOffsets { split_id: SPLIT_ID.to_string(), @@ -56,18 +55,19 @@ fn split_file_name() -> String { format!("{SPLIT_ID}.split") } -fn counted_split_storage(split_bytes: &OwnedBytes) -> (Arc, Arc) { - let ram = RamStorageBuilder::default() - .put(&split_file_name(), split_bytes.as_slice()) - .build(); - CountingStorage::instrument_storage(Arc::new(ram)) +fn split_storage(split_bytes: &OwnedBytes) -> Arc { + Arc::new( + RamStorageBuilder::default() + .put(&split_file_name(), split_bytes.as_slice()) + .build(), + ) } #[tokio::test] async fn test_legacy_budgets_cache_footer_and_body_without_disk() { let split = build_split().await; let offsets = &split.footer_offsets; - let (storage, counters) = counted_split_storage(&split.split_bytes); + let storage = split_storage(&split.split_bytes); for enabled in [false, true] { let config: SearcherConfig = serde_json::from_value(serde_json::json!({ "fast_field_cache": 0, @@ -83,21 +83,17 @@ async fn test_legacy_budgets_cache_footer_and_body_without_disk() { .unwrap(); } assert_eq!(context.storage_cache_opt.is_some(), enabled); - let reads_before = counters.snapshot().1; for num_reads in 1..=2 { - let (bytes_before_footer, reads_before_footer) = counters.snapshot(); - let (hotcache, bundle) = open_split_bundle(&context, storage.clone(), offsets) - .await - .unwrap(); + let reader = context.split_storage_reader(storage.clone()); + let counters = reader.download_counters().clone(); + let (hotcache, bundle) = open_split_bundle(reader, offsets).await.unwrap(); assert_eq!(hotcache.as_slice(), HOTCACHE_BYTES); - let expected_footer_reads = u64::from(!enabled || num_reads == 1); + let expected_reads = u64::from(!enabled || num_reads == 1); assert_eq!( counters.snapshot(), ( - bytes_before_footer - + (offsets.split_footer_end - offsets.split_footer_start) - * expected_footer_reads, - reads_before_footer + expected_footer_reads, + (offsets.split_footer_end - offsets.split_footer_start) * expected_reads, + expected_reads, ) ); assert_eq!( @@ -108,10 +104,7 @@ async fn test_legacy_budgets_cache_footer_and_body_without_disk() { .as_slice(), BODY_BYTES ); - assert_eq!( - counters.snapshot().1 - reads_before, - if enabled { 2 } else { 2 * num_reads } - ); + assert_eq!(counters.snapshot().1, 2 * expected_reads); } } } @@ -123,7 +116,7 @@ mod disk_tests { use bytesize::ByteSize; use quickwit_config::{SplitCacheLimits, StorageCacheConfig}; - use quickwit_storage::{SearchSplitCache, open_storage_cache, wrap_storage_with_storage_cache}; + use quickwit_storage::{SearchSplitCache, SplitStorageReader, open_storage_cache}; use super::*; @@ -151,12 +144,12 @@ mod disk_tests { let cache_dir = tempfile::tempdir().unwrap(); let cache = open_cache(cache_dir.path()).await; let context = context_with_storage_cache(cache.clone()); - let (counted, counters) = counted_split_storage(&split.split_bytes); - - let (hotcache, bundle) = - open_split_bundle(&context, counted.clone(), &split.footer_offsets) - .await - .unwrap(); + let storage = split_storage(&split.split_bytes); + let reader = context.split_storage_reader(storage.clone()); + let counters = reader.download_counters().clone(); + let (hotcache, bundle) = open_split_bundle(reader, &split.footer_offsets) + .await + .unwrap(); assert_eq!(hotcache.as_slice(), HOTCACHE_BYTES); assert_eq!( counters.snapshot().1, @@ -182,11 +175,13 @@ mod disk_tests { // Another searcher context shares this `storage_cache` and reuses its cached footer. let fresh_context = context_with_storage_cache(cache); - let (hotcache, _bundle) = open_split_bundle(&fresh_context, counted, &split.footer_offsets) + let fresh_reader = fresh_context.split_storage_reader(storage); + let fresh_counters = fresh_reader.download_counters().clone(); + let (hotcache, _bundle) = open_split_bundle(fresh_reader, &split.footer_offsets) .await .unwrap(); assert_eq!(hotcache.as_slice(), HOTCACHE_BYTES); - assert_eq!(counters.snapshot().1, 2); + assert_eq!(fresh_counters.snapshot().1, 0); } #[tokio::test] @@ -215,8 +210,10 @@ mod disk_tests { let mut context = SearcherContext::new_without_invoker(SearcherConfig::default(), Some(split_cache)); context.storage_cache_opt = Some(storage_cache); - let (counted, counters) = counted_split_storage(&split.split_bytes); - let (_hotcache, bundle) = open_split_bundle(&context, counted, &split.footer_offsets) + let storage = split_storage(&split.split_bytes); + let reader = context.split_storage_reader(storage); + let counters = reader.download_counters().clone(); + let (_hotcache, bundle) = open_split_bundle(reader, &split.footer_offsets) .await .unwrap(); assert_eq!( @@ -238,16 +235,19 @@ mod disk_tests { let split = build_split().await; let cache_dir = tempfile::tempdir().unwrap(); let cache = open_cache(cache_dir.path()).await; - let (counted, counters) = counted_split_storage(&split.split_bytes); - let cached_storage = wrap_storage_with_storage_cache(cache.clone(), counted.clone()); - cached_storage + let storage = split_storage(&split.split_bytes); + let cached_reader = + SplitStorageReader::new(storage.clone()).with_storage_cache(cache.clone()); + cached_reader .get_slice(Path::new(&split_file_name()), 0..split.split_bytes.len()) .await .unwrap(); - assert_eq!(counters.snapshot().1, 1); + assert_eq!(cached_reader.download_counters().snapshot().1, 1); let context = context_with_storage_cache(cache); - let (_, bundle) = open_split_bundle(&context, counted, &split.footer_offsets) + let reader = context.split_storage_reader(storage); + let counters = reader.download_counters().clone(); + let (_, bundle) = open_split_bundle(reader, &split.footer_offsets) .await .unwrap(); assert_eq!( @@ -260,7 +260,7 @@ mod disk_tests { ); assert_eq!( counters.snapshot().1, - 3, + 2, "footer and body require their own exact slices despite a covering cached slice" ); } diff --git a/quickwit/quickwit-storage/Cargo.toml b/quickwit/quickwit-storage/Cargo.toml index 4cfd899ac23..ffae9d7a119 100644 --- a/quickwit/quickwit-storage/Cargo.toml +++ b/quickwit/quickwit-storage/Cargo.toml @@ -25,18 +25,16 @@ hyper = { workspace = true } itertools = { workspace = true, optional = true } lru = { workspace = true } md5 = { workspace = true } -mini-moka = { workspace = true } mixtrics = { workspace = true } mockall = { workspace = true, optional = true } percent-encoding = { workspace = true } pin-project = { workspace = true } -quick_cache = { workspace = true } regex = { workspace = true } -rustc-hash = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } stable_deref_trait = { workspace = true } tantivy = { workspace = true } +tantivy-common = { workspace = true } tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["test-util"] } @@ -70,7 +68,6 @@ http = { workspace = true } metrics = { workspace = true } metrics-util = { workspace = true } mockall = { workspace = true } -proptest = { workspace = true } # `default-features = false` to make sure we get HTTPS from OpenDAL's requested features reqwest = { version = "0.13", default-features = false } # Used by the HTTPS TLS regression test to inject a custom reqwest client via diff --git a/quickwit/quickwit-storage/src/cache/base_cache.rs b/quickwit/quickwit-storage/src/cache/base_cache.rs deleted file mode 100644 index 8ac6e11f573..00000000000 --- a/quickwit/quickwit-storage/src/cache/base_cache.rs +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::borrow::Borrow; -use std::hash::Hash; -use std::sync::{Arc, Weak}; -use std::time::Duration; - -use bytesize::ByteSize; -use lru::LruCache; -use mini_moka::sync::Cache as MokaCache; -use quick_cache::unsync::Cache as QuickCache; -use quickwit_config::CachePolicy; -use tokio::time::Instant; -use tracing::{error, warn}; - -use crate::OwnedBytes; -use crate::cache::stored_item::{StoredItem, ValueLen}; -use crate::metrics::SingleCacheMetrics; - -/// We do not evict anything that has been accessed in the last 60s. -/// -/// The goal is to behave better on scan access patterns, without being as aggressive as -/// using a MRU strategy. -/// -/// TLDR is: -/// -/// If two items have been access in the last 60s it is not really worth considering the -/// latter too be more recent than the previous and do an eviction. -/// The difference is not significant enough to raise the probability of its future access. -/// -/// On the other hand, for very large queries involving enough data to saturate the cache, -/// we are facing a scanning pattern. If variations of this query is repeated over and over -/// a regular LRU eviction policy would yield a hit rate of 0. -pub(crate) const LRU_MIN_TIME_SINCE_LAST_ACCESS: Duration = Duration::from_mins(1); - -// A fake entry inside a cache, which the cache believe to be of the given size -#[derive(Clone)] -pub(crate) struct FakeCacheEntry(pub usize); - -impl ValueLen for FakeCacheEntry { - fn len(&self) -> usize { - self.0 - } -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Capacity { - Unlimited, - InBytes(usize), -} - -impl Capacity { - fn exceeds_capacity(&self, num_bytes: usize) -> bool { - match *self { - Capacity::Unlimited => false, - Capacity::InBytes(capacity_in_bytes) => num_bytes > capacity_in_bytes, - } - } -} - -pub(crate) enum AnyCache { - Lru(Lru), - S3Fifo(S3Fifo), - TinyLfu(TinyLfu), -} - -impl - AnyCache -{ - pub fn from_policy_and_capacity( - policy: CachePolicy, - capacity: ByteSize, - cache_metrics: SingleCacheMetrics, - ) -> Self { - match policy { - CachePolicy::Lru => AnyCache::Lru(Lru::with_capacity( - Capacity::InBytes(capacity.as_u64().try_into().unwrap_or(usize::MAX)), - cache_metrics, - )), - CachePolicy::S3Fifo => { - AnyCache::S3Fifo(S3Fifo::with_capacity(capacity.as_u64(), cache_metrics)) - } - CachePolicy::TinyLfu => { - AnyCache::TinyLfu(TinyLfu::with_capacity(capacity.as_u64(), cache_metrics)) - } - } - } - pub fn unbounded(cache_metrics: SingleCacheMetrics) -> Self { - AnyCache::Lru(Lru::with_capacity(Capacity::Unlimited, cache_metrics)) - } - - pub fn get(&mut self, cache_key: &Q) -> Option - where - K: Borrow, - Arc: Borrow, - Q: Hash + Eq + ?Sized, - { - match self { - AnyCache::Lru(lru) => lru.get(cache_key), - AnyCache::S3Fifo(s3fifo) => s3fifo.get(cache_key), - AnyCache::TinyLfu(tiny_lfu) => tiny_lfu.get(cache_key), - } - } - pub fn put(&mut self, key: K, value: V) -> bool { - match self { - AnyCache::Lru(lru) => lru.put(key, value), - AnyCache::S3Fifo(s3fifo) => s3fifo.put(key, value), - AnyCache::TinyLfu(tiny_lfu) => tiny_lfu.put(key, value), - } - } -} - -pub struct Lru { - lru_cache: LruCache>, - num_items: usize, - num_bytes: u64, - capacity: Capacity, - cache_metrics: SingleCacheMetrics, -} - -impl Drop for Lru { - fn drop(&mut self) { - // we don't count this toward evicted entries, as we are clearing the whole cache - self.cache_metrics - .in_cache_count - .dec_by(self.num_items as f64); - self.cache_metrics - .in_cache_num_bytes - .dec_by(self.num_bytes as f64); - } -} - -impl Lru { - /// Creates a new NeedMutSliceCache with the given capacity. - fn with_capacity(capacity: Capacity, cache_metrics: SingleCacheMetrics) -> Self { - Lru { - // The limit will be decided by the amount of memory in the cache, - // not the number of items in the cache. - // Enforcing this limit is done in the `NeedMutCache` impl. - lru_cache: LruCache::unbounded(), - num_items: 0, - num_bytes: 0, - capacity, - cache_metrics, - } - } - - fn record_item(&mut self, num_bytes: u64) { - self.num_items += 1; - self.num_bytes += num_bytes; - self.cache_metrics.in_cache_count.inc(); - self.cache_metrics - .in_cache_num_bytes - .inc_by(num_bytes as f64); - } - - fn drop_item(&mut self, num_bytes: u64) { - self.num_items -= 1; - self.num_bytes -= num_bytes; - self.cache_metrics.in_cache_count.dec(); - self.cache_metrics - .in_cache_num_bytes - .dec_by(num_bytes as f64); - self.cache_metrics.evict_num_items.inc(); - self.cache_metrics.evict_num_bytes.inc_by(num_bytes); - } - - pub fn get(&mut self, cache_key: &Q) -> Option - where - K: Borrow, - Q: Hash + Eq + ?Sized, - { - let item_opt = self.lru_cache.get_mut(cache_key); - if let Some(item) = item_opt { - self.cache_metrics.hits_num_items.inc(); - self.cache_metrics.hits_num_bytes.inc_by(item.len() as u64); - Some(item.payload()) - } else { - self.cache_metrics.misses_num_items.inc(); - None - } - } - - /// Attempt to put the given amount of data in the cache. - /// This may fail silently if the owned_bytes slice is larger than the cache - /// capacity. - fn put(&mut self, key: K, bytes: V) -> bool { - if self.capacity.exceeds_capacity(bytes.len()) { - // The value does not fit in the cache. We simply don't store it. - if self.capacity != Capacity::InBytes(0) { - warn!( - capacity_in_bytes = ?self.capacity, - len = bytes.len(), - "Downloaded a byte slice larger than the cache capacity." - ); - } - return false; - } - if let Some(previous_data) = self.lru_cache.pop(&key) { - self.drop_item(previous_data.len() as u64); - } - - let now = Instant::now(); - while self - .capacity - .exceeds_capacity(self.num_bytes as usize + bytes.len()) - { - if let Some((_, candidate_for_eviction)) = self.lru_cache.peek_lru() { - let time_since_last_access = - now.duration_since(candidate_for_eviction.last_access_time()); - if time_since_last_access < LRU_MIN_TIME_SINCE_LAST_ACCESS { - // It is not worth doing an eviction. - // TODO: It is sub-optimal that we might have needlessly evicted items in this - // loop before just returning. - return false; - } - } - if let Some((_, bytes)) = self.lru_cache.pop_lru() { - self.drop_item(bytes.len() as u64); - } else { - error!( - "Logical error. Even after removing all of the items in the cache the \ - capacity is insufficient. This case is guarded against and should never \ - happen." - ); - return false; - } - } - self.record_item(bytes.len() as u64); - self.lru_cache.put(key, StoredItem::new(bytes, now)); - true - } -} - -// actually, quick_cache is a Clock-PRO, not a S3-fifo contrary to what quick-cache and Moka's -// readme says. While both are clearly distinct (one being clock-based, the other being fifo -// based), they are not too disimilar in term of strenght/weaknesses. -pub struct S3Fifo { - cache: - QuickCache, - capacity: u64, - cache_metrics: SingleCacheMetrics, -} - -impl Drop for S3Fifo { - fn drop(&mut self) { - // we don't count this toward evicted entries, as we are clearing the whole cache - self.cache_metrics - .in_cache_count - .dec_by(self.cache.len() as f64); - self.cache_metrics - .in_cache_num_bytes - .dec_by(self.cache.weight() as f64); - } -} - -struct QuickCacheWeighter; -impl quick_cache::Weighter for QuickCacheWeighter { - fn weight(&self, _key: &K, value: &V) -> u64 { - value.len() as u64 - } -} - -struct QuickCacheLifecycle; -#[derive(Default)] -struct QuickCacheQueryEffect { - count: u64, - bytes: u64, -} -impl quick_cache::Lifecycle for QuickCacheLifecycle { - type RequestState = QuickCacheQueryEffect; - - fn on_evict(&self, state: &mut Self::RequestState, _key: K, val: V) { - state.count += 1; - state.bytes += val.len() as u64; - } -} - -impl S3Fifo { - /// Creates a new NeedMutSliceCache with the given capacity. - fn with_capacity(capacity: u64, cache_metrics: SingleCacheMetrics) -> Self { - S3Fifo { - cache: QuickCache::with( - (capacity / (128 * 1024)) as usize, - capacity, - QuickCacheWeighter, - quick_cache::DefaultHashBuilder::default(), - QuickCacheLifecycle, - ), - capacity, - cache_metrics, - } - } - - pub fn get(&mut self, cache_key: &Q) -> Option - where - K: Borrow, - Q: Hash + Eq + ?Sized, - { - let item_opt = self.cache.get(cache_key); - if let Some(item) = item_opt { - self.cache_metrics.hits_num_items.inc(); - self.cache_metrics.hits_num_bytes.inc_by(item.len() as u64); - Some(item.clone()) - } else { - self.cache_metrics.misses_num_items.inc(); - None - } - } - - /// Attempt to put the given amount of data in the cache. - /// This may fail silently if the owned_bytes slice is larger than the cache - /// capacity. - fn put(&mut self, key: K, value: V) -> bool { - if self.capacity < value.len() as u64 { - // The value does not fit in the cache. We simply don't store it. - if self.capacity != 0 { - warn!( - capacity_in_bytes = ?self.capacity, - len = value.len(), - "Downloaded a byte slice larger than the cache capacity." - ); - } - return false; - } - - self.cache_metrics.in_cache_count.inc(); - self.cache_metrics - .in_cache_num_bytes - .inc_by(value.len() as f64); - let mut evicted = QuickCacheQueryEffect::default(); - self.cache.insert_with_lifecycle(key, value, &mut evicted); - self.cache_metrics - .in_cache_count - .dec_by(evicted.count as f64); - self.cache_metrics - .in_cache_num_bytes - .dec_by(evicted.bytes as f64); - self.cache_metrics.evict_num_items.inc_by(evicted.count); - self.cache_metrics.evict_num_bytes.inc_by(evicted.bytes); - true - } -} - -// We don't make this value Clone to ensure each item is dropped only once -struct CapacityTracker { - item: V, - cache_metrics: Weak, -} - -impl Drop for CapacityTracker { - fn drop(&mut self) { - if let Some(cache_metrics) = self.cache_metrics.upgrade() { - cache_metrics.in_cache_count.dec(); - cache_metrics - .in_cache_num_bytes - .dec_by(self.item.len() as f64); - cache_metrics.evict_num_items.inc(); - cache_metrics.evict_num_bytes.inc_by(self.item.len() as u64); - } - } -} - -pub struct TinyLfu { - // this field is put first so it's dropped before the cache - // we use that to not count removed entries as "evicted", by - // calling CapacityTracker's Drop only after its Weak has expired. - cache_metrics: Arc, - - // we store an Arc because moka does a lot of internal cloning, and it's hard to not double - // evict/forget to count eviction otherwise - cache: MokaCache>>, - capacity: u64, -} - -impl Drop for TinyLfu { - fn drop(&mut self) { - // we don't count this toward evicted entries, as we are clearing the whole cache - self.cache_metrics - .in_cache_count - .dec_by(self.cache.entry_count() as f64); - self.cache_metrics - .in_cache_num_bytes - .dec_by(self.cache.weighted_size() as f64); - } -} - -impl - TinyLfu -{ - /// Creates a new NeedMutSliceCache with the given capacity. - fn with_capacity(capacity: u64, cache_metrics: SingleCacheMetrics) -> Self { - TinyLfu { - cache: MokaCache::builder() - .max_capacity(capacity) - .weigher(|_k, v: &Arc>| { - v.item.len().try_into().unwrap_or(u32::MAX) - }) - .build(), - capacity, - cache_metrics: cache_metrics.into(), - } - } - - pub fn get(&mut self, cache_key: &Q) -> Option - where - Arc: Borrow, - Q: Hash + Eq + ?Sized, - { - let item_opt = self.cache.get(cache_key); - if let Some(item) = item_opt { - self.cache_metrics.hits_num_items.inc(); - self.cache_metrics - .hits_num_bytes - .inc_by(item.item.len() as u64); - Some(item.item.clone()) - } else { - self.cache_metrics.misses_num_items.inc(); - None - } - } - - /// Attempt to put the given amount of data in the cache. - /// This may fail silently if the owned_bytes slice is larger than the cache - /// capacity. - fn put(&mut self, key: K, value: V) -> bool { - if self.capacity < value.len() as u64 { - // The value does not fit in the cache. We simply don't store it. - if self.capacity != 0 { - warn!( - capacity_in_bytes = ?self.capacity, - len = value.len(), - "Downloaded a byte slice larger than the cache capacity." - ); - } - return false; - } - - self.cache_metrics.in_cache_count.inc(); - self.cache_metrics - .in_cache_num_bytes - .inc_by(value.len() as f64); - self.cache.insert( - key, - CapacityTracker { - item: value, - cache_metrics: Arc::downgrade(&self.cache_metrics), - } - .into(), - ); - true - } -} diff --git a/quickwit/quickwit-storage/src/cache/memory_sized_cache.rs b/quickwit/quickwit-storage/src/cache/memory_sized_cache.rs deleted file mode 100644 index 767b198ac6d..00000000000 --- a/quickwit/quickwit-storage/src/cache/memory_sized_cache.rs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::borrow::Borrow; -use std::hash::Hash; -use std::ops::Range; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; - -use quickwit_config::CacheConfig; - -use crate::OwnedBytes; -use crate::cache::base_cache::{AnyCache, FakeCacheEntry}; -use crate::cache::slice_address::{SliceAddress, SliceAddressKey, SliceAddressRef}; -use crate::metrics::CacheMetrics; - -struct CacheState { - cache: AnyCache, - virtual_caches: Vec>, -} - -impl CacheState { - fn from_config(cache_config: &CacheConfig, cache_counters: &'static CacheMetrics) -> Self { - let cache = AnyCache::from_policy_and_capacity( - cache_config.policy(), - cache_config.memory_capacity(), - cache_counters.cache_metrics.clone(), - ); - let virtual_caches = cache_config - .virtual_caches - .iter() - .cloned() - .map(|mut virtual_cache_config| { - AnyCache::from_policy_and_capacity( - virtual_cache_config.policy_for_virtual_cache(cache_config.policy()), - virtual_cache_config - .memory_capacity_for_virtual_cache(cache_config.memory_capacity()), - cache_counters.virtual_cache(&virtual_cache_config), - ) - }) - .collect(); - CacheState { - cache, - virtual_caches, - } - } - - fn infinite(cache_counters: &'static CacheMetrics) -> Self { - CacheState { - cache: AnyCache::unbounded(cache_counters.cache_metrics.clone()), - // there is no point in having virtual caches for an unbounded cache - virtual_caches: Vec::new(), - } - } - - pub fn get(&mut self, cache_key: &Q) -> Option - where - K: Borrow, - Arc: Borrow, - Q: Hash + Eq + ?Sized, - { - for virtual_cache in &mut self.virtual_caches { - // we simulate an access on all virtual caches - virtual_cache.get(cache_key); - } - self.cache.get(cache_key) - } - - fn put(&mut self, key: K, bytes: OwnedBytes) -> bool { - for virtual_cache in &mut self.virtual_caches { - // we simulate an access on all virtual caches - virtual_cache.put(key.clone(), FakeCacheEntry(bytes.len())); - } - - self.cache.put(key, bytes) - } -} - -/// A simple in-resident memory slice cache. -pub struct MemorySizedCache { - inner: Mutex>, -} - -impl MemorySizedCache { - /// Creates an slice cache with the given capacity. - pub fn from_config(cache_config: &CacheConfig, cache_counters: &'static CacheMetrics) -> Self { - MemorySizedCache { - inner: Mutex::new(CacheState::from_config(cache_config, cache_counters)), - } - } - - /// Creates a slice cache that never removes any entry. - pub fn with_infinite_capacity(cache_counters: &'static CacheMetrics) -> Self { - MemorySizedCache { - inner: Mutex::new(CacheState::infinite(cache_counters)), - } - } - - /// If available, returns the cached view of the slice. - pub fn get(&self, cache_key: &Q) -> Option - where - K: Borrow, - Arc: Borrow, - Q: Hash + Eq + ?Sized, - { - self.inner.lock().unwrap().get(cache_key) - } - - /// Attempts to put the data in the cache and returns whether it was admitted. - pub fn put(&self, val: K, bytes: OwnedBytes) -> bool { - self.inner.lock().unwrap().put(val, bytes) - } -} - -impl MemorySizedCache { - /// If available, returns the cached view of the slice. - pub fn get_slice(&self, path: &Path, byte_range: Range) -> Option { - let slice_address_ref = SliceAddressRef { path, byte_range }; - self.get(&slice_address_ref as &dyn SliceAddressKey) - } - - /// Attempt to put the given amount of data in the cache. - /// This may fail silently if the owned_bytes slice is larger than the cache - /// capacity. - pub fn put_slice(&self, path: PathBuf, byte_range: Range, bytes: OwnedBytes) { - let slice_address = SliceAddress { path, byte_range }; - self.put(slice_address, bytes); - } -} - -#[cfg(test)] -mod tests { - use bytesize::ByteSize; - - use super::*; - use crate::cache::base_cache::LRU_MIN_TIME_SINCE_LAST_ACCESS; - use crate::metrics::CACHE_METRICS_FOR_TESTS; - - #[tokio::test] - async fn test_cache_edge_condition() { - tokio::time::pause(); - let cache = MemorySizedCache::::from_config( - &ByteSize::b(5).into(), - &CACHE_METRICS_FOR_TESTS, - ); - { - let data = OwnedBytes::new(&b"abc"[..]); - cache.put("3".to_string(), data); - assert_eq!(cache.get(&"3".to_string()).unwrap(), &b"abc"[..]); - } - { - let data = OwnedBytes::new(&b"de"[..]); - cache.put("2".to_string(), data); - // our first entry should still be here. - assert_eq!(cache.get(&"3".to_string()).unwrap(), &b"abc"[..]); - assert_eq!(cache.get(&"2".to_string()).unwrap(), &b"de"[..]); - } - { - let data = OwnedBytes::new(&b"fghij"[..]); - assert!(!cache.put("5".to_string(), data)); - // Eviction should not happen, because all items in cache are too young. - assert!(cache.get(&"5".to_string()).is_none()); - } - tokio::time::advance(LRU_MIN_TIME_SINCE_LAST_ACCESS.mul_f32(1.1f32)).await; - { - let data = OwnedBytes::new(&b"fghij"[..]); - assert!(cache.put("5".to_string(), data)); - assert_eq!(cache.get(&"5".to_string()).unwrap(), &b"fghij"[..]); - // our two first entries should have be removed from the cache - assert!(cache.get(&"2".to_string()).is_none()); - assert!(cache.get(&"3".to_string()).is_none()); - } - tokio::time::advance(LRU_MIN_TIME_SINCE_LAST_ACCESS.mul_f32(1.1f32)).await; - { - let data = OwnedBytes::new(&b"klmnop"[..]); - assert!(!cache.put("6".to_string(), data)); - // The entry put should have been dismissed as it is too large for the cache - assert!(cache.get(&"6".to_string()).is_none()); - // The previous entry should however be remaining. - assert_eq!(cache.get(&"5".to_string()).unwrap(), &b"fghij"[..]); - } - } - - #[test] - fn test_cache_edge_unlimited_capacity() { - let cache = MemorySizedCache::with_infinite_capacity(&CACHE_METRICS_FOR_TESTS); - { - let data = OwnedBytes::new(&b"abc"[..]); - cache.put("3".to_string(), data); - assert_eq!(cache.get(&"3".to_string()).unwrap(), &b"abc"[..]); - } - { - let data = OwnedBytes::new(&b"de"[..]); - cache.put("2".to_string(), data); - assert_eq!(cache.get(&"3".to_string()).unwrap(), &b"abc"[..]); - assert_eq!(cache.get(&"2".to_string()).unwrap(), &b"de"[..]); - } - } - - #[test] - fn test_cache() { - let cache = - MemorySizedCache::from_config(&ByteSize::kb(10).into(), &CACHE_METRICS_FOR_TESTS); - assert!(cache.get(&"hello.seg").is_none()); - let data = OwnedBytes::new(&b"werwer"[..]); - cache.put("hello.seg", data); - assert_eq!(cache.get(&"hello.seg").unwrap(), &b"werwer"[..]); - } - - #[test] - fn test_cache_no_cache() { - let cache = - MemorySizedCache::from_config(&CacheConfig::no_cache(), &CACHE_METRICS_FOR_TESTS); - assert!(cache.get(&"hello.seg").is_none()); - let data = OwnedBytes::new(&b"werwer"[..]); - assert!(!cache.put("hello.seg", data)); - assert!(cache.get(&"hello.seg").is_none()); - } -} diff --git a/quickwit/quickwit-storage/src/cache/mod.rs b/quickwit/quickwit-storage/src/cache/mod.rs deleted file mode 100644 index 1f0331779f6..00000000000 --- a/quickwit/quickwit-storage/src/cache/mod.rs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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. - -mod base_cache; -mod byte_range_cache; -mod memory_sized_cache; -mod slice_address; -mod storage_with_cache; -mod stored_item; - -use std::ops::Range; -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use async_trait::async_trait; -pub use storage_with_cache::StorageWithCache; -use tokio::io::AsyncRead; - -pub use self::byte_range_cache::{ByteRangeCache, FileByteRangeCache}; -pub use self::memory_sized_cache::MemorySizedCache; -use crate::{OwnedBytes, Storage}; - -/// Wraps the given directory with a slice cache that is actually global -/// to quickwit. -/// -/// FIXME The current approach is quite horrible in that: -/// - it uses a global -/// - it relies on the idea that all of the files we attempt to cache have universally unique names. -/// It happens to be true today, but this might be very error prone in the future. -pub fn wrap_storage_with_cache( - long_term_cache: Arc, - storage: Arc, -) -> Arc { - Arc::new(StorageWithCache { - storage, - cache: long_term_cache, - }) -} - -/// The `StorageCache` trait is the abstraction used to describe the caching logic -/// used in front of a storage. See `StorageWithCache`. -#[cfg_attr(any(test, feature = "testsuite"), mockall::automock)] -#[async_trait] -pub trait StorageCache: Send + Sync + 'static { - /// Try to get a slice from the cache. - async fn get(&self, path: &Path, byte_range: Range) -> Option; - /// Try to stream a slice from the cache. Disk caches can read on demand. - async fn get_slice_stream( - &self, - path: &Path, - byte_range: Range, - ) -> Option> { - let bytes = self.get(path, byte_range).await?; - Some(Box::new(std::io::Cursor::new(bytes))) - } - /// Try to get the entire file. - async fn get_all(&self, path: &Path) -> Option; - /// Put a slice of data into the cache. - async fn put(&self, path: PathBuf, byte_range: Range, bytes: OwnedBytes); - /// Put an entire file into the cache. - async fn put_all(&self, path: PathBuf, bytes: OwnedBytes); -} diff --git a/quickwit/quickwit-storage/src/cache/slice_address.rs b/quickwit/quickwit-storage/src/cache/slice_address.rs deleted file mode 100644 index b64e59d2148..00000000000 --- a/quickwit/quickwit-storage/src/cache/slice_address.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::borrow::Borrow; -use std::hash::{Hash, Hasher}; -use std::ops::Range; -use std::path::{Path, PathBuf}; - -#[derive(Hash, Clone, Debug, Eq, PartialEq)] -pub struct SliceAddress { - pub path: PathBuf, - pub byte_range: Range, -} - -// ------------------------------------------------------------ -// The following struct exists to make it possible to -// fetch a slice from a cache without cloning PathBuf. - -// The trick is described in https://github.com/sunshowers-code/borrow-complex-key-example/blob/main/src/lib.rs - -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub(crate) struct SliceAddressRef<'a> { - pub path: &'a Path, - pub byte_range: Range, -} - -pub(crate) trait SliceAddressKey { - fn key(&self) -> SliceAddressRef<'_>; -} - -impl SliceAddressKey for SliceAddress { - fn key(&self) -> SliceAddressRef<'_> { - SliceAddressRef { - path: self.path.as_path(), - byte_range: self.byte_range.clone(), - } - } -} - -impl SliceAddressKey for SliceAddressRef<'_> { - fn key(&self) -> SliceAddressRef<'_> { - self.clone() - } -} - -impl<'a> Borrow for std::sync::Arc { - fn borrow(&self) -> &(dyn SliceAddressKey + 'a) { - &**self - } -} - -impl<'a> Borrow for SliceAddress { - fn borrow(&self) -> &(dyn SliceAddressKey + 'a) { - self - } -} -impl PartialEq for dyn SliceAddressKey + '_ { - fn eq(&self, other: &Self) -> bool { - self.key().eq(&other.key()) - } -} - -impl Eq for dyn SliceAddressKey + '_ {} - -impl Hash for dyn SliceAddressKey + '_ { - fn hash(&self, state: &mut H) { - self.key().hash(state) - } -} diff --git a/quickwit/quickwit-storage/src/cache/storage_with_cache.rs b/quickwit/quickwit-storage/src/cache/storage_with_cache.rs deleted file mode 100644 index 5d6af2c6753..00000000000 --- a/quickwit/quickwit-storage/src/cache/storage_with_cache.rs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::fmt; -use std::ops::Range; -use std::path::Path; -use std::sync::Arc; - -use async_trait::async_trait; -use quickwit_common::uri::Uri; -use tokio::io::AsyncRead; - -use crate::cache::StorageCache; -use crate::storage::SendableAsync; -use crate::{BulkDeleteError, ListObjectsStream, OwnedBytes, Storage, StorageResult}; - -/// Use with care, StorageWithCache is read-only. -/// Streaming reads reuse cache hits and forward misses without insertion. -pub struct StorageWithCache { - pub storage: Arc, - pub cache: Arc, -} - -impl fmt::Debug for StorageWithCache { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("StorageWithCache").finish() - } -} - -#[async_trait] -impl Storage for StorageWithCache { - async fn check_connectivity(&self) -> anyhow::Result<()> { - self.storage.check_connectivity().await - } - - async fn put( - &self, - path: &Path, - _payload: Box, - ) -> crate::StorageResult<()> { - unimplemented!("StorageWithCache is readonly. Failed to put {:?}", path) - } - - async fn copy_to(&self, path: &Path, output: &mut dyn SendableAsync) -> StorageResult<()> { - self.storage.copy_to(path, output).await - } - - async fn get_slice(&self, path: &Path, byte_range: Range) -> StorageResult { - if let Some(bytes) = self.cache.get(path, byte_range.clone()).await { - Ok(bytes) - } else { - let bytes = self.storage.get_slice(path, byte_range.clone()).await?; - self.cache - .put(path.to_owned(), byte_range, bytes.clone()) - .await; - Ok(bytes) - } - } - - async fn get_slice_into( - &self, - path: &Path, - range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - if buffer.is_empty() { - return Ok(()); - } - // Use buffered reads so cache misses populate the cache. - let bytes = self.get_slice(path, range).await?; - buffer.copy_from_slice(&bytes); - Ok(()) - } - - async fn get_slice_stream( - &self, - path: &Path, - range: Range, - ) -> StorageResult> { - if let Some(reader) = self.cache.get_slice_stream(path, range.clone()).await { - return Ok(reader); - } - self.storage.get_slice_stream(path, range).await - } - - async fn get_all(&self, path: &Path) -> StorageResult { - if let Some(bytes) = self.cache.get_all(path).await { - Ok(bytes) - } else { - let bytes = self.storage.get_all(path).await?; - self.cache.put_all(path.to_owned(), bytes.clone()).await; - Ok(bytes) - } - } - - async fn delete(&self, path: &Path) -> StorageResult<()> { - unimplemented!("Failed to delete file `{path:?}`. `StorageWithCache` is read-only.") - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - unimplemented!("Failed to delete files `{paths:?}`. `StorageWithCache` is read-only.") - } - - fn list(&self, prefix: &Path) -> ListObjectsStream { - self.storage.list(prefix) - } - - async fn exists(&self, path: &Path) -> StorageResult { - self.storage.exists(path).await - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - self.storage.file_num_bytes(path).await - } - - fn uri(&self) -> &Uri { - self.storage.uri() - } -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::path::PathBuf; - use std::sync::Mutex; - - use super::*; - use crate::{MockStorage, MockStorageCache, OwnedBytes}; - - #[tokio::test] - async fn put_in_cache_test() { - let mut mock_storage = MockStorage::default(); - let mut mock_cache = MockStorageCache::default(); - let actual_cache: Arc>> = - Arc::new(Mutex::new(HashMap::new())); - - let cache1 = actual_cache.clone(); - mock_cache - .expect_get_all() - .times(2) - .returning(move |path| cache1.lock().unwrap().get(path).cloned()); - mock_cache - .expect_put_all() - .times(1) - .returning(move |path, data| { - let actual_cache = actual_cache.clone(); - actual_cache.lock().unwrap().insert(path, data); - }); - - mock_storage - .expect_get_all() - .times(1) - .returning(|_path| Ok(OwnedBytes::new(vec![1, 2, 3]))); - - let storage_with_cache = StorageWithCache { - storage: Arc::new(mock_storage), - cache: Arc::new(mock_cache), - }; - - let data1 = storage_with_cache - .get_all(Path::new("cool_file")) - .await - .unwrap(); - // hitting the cache - let data2 = storage_with_cache - .get_all(Path::new("cool_file")) - .await - .unwrap(); - assert_eq!(data1, data2); - } -} diff --git a/quickwit/quickwit-storage/src/cache/stored_item.rs b/quickwit/quickwit-storage/src/cache/stored_item.rs deleted file mode 100644 index 8d1af95c8fd..00000000000 --- a/quickwit/quickwit-storage/src/cache/stored_item.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 tantivy::directory::OwnedBytes; -use tokio::time::Instant; - -/// It is a bit overkill to put this in its own module, but I -/// wanted to ensure that no one would access payload without updating `last_access_time`. -pub(super) struct StoredItem { - last_access_time: Instant, - payload: V, -} - -impl StoredItem { - pub fn new(payload: V, now: Instant) -> Self { - StoredItem { - last_access_time: now, - payload, - } - } -} - -impl StoredItem { - pub fn payload(&mut self) -> V { - self.last_access_time = Instant::now(); - self.payload.clone() - } - - pub fn len(&self) -> usize { - self.payload.len() - } - - pub fn last_access_time(&self) -> Instant { - self.last_access_time - } -} - -pub(crate) trait ValueLen { - fn len(&self) -> usize; -} - -impl ValueLen for OwnedBytes { - fn len(&self) -> usize { - OwnedBytes::len(self) - } -} diff --git a/quickwit/quickwit-storage/src/counting_storage.rs b/quickwit/quickwit-storage/src/counting_storage.rs deleted file mode 100644 index ca54a34d791..00000000000 --- a/quickwit/quickwit-storage/src/counting_storage.rs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::ops::Range; -use std::path::Path; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; - -use async_trait::async_trait; -use quickwit_common::uri::Uri; -use tantivy::directory::OwnedBytes; -use tokio::io::AsyncRead; - -use crate::storage::SendableAsync; -use crate::{BulkDeleteError, ListObjectsStream, PutPayload, Storage, StorageResult}; - -/// Per-request download counters tracked by [`CountingStorage`]. -/// -/// `bytes` accumulates the size of every successfully fulfilled read; `requests` -/// counts each call to a read method. Counters are atomic so a single instance -/// can be shared across the wrapper clones used internally by lower storage -/// layers (`HotDirectory`, `BundleStorage`, etc.). -#[derive(Debug, Default)] -pub struct DownloadCounters { - bytes: AtomicU64, - requests: AtomicU64, -} - -impl DownloadCounters { - /// Snapshots the current counters as `(bytes, requests)`. - pub fn snapshot(&self) -> (u64, u64) { - ( - self.bytes.load(Ordering::Relaxed), - self.requests.load(Ordering::Relaxed), - ) - } - - fn record_read(&self, num_bytes: u64) { - self.bytes.fetch_add(num_bytes, Ordering::Relaxed); - self.requests.fetch_add(1, Ordering::Relaxed); - } -} - -/// Storage proxy that counts the bytes and number of read requests it serves. -/// -/// Wrap a base `Storage` with this proxy at the entry point of a request to -/// observe the per-request download volume. Cache hits (`storage_cache`, `split_cache`, -/// hotcache, short-lived cache) return before reaching this wrapper, so the counters -/// measure downloads from object storage. -/// -/// Write methods (`put`, `delete`, `bulk_delete`) and metadata methods -/// (`exists`, `file_num_bytes`, `check_connectivity`) are passed through -/// without counting; we only record reads that materialise data. -#[derive(Debug)] -pub struct CountingStorage { - inner: Arc, - counters: Arc, -} - -impl CountingStorage { - /// Wrap a storage object to count for download request and downloaded bytes. - pub fn instrument_storage( - inner: Arc, - ) -> (Arc, Arc) { - let counters = Arc::new(DownloadCounters::default()); - let instrumented_storage = Self { - inner, - counters: counters.clone(), - }; - (Arc::new(instrumented_storage), counters) - } -} - -#[async_trait] -impl Storage for CountingStorage { - async fn check_connectivity(&self) -> anyhow::Result<()> { - self.inner.check_connectivity().await - } - - async fn put(&self, path: &Path, payload: Box) -> StorageResult<()> { - self.inner.put(path, payload).await - } - - async fn copy_to(&self, path: &Path, output: &mut dyn SendableAsync) -> StorageResult<()> { - // We do not know the final byte count without intercepting the writer, - // so we conservatively count the request only. `copy_to` is not on the - // hot path of leaf search (only `get_slice` is), so this approximation - // is acceptable. - self.counters.requests.fetch_add(1, Ordering::Relaxed); - self.inner.copy_to(path, output).await - } - - async fn copy_to_file(&self, path: &Path, output_path: &Path) -> StorageResult { - let num_bytes = self.inner.copy_to_file(path, output_path).await?; - self.counters.record_read(num_bytes); - Ok(num_bytes) - } - - async fn get_slice(&self, path: &Path, range: Range) -> StorageResult { - let bytes = self.inner.get_slice(path, range).await?; - self.counters.record_read(bytes.len() as u64); - Ok(bytes) - } - - async fn get_slice_into( - &self, - path: &Path, - range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - self.inner.get_slice_into(path, range, buffer).await?; - self.counters.record_read(buffer.len() as u64); - Ok(()) - } - - async fn get_slice_stream( - &self, - path: &Path, - range: Range, - ) -> StorageResult> { - // We approximate the bytes by the requested range length on success. - // The stream may yield fewer bytes if the caller drops it early, but - // that is rare and the over-count is bounded by the requested range. - let range_len = range.len() as u64; - let stream = self.inner.get_slice_stream(path, range).await?; - self.counters.record_read(range_len); - Ok(stream) - } - - async fn get_all(&self, path: &Path) -> StorageResult { - let bytes = self.inner.get_all(path).await?; - self.counters.record_read(bytes.len() as u64); - Ok(bytes) - } - - async fn delete(&self, path: &Path) -> StorageResult<()> { - self.inner.delete(path).await - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - self.inner.bulk_delete(paths).await - } - - fn list(&self, prefix: &Path) -> ListObjectsStream { - self.inner.list(prefix) - } - - async fn exists(&self, path: &Path) -> StorageResult { - self.inner.exists(path).await - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - self.inner.file_num_bytes(path).await - } - - fn uri(&self) -> &Uri { - self.inner.uri() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::RamStorageBuilder; - - #[tokio::test] - async fn test_counting_storage_counts_get_slice() { - let inner = RamStorageBuilder::default() - .put("foo", b"hello world") - .build(); - let (storage, counters) = CountingStorage::instrument_storage(Arc::new(inner)); - - let bytes = storage.get_slice(Path::new("foo"), 0..5).await.unwrap(); - assert_eq!(bytes.as_slice(), b"hello"); - - let bytes = storage.get_slice(Path::new("foo"), 6..11).await.unwrap(); - assert_eq!(bytes.as_slice(), b"world"); - - let (download_num_bytes, download_num_requests) = counters.snapshot(); - assert_eq!(download_num_bytes, 10); - assert_eq!(download_num_requests, 2); - } - - #[tokio::test] - async fn test_counting_storage_counts_get_slice_into() { - let inner = RamStorageBuilder::default() - .put("foo", b"hello world") - .build(); - let (storage, counters) = CountingStorage::instrument_storage(Arc::new(inner)); - let mut buffer = [0; 5]; - storage - .get_slice_into(Path::new("foo"), 6..11, &mut buffer) - .await - .unwrap(); - assert_eq!(&buffer, b"world"); - assert_eq!(counters.snapshot(), (5, 1)); - assert!( - storage - .get_slice_into(Path::new("missing"), 0..5, &mut buffer) - .await - .is_err() - ); - assert_eq!( - counters.snapshot(), - (5, 1), - "failed reads must not count as downloads" - ); - } - - #[tokio::test] - async fn test_counting_storage_counts_get_all() { - let inner = RamStorageBuilder::default().put("foo", b"hello").build(); - let (storage, counters) = CountingStorage::instrument_storage(Arc::new(inner)); - - let bytes = storage.get_all(Path::new("foo")).await.unwrap(); - assert_eq!(bytes.as_slice(), b"hello"); - - let (download_num_bytes, download_num_requests) = counters.snapshot(); - assert_eq!(download_num_bytes, 5); - assert_eq!(download_num_requests, 1); - } - - #[tokio::test] - async fn test_counting_storage_does_not_count_metadata() { - let inner = RamStorageBuilder::default().put("foo", b"hello").build(); - let (storage, counters) = CountingStorage::instrument_storage(Arc::new(inner)); - - assert!(storage.exists(Path::new("foo")).await.unwrap()); - assert_eq!(storage.file_num_bytes(Path::new("foo")).await.unwrap(), 5); - - let (download_num_bytes, download_num_requests) = counters.snapshot(); - assert_eq!(download_num_bytes, 0); - assert_eq!(download_num_requests, 0); - } -} diff --git a/quickwit/quickwit-storage/src/debouncer.rs b/quickwit/quickwit-storage/src/debouncer.rs index 399928e7130..b8830fb7bf8 100644 --- a/quickwit/quickwit-storage/src/debouncer.rs +++ b/quickwit/quickwit-storage/src/debouncer.rs @@ -16,31 +16,23 @@ use std::fmt; use std::hash::Hash; use std::ops::Range; use std::path::{Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; use ahash::HashMap; -use async_trait::async_trait; use futures::future::{BoxFuture, Shared, WeakShared}; use futures::{Future, FutureExt}; use quickwit_common::uri::Uri; use tantivy::directory::OwnedBytes; use tokio::io::AsyncRead; -use crate::storage::SendableAsync; -use crate::{BulkDeleteError, ListObjectsStream, Storage, StorageResult}; +use crate::StorageResult; mod stream; use stream::StreamDebouncer; -/// The AsyncDebouncer debounces inflight Futures, so that concurrent async request to the same data -/// source can be deduplicated. -/// -/// Since we pass the Future potentially to multiple consumer, everything needs to be cloneable. The -/// data and the future. This is reflected on the generic type bounds for the value V: Clone. -/// -/// Since most Futures return an Result, this also encompasses the error. -pub struct AsyncDebouncer { +/// Debounces inflight futures so that concurrent async requests for the same key are deduplicated. +struct AsyncDebouncer { cache: Mutex>>>, /// Number of inserts performed since the last full garbage-collection scan. /// @@ -66,11 +58,8 @@ impl Default for AsyncDebouncer { const CLEANUP_INTERVAL: usize = 1_024; impl AsyncDebouncer { - /// Returns the number of entries in the debouncing cache. - /// - /// This is always greater than the number of inflight futures, and smaller - /// than that number + CLEANUP_INTERVAL + 1. - pub fn len(&self) -> usize { + #[cfg(test)] + fn len(&self) -> usize { self.cache.lock().unwrap().len() } @@ -95,9 +84,6 @@ impl AsyncDebouncer { T: FnOnce() -> F, F: Future + Send + 'static, { - // `created` distinguishes the caller that actually built the entry (and is therefore - // responsible for removing it once the future resolves) from callers that merely joined - // an already-inflight future. let mut debouncing_cache_guard = self.cache.lock().unwrap(); // A stale entry (left behind by a cancelled future) fails to upgrade and is simply @@ -129,120 +115,54 @@ impl AsyncDebouncer { } } -type DebouncerKey = (PathBuf, Range); +pub(super) type DebouncerKey = (Uri, PathBuf, Range); -/// Just to keep in mind there is a race condition on debouncing, when combined with delete +/// Deduplicates concurrent immutable storage reads (both buffered slices and streams) keyed by +/// `(storage_uri, path, byte_range)`. /// -/// All on the same key -/// start get R1 -/// start delete R2 -/// end delete R2 -/// start get R3 -/// end get R1 -/// end get R3 -/// -/// ==> R3 would return the cached result, although the resource has been deleted. -pub(crate) struct DebouncedStorage { - // wrap both in Arc, because the Future is stored in the cache, which has 'static lifetime - // associated - underlying: Arc, - slice_debouncer: Arc>>, - stream_debouncer: StreamDebouncer, +/// Only intended for immutable objects such as split files. Because keys include the storage +/// [`Uri`], a single `StorageDebouncer` can be shared across all indices and buckets on a node. +#[derive(Default)] +pub struct StorageDebouncer { + buffered: AsyncDebouncer>, + stream: StreamDebouncer, } -impl fmt::Debug for DebouncedStorage { +impl fmt::Debug for StorageDebouncer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DebouncedStorage").finish() + f.debug_struct("StorageDebouncer").finish() } } -impl DebouncedStorage { - pub(crate) fn new(underlying: T) -> Self { - Self { - underlying: Arc::new(underlying), - slice_debouncer: Arc::new(AsyncDebouncer::default()), - stream_debouncer: StreamDebouncer::default(), - } - } -} - -#[async_trait] -impl Storage for DebouncedStorage { - async fn check_connectivity(&self) -> anyhow::Result<()> { - self.underlying.check_connectivity().await - } - - async fn put( - &self, - path: &Path, - payload: Box, - ) -> crate::StorageResult<()> { - self.underlying.put(path, payload).await - } - - async fn copy_to(&self, path: &Path, output: &mut dyn SendableAsync) -> StorageResult<()> { - self.underlying.copy_to(path, output).await - } - - async fn get_slice(&self, path: &Path, range: Range) -> StorageResult { - let (debouncer, underlying) = (self.slice_debouncer.clone(), self.underlying.clone()); - let key = (path.to_owned(), range); - debouncer - .get_or_create(key.clone(), || async move { - underlying.get_slice(&key.0, key.1).await - }) - .await - } - - async fn get_slice_into( +impl StorageDebouncer { + pub(crate) async fn get_slice( &self, + uri: &Uri, path: &Path, range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - // Forward caller-owned buffers directly to preserve backend accounting and streaming. - self.underlying.get_slice_into(path, range, buffer).await + fetch: F, + ) -> StorageResult + where + F: FnOnce() -> Fut, + Fut: Future> + Send + 'static, + { + let key = (uri.clone(), path.to_owned(), range); + self.buffered.get_or_create(key, fetch).await } - async fn get_slice_stream( + pub(crate) async fn get_slice_stream( &self, + uri: &Uri, path: &Path, range: Range, - ) -> StorageResult> { - self.stream_debouncer - .get_slice_stream(self.underlying.clone(), path, range) - .await - } - - async fn delete(&self, path: &Path) -> StorageResult<()> { - self.underlying.delete(path).await - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - self.underlying.bulk_delete(paths).await - } - - fn list(&self, prefix: &Path) -> ListObjectsStream { - self.underlying.list(prefix) - } - - async fn get_all(&self, path: &Path) -> StorageResult { - let (debouncer, underlying) = (self.slice_debouncer.clone(), self.underlying.clone()); - let key = (path.to_owned(), 0..usize::MAX); - debouncer - .get_or_create( - key.clone(), - || async move { underlying.get_all(&key.0).await }, - ) - .await - } - - fn uri(&self) -> &Uri { - self.underlying.uri() - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - self.underlying.file_num_bytes(path).await + open_stream: F, + ) -> StorageResult> + where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future>> + Send + 'static, + { + let key = (uri.clone(), path.to_owned(), range); + self.stream.get_slice_stream(key, open_stream).await } } @@ -262,34 +182,14 @@ mod tests { use super::*; - #[tokio::test] - async fn test_get_slice_into_forwards_to_backend() { - let mut backend = crate::MockStorage::new(); - backend.expect_get_slice_stream().never(); - backend - .expect_get_slice_into() - .times(1) - .returning(|path, range, buffer| { - assert_eq!(path, Path::new("object")); - assert_eq!(range, 2..5); - buffer.copy_from_slice(b"abc"); - Ok(()) - }); - let storage = DebouncedStorage::new(backend); - let mut buffer = [0; 3]; - storage - .get_slice_into(Path::new("object"), 2..5, &mut buffer) - .await - .unwrap(); - assert_eq!(&buffer, b"abc"); - } - #[test] fn test_sync_and_send() { fn is_sync() {} fn is_send() {} is_sync::>>(); is_send::>>(); + is_sync::(); + is_send::(); } #[derive(Hash, Clone, Debug, Eq, PartialEq)] diff --git a/quickwit/quickwit-storage/src/debouncer/stream.rs b/quickwit/quickwit-storage/src/debouncer/stream.rs index 5e7708feac4..3af231658e1 100644 --- a/quickwit/quickwit-storage/src/debouncer/stream.rs +++ b/quickwit/quickwit-storage/src/debouncer/stream.rs @@ -12,9 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::future::Future; use std::io; -use std::ops::Range; -use std::path::Path; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; @@ -29,7 +28,7 @@ use tokio_util::task::AbortOnDropHandle; use tracing::Instrument; use super::{CLEANUP_INTERVAL, DebouncerKey}; -use crate::{Storage, StorageErrorKind, StorageResult}; +use crate::{StorageErrorKind, StorageResult}; const JOIN_WINDOW: Duration = Duration::from_millis(5); const CHUNK_NUM_BYTES: usize = 1024 * 1024; @@ -37,9 +36,10 @@ const CHUNK_NUM_BYTES: usize = 1024 * 1024; // reader absorbs jitter without multiplying memory by the number of readers. const READER_CHANNEL_CAPACITY: usize = 4; -/// Collects concurrent reads for the same path and byte range for 5 ms, then shares one storage -/// stream across those readers. Each reader buffers up to [`READER_CHANNEL_CAPACITY`] chunks. A -/// slow reader pauses the producer once its buffer fills, and dropping the last reader cancels it. +/// Collects concurrent reads for the same URI, path, and byte range for 5 ms, then shares one +/// storage stream across those readers. Each reader buffers up to [`READER_CHANNEL_CAPACITY`] +/// chunks. A slow reader pauses the producer once its buffer fills, and dropping the last reader +/// cancels it. #[derive(Default)] pub(super) struct StreamDebouncer { // The group map and the count of insertions since the last sweep share one lock. @@ -64,14 +64,17 @@ struct StreamGroup { } impl StreamDebouncer { - pub(super) async fn get_slice_stream( + pub(super) async fn get_slice_stream( &self, - storage: Arc, - path: &Path, - range: Range, - ) -> StorageResult> { + key: DebouncerKey, + open_stream: F, + ) -> StorageResult> + where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future>> + Send + 'static, + { let (open_sender, open_receiver) = oneshot::channel(); - let group = self.join_or_start_group(storage, (path.to_owned(), range), open_sender); + let group = self.join_or_start_group(key, open_sender, open_stream); let item_receiver = open_receiver.await.map_err(|_| { StorageErrorKind::Internal.with_error(anyhow::anyhow!("stream producer stopped")) })??; @@ -89,12 +92,16 @@ impl StreamDebouncer { Ok(Box::new(StreamReader::new(chunks.boxed()))) } - fn join_or_start_group( + fn join_or_start_group( &self, - storage: Arc, key: DebouncerKey, mut reader: OpenSender, - ) -> Arc { + open_stream: F, + ) -> Arc + where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future>> + Send + 'static, + { let mut registry = self.groups.lock().unwrap(); let (groups, inserts_since_cleanup) = &mut *registry; if let Some(group) = groups.get(&key).and_then(Weak::upgrade) { @@ -110,13 +117,7 @@ impl StreamDebouncer { .send(reader) .expect("receiver is still owned here"); let task = tokio::spawn( - share_stream( - storage, - key.clone(), - join_deadline, - joining_readers_receiver, - ) - .in_current_span(), + share_stream(open_stream, join_deadline, joining_readers_receiver).in_current_span(), ); let group = Arc::new(StreamGroup { _producer_task: AbortOnDropHandle::new(task), @@ -133,16 +134,18 @@ impl StreamDebouncer { } } -async fn share_stream( - storage: Arc, - key: DebouncerKey, +async fn share_stream( + open_stream: F, join_deadline: Instant, mut joining_readers: mpsc::UnboundedReceiver, -) { +) where + F: FnOnce() -> Fut, + Fut: Future>>, +{ tokio::time::sleep_until(join_deadline).await; // Callers arriving after this point start a new stream group. joining_readers.close(); - let stream = storage.get_slice_stream(&key.0, key.1).await; + let stream = open_stream().await; let mut senders = Vec::new(); while let Some(open_sender) = joining_readers.recv().await { match &stream { @@ -192,18 +195,31 @@ async fn share_stream( #[cfg(test)] mod tests { + use std::path::Path; + use futures::poll; + use quickwit_common::uri::Uri; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use super::*; - use crate::MockStorage; - use crate::debouncer::DebouncedStorage; + use crate::debouncer::StorageDebouncer; + use crate::{MockStorage, SplitStorageReader}; + + fn debounced_reader(backend: MockStorage, uri: &'static str) -> SplitStorageReader { + let mut backend = backend; + backend.expect_uri().return_const(Uri::for_test(uri)); + SplitStorageReader::new(Arc::new(backend)) + .with_debouncer(Arc::new(StorageDebouncer::default())) + } #[tokio::test(start_paused = true)] - async fn test_groups_by_path_range_and_fixed_window() { + async fn test_groups_by_uri_path_range_and_fixed_window() { let start = Instant::now(); - let mut backend = MockStorage::default(); - backend + let mut backend_a = MockStorage::default(); + backend_a + .expect_uri() + .return_const(Uri::for_test("ram:///bucket-a")); + backend_a .expect_get_slice_stream() .times(4) .returning(move |path, range| { @@ -211,23 +227,39 @@ mod tests { let byte = path.to_str().unwrap().as_bytes()[0] + range.start as u8; Ok(Box::new(io::Cursor::new([byte]))) }); - let storage = DebouncedStorage::new(backend); - let mut first = Box::pin(storage.get_slice_stream(Path::new("a"), 0..1)); + let mut backend_b = MockStorage::default(); + backend_b + .expect_uri() + .return_const(Uri::for_test("ram:///bucket-b")); + backend_b + .expect_get_slice_stream() + .times(1) + .returning(move |_, _| { + assert!(Instant::now() >= start + JOIN_WINDOW); + Ok(Box::new(io::Cursor::new(*b"B"))) + }); + let debouncer = Arc::new(StorageDebouncer::default()); + let reader_a = + SplitStorageReader::new(Arc::new(backend_a)).with_debouncer(debouncer.clone()); + let reader_b = SplitStorageReader::new(Arc::new(backend_b)).with_debouncer(debouncer); + let mut first = Box::pin(reader_a.get_slice_stream(Path::new("a"), 0..1)); assert!(poll!(&mut first).is_pending()); tokio::time::advance(Duration::from_millis(4)).await; - let (first, second) = tokio::join!(first, storage.get_slice_stream(Path::new("a"), 0..1)); + let (first, second) = tokio::join!(first, reader_a.get_slice_stream(Path::new("a"), 0..1)); assert_eq!(Instant::now(), start + JOIN_WINDOW); - // Late readers and different keys each open a separate stream. - let (late, other_path, other_range) = tokio::join!( - storage.get_slice_stream(Path::new("a"), 0..1), - storage.get_slice_stream(Path::new("z"), 0..1), - storage.get_slice_stream(Path::new("a"), 1..2), + // Late readers and different keys (including different URIs) each open a separate stream. + let (late, other_path, other_range, other_uri) = tokio::join!( + reader_a.get_slice_stream(Path::new("a"), 0..1), + reader_a.get_slice_stream(Path::new("z"), 0..1), + reader_a.get_slice_stream(Path::new("a"), 1..2), + reader_b.get_slice_stream(Path::new("a"), 0..1), ); assert_eq!(Instant::now(), start + 2 * JOIN_WINDOW); - drop(storage); + drop((reader_a, reader_b)); for (reader, expected) in [ (first, b'a'), (second, b'a'), + (other_uri, b'B'), (late, b'a'), (other_path, b'z'), (other_range, b'b'), @@ -247,7 +279,7 @@ mod tests { .expect_get_slice_stream() .once() .return_once(|_, _| Ok(Box::new(reader))); - let storage = DebouncedStorage::new(backend); + let storage = debounced_reader(backend, "ram:///bucket"); let mut cancelled = Box::pin(storage.get_slice_stream(Path::new("cancelled"), 0..3)); assert!(poll!(&mut cancelled).is_pending()); drop(cancelled); @@ -308,7 +340,7 @@ mod tests { })))), _ => panic!("open panic"), }); - let storage = DebouncedStorage::new(backend); + let storage = debounced_reader(backend, "ram:///bucket"); let (first, second) = tokio::join!( storage.get_slice_stream(Path::new("file"), 0..10), storage.get_slice_stream(Path::new("file"), 0..10), diff --git a/quickwit/quickwit-storage/src/file_descriptor_cache.rs b/quickwit/quickwit-storage/src/file_descriptor_cache.rs index b46686b147b..e3707f6aadf 100644 --- a/quickwit/quickwit-storage/src/file_descriptor_cache.rs +++ b/quickwit/quickwit-storage/src/file_descriptor_cache.rs @@ -25,19 +25,18 @@ use tokio::io::AsyncRead; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio_util::io::StreamReader; -use crate::metrics::{FD_CACHE_METRICS, SingleCacheMetrics}; +use crate::metrics::{CacheMetrics, FD_CACHE_METRICS}; pub struct FileDescriptorCache { fd_cache: Mutex>, fd_semaphore: Arc, - fd_cache_metrics: SingleCacheMetrics, + fd_cache_metrics: CacheMetrics, } #[derive(Clone)] pub struct SplitFile(Arc); struct SplitFileInner { - num_bytes: u64, // Order matters here. We want file to be dropped (closed) before the semaphore. file: File, _fd_semaphore_guard: OwnedSemaphorePermit, @@ -70,7 +69,7 @@ impl FileDescriptorCache { fn new( max_fd_limit: NonZeroU32, fd_cache_capacity: NonZeroU32, - fd_cache_metrics: SingleCacheMetrics, + fd_cache_metrics: CacheMetrics, ) -> FileDescriptorCache { assert!(max_fd_limit.get() > fd_cache_capacity.get()); let fd_cache = Mutex::new(lru::LruCache::new( @@ -90,7 +89,7 @@ impl FileDescriptorCache { Self::new( NonZeroU32::new(max_fd_limit).unwrap(), fd_cache_capacity, - FD_CACHE_METRICS.cache_metrics.clone(), + FD_CACHE_METRICS.clone(), ) } @@ -125,7 +124,6 @@ impl FileDescriptorCache { &self, root_path: &Path, split_id: SplitId, - num_bytes: u64, ) -> std::io::Result { if let Some(split_file) = self.get_split_file(&split_id) { self.fd_cache_metrics.hits_num_items.inc(); @@ -143,7 +141,6 @@ impl FileDescriptorCache { io::Error::other(format!("failed to open file: {join_error:?}")) })??; let split_file = SplitFile(Arc::new(SplitFileInner { - num_bytes, file, _fd_semaphore_guard: fd_semaphore_guard, })); @@ -188,10 +185,6 @@ impl SplitFile { }); StreamReader::new(Box::pin(chunks)) } - - pub async fn get_all(&self) -> io::Result { - self.get_range(0..self.0.num_bytes as usize).await - } } #[cfg(test)] @@ -211,7 +204,7 @@ mod tests { #[tokio::test] async fn test_fd_cache_big_cache() { - let cache_metrics = CacheMetrics::for_component("fdtest").cache_metrics; + let cache_metrics = CacheMetrics::for_component("fdtest"); let fd_cache = FileDescriptorCache::new( NonZeroU32::new(20).unwrap(), NonZeroU32::new(10).unwrap(), @@ -229,19 +222,19 @@ mod tests { } for split_id in &split_ids[0..10] { fd_cache - .get_or_open_split_file(tempdir.path(), split_id.clone(), 26) + .get_or_open_split_file(tempdir.path(), split_id.clone()) .await .unwrap(); } for split_id in &split_ids[0..10] { fd_cache - .get_or_open_split_file(tempdir.path(), split_id.clone(), 26) + .get_or_open_split_file(tempdir.path(), split_id.clone()) .await .unwrap(); } for split_id in &split_ids[0..10] { fd_cache - .get_or_open_split_file(tempdir.path(), split_id.clone(), 26) + .get_or_open_split_file(tempdir.path(), split_id.clone()) .await .unwrap(); } @@ -255,7 +248,7 @@ mod tests { // opening the file several times. #[tokio::test] async fn test_fd_cache_small_cache() { - let cache_metrics = CacheMetrics::for_component("fdtest2").cache_metrics; + let cache_metrics = CacheMetrics::for_component("fdtest2"); let fd_cache = FileDescriptorCache::new( NonZeroU32::new(20).unwrap(), NonZeroU32::new(10).unwrap(), @@ -274,7 +267,7 @@ mod tests { for split_id in &split_ids[0..100] { for _ in 0..10 { fd_cache - .get_or_open_split_file(tempdir.path(), split_id.clone(), 26) + .get_or_open_split_file(tempdir.path(), split_id.clone()) .await .unwrap(); } @@ -294,11 +287,11 @@ mod tests { assert_eq!(content.len(), 26); fs::write(split_filepath, content.as_bytes()).await.unwrap(); let split_file = fd_cache - .get_or_open_split_file(tempdir.path(), split_id, 26) + .get_or_open_split_file(tempdir.path(), split_id) .await .unwrap(); { - let bytes = split_file.get_all().await.unwrap(); + let bytes = split_file.get_range(0..26).await.unwrap(); assert_eq!(bytes.as_slice(), content.as_bytes()); } { diff --git a/quickwit/quickwit-storage/src/lib.rs b/quickwit/quickwit-storage/src/lib.rs index 245d5c2b2da..d608978949a 100644 --- a/quickwit/quickwit-storage/src/lib.rs +++ b/quickwit/quickwit-storage/src/lib.rs @@ -24,21 +24,23 @@ //! - distributed filesystems. //! - etc. //! -//! The `BundleStorage` bundles together multiple files into a single file. -mod cache; -mod counting_storage; +//! The `SplitBundle` and `SplitStorageReader` types provide a static read pipeline over bundled +//! split files. mod debouncer; mod file_descriptor_cache; pub mod metrics; +mod split_bundle; +mod split_storage_reader; mod storage; -mod timeout_and_retry_storage; -pub use debouncer::AsyncDebouncer; -pub(crate) use debouncer::DebouncedStorage; +mod timeout_and_retry; +pub use debouncer::StorageDebouncer; +pub use split_storage_reader::{DownloadCounters, SplitStorageReader}; pub use self::payload::PutPayload; -pub use self::storage::{ListObjectsStream, ObjectMetadata, Storage, default_get_slice_into}; +pub use self::storage::{ + ListObjectsStream, ObjectMetadata, SendableAsync, Storage, default_get_slice_into, +}; -mod bundle_storage; mod error; mod feuer_cache; @@ -60,21 +62,10 @@ mod versioned_component; pub use feuer_cache::{FeuerCache, FeuerIoQueues}; use quickwit_common::uri::Uri; pub use split_cache::SearchSplitCache; -pub use storage_cache::{ - attach_storage_cache_access_trace, open_storage_cache, wrap_storage_with_storage_cache, -}; +pub use storage_cache::{attach_storage_cache_access_trace, open_storage_cache}; pub use tantivy::directory::OwnedBytes; pub use versioned_component::VersionedComponent; -pub use self::bundle_storage::{ - BundleFileRanges, BundleStorage, locate_split_footer_range, strip_split_footer_trailer, -}; -#[cfg(any(test, feature = "testsuite"))] -pub use self::cache::MockStorageCache; -pub use self::cache::{ - ByteRangeCache, FileByteRangeCache, MemorySizedCache, StorageCache, wrap_storage_with_cache, -}; -pub use self::counting_storage::{CountingStorage, DownloadCounters}; pub use self::local_file_storage::{LocalFileStorage, LocalFileStorageFactory}; #[cfg(feature = "azure")] pub use self::object_storage::{AzureBlobStorage, AzureBlobStorageFactory}; @@ -87,6 +78,9 @@ pub use self::opendal_storage::GoogleCloudStorageFactory; pub use self::opendal_storage::test_config_helpers; pub use self::ram_storage::{RamStorage, RamStorageBuilder}; pub use self::split::{SplitPayload, SplitPayloadBuilder}; +pub use self::split_bundle::{ + BundleFileRanges, SplitBundle, locate_split_footer_range, strip_split_footer_trailer, +}; #[cfg(any(test, feature = "testsuite"))] pub use self::storage::MockStorage; #[cfg(any(test, feature = "testsuite"))] @@ -98,7 +92,6 @@ pub use self::test_suite::{ storage_test_multi_part_upload, storage_test_single_part_upload, storage_test_suite, test_write_and_bulk_delete, }; -pub use self::timeout_and_retry_storage::TimeoutAndRetryStorage; pub use crate::error::{ BulkDeleteError, DeleteFailure, StorageError, StorageErrorKind, StorageResolverError, StorageResult, diff --git a/quickwit/quickwit-storage/src/local_file_storage.rs b/quickwit/quickwit-storage/src/local_file_storage.rs index 4f54b36b3c9..a310bc9afbc 100644 --- a/quickwit/quickwit-storage/src/local_file_storage.rs +++ b/quickwit/quickwit-storage/src/local_file_storage.rs @@ -31,8 +31,8 @@ use tracing::warn; use crate::metrics::object_storage_get_slice_in_flight_guards; use crate::storage::SendableAsync; use crate::{ - BulkDeleteError, DebouncedStorage, DeleteFailure, OwnedBytes, Storage, StorageError, - StorageErrorKind, StorageFactory, StorageResolverError, StorageResult, + BulkDeleteError, DeleteFailure, OwnedBytes, Storage, StorageError, StorageErrorKind, + StorageFactory, StorageResolverError, StorageResult, }; /// File system compatible storage implementation. @@ -389,7 +389,7 @@ impl StorageFactory for LocalFileStorageFactory { async fn resolve(&self, uri: &Uri) -> Result, StorageResolverError> { let storage = LocalFileStorage::from_uri(uri)?; - Ok(Arc::new(DebouncedStorage::new(storage))) + Ok(Arc::new(storage)) } } diff --git a/quickwit/quickwit-storage/src/metrics.rs b/quickwit/quickwit-storage/src/metrics.rs index ebcbd265f35..d47f6abecad 100644 --- a/quickwit/quickwit-storage/src/metrics.rs +++ b/quickwit/quickwit-storage/src/metrics.rs @@ -15,10 +15,8 @@ //! Storage and cache metrics following //! [Prometheus naming conventions](https://prometheus.io/docs/practices/naming/). -use std::collections::HashMap; -use std::sync::{LazyLock, RwLock}; +use std::sync::LazyLock; -use quickwit_config::CacheConfig; use quickwit_metrics::{ Counter, Gauge, GaugeGuard, LabelNames, Labels, LazyCounter, LazyGauge, LazyHistogram, counter, gauge, label_names, label_values, labels, lazy_counter, lazy_gauge, lazy_histogram, @@ -31,8 +29,6 @@ const ACTION_PUT_OBJECT: Labels<1> = labels!("action" => "put_object"); const ACTION_UPLOAD_PART: Labels<1> = labels!("action" => "upload_part"); const OUTCOME_NAME: LabelNames<1> = label_names!("outcome"); const COMPONENT_NAME: LabelNames<1> = label_names!("component_name"); -const COMPONENT_CAPACITY_POLICY: LabelNames<3> = - label_names!("component_name", "capacity", "policy"); pub(crate) const ERROR_CLASS: LabelNames<1> = label_names!("class"); static GET_SLICE_TIMEOUT_OUTCOME_TOTAL: LazyCounter = lazy_counter!( @@ -97,7 +93,7 @@ pub(crate) static OBJECT_STORAGE_UPLOAD_PART_DURATION: LazyHistogram = pub(crate) static OBJECT_STORAGE_GET_TOTAL: LazyCounter = lazy_counter!( name: "object_storage_gets_total", - description: "Number of objects fetched. Might be lower than get_slice_timeout_outcome if queries are debounced.", + description: "Number of objects fetched. Might be higher than get_slice_timeout_outcome if timed-out reads are retried.", subsystem: "storage", ); @@ -161,21 +157,12 @@ pub(crate) static OBJECT_STORAGE_UPLOAD_NUM_BYTES: LazyCounter = lazy_counter!( subsystem: "storage", ); -/// Metrics for a named cache component (e.g. "fastfields", "splitfooter"). +/// Metrics for a named cache component (e.g. "partial_request", "predicate"). /// /// Each `CacheMetrics` instance holds a set of counters and gauges scoped to a -/// `component_name` label. It also supports virtual sub-caches keyed by -/// [`CacheConfig`], which add `capacity` and `policy` labels. -pub struct CacheMetrics { - component_name: String, - pub(crate) cache_metrics: SingleCacheMetrics, - virtual_caches_metrics: RwLock>, -} - -/// Per-cache counters and gauges tracking items in cache, hits, misses, and -/// evictions. +/// `component_name` label. #[derive(Clone)] -pub struct SingleCacheMetrics { +pub struct CacheMetrics { /// Current number of items stored in the cache. pub(crate) in_cache_count: Gauge, /// Current number of bytes stored in the cache. @@ -195,20 +182,15 @@ pub struct SingleCacheMetrics { impl CacheMetrics { /// Creates a new `CacheMetrics` for the given component name. pub fn for_component(component_name: &str) -> Self { - let component_name = component_name.to_string(); - let labels = label_values!(COMPONENT_NAME => component_name.clone()); + let labels = label_values!(COMPONENT_NAME => component_name.to_string()); CacheMetrics { - component_name, - cache_metrics: SingleCacheMetrics { - in_cache_count: gauge!(parent: CACHE_IN_CACHE_COUNT, labels: [labels]), - in_cache_num_bytes: gauge!(parent: CACHE_IN_CACHE_NUM_BYTES, labels: [labels]), - hits_num_items: counter!(parent: CACHE_HITS_TOTAL, labels: [labels]), - hits_num_bytes: counter!(parent: CACHE_HITS_BYTES, labels: [labels]), - misses_num_items: counter!(parent: CACHE_MISSES_TOTAL, labels: [labels]), - evict_num_items: counter!(parent: CACHE_EVICT_TOTAL, labels: [labels]), - evict_num_bytes: counter!(parent: CACHE_EVICT_BYTES, labels: [labels]), - }, - virtual_caches_metrics: RwLock::default(), + in_cache_count: gauge!(parent: CACHE_IN_CACHE_COUNT, labels: [labels]), + in_cache_num_bytes: gauge!(parent: CACHE_IN_CACHE_NUM_BYTES, labels: [labels]), + hits_num_items: counter!(parent: CACHE_HITS_TOTAL, labels: [labels]), + hits_num_bytes: counter!(parent: CACHE_HITS_BYTES, labels: [labels]), + misses_num_items: counter!(parent: CACHE_MISSES_TOTAL, labels: [labels]), + evict_num_items: counter!(parent: CACHE_EVICT_TOTAL, labels: [labels]), + evict_num_bytes: counter!(parent: CACHE_EVICT_BYTES, labels: [labels]), } } @@ -216,45 +198,11 @@ impl CacheMetrics { pub fn record_get(&self, num_bytes: Option) { match num_bytes { Some(num_bytes) => { - self.cache_metrics.hits_num_items.inc(); - self.cache_metrics.hits_num_bytes.inc_by(num_bytes as u64); + self.hits_num_items.inc(); + self.hits_num_bytes.inc_by(num_bytes as u64); } - None => self.cache_metrics.misses_num_items.inc(), - } - } - - /// Returns metrics for a virtual sub-cache identified by `config`. - /// - /// Virtual caches share the same parent component but add `capacity` and - /// `policy` labels. Instances are cached and reused across calls. - pub(crate) fn virtual_cache(&self, config: &CacheConfig) -> SingleCacheMetrics { - if let Some(virtual_cache_metrics) = self.virtual_caches_metrics.read().unwrap().get(config) - { - return virtual_cache_metrics.clone(); + None => self.misses_num_items.inc(), } - - let labels = label_values!( - COMPONENT_CAPACITY_POLICY => - self.component_name.clone(), - config.memory_capacity().as_u64().to_string(), - config.policy().to_string(), - ); - let new_virtual_cache_metrics = SingleCacheMetrics { - in_cache_count: gauge!(parent: VIRTUAL_CACHE_IN_CACHE_COUNT, labels: [labels]), - in_cache_num_bytes: gauge!(parent: VIRTUAL_CACHE_IN_CACHE_NUM_BYTES, labels: [labels]), - hits_num_items: counter!(parent: VIRTUAL_CACHE_HITS_TOTAL, labels: [labels]), - hits_num_bytes: counter!(parent: VIRTUAL_CACHE_HITS_BYTES, labels: [labels]), - misses_num_items: counter!(parent: VIRTUAL_CACHE_MISSES_TOTAL, labels: [labels]), - evict_num_items: counter!(parent: VIRTUAL_CACHE_EVICT_TOTAL, labels: [labels]), - evict_num_bytes: counter!(parent: VIRTUAL_CACHE_EVICT_BYTES, labels: [labels]), - }; - - self.virtual_caches_metrics - .write() - .unwrap() - .entry(config.clone()) - .or_insert(new_virtual_cache_metrics) - .clone() } } @@ -300,48 +248,6 @@ static CACHE_EVICT_BYTES: LazyCounter = lazy_counter!( subsystem: "cache", ); -static VIRTUAL_CACHE_IN_CACHE_COUNT: LazyGauge = lazy_gauge!( - name: "virtual_in_cache_count", - description: "Count of in cache by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_IN_CACHE_NUM_BYTES: LazyGauge = lazy_gauge!( - name: "virtual_in_cache_num_bytes", - description: "Number of bytes in cache by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_HITS_TOTAL: LazyCounter = lazy_counter!( - name: "virtual_cache_hits_total", - description: "Number of cache hits by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_HITS_BYTES: LazyCounter = lazy_counter!( - name: "virtual_cache_hits_bytes", - description: "Number of cache hits in bytes by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_MISSES_TOTAL: LazyCounter = lazy_counter!( - name: "virtual_cache_misses_total", - description: "Number of cache misses by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_EVICT_TOTAL: LazyCounter = lazy_counter!( - name: "virtual_cache_evict_total", - description: "Number of cache entry evicted by component", - subsystem: "cache", -); - -static VIRTUAL_CACHE_EVICT_BYTES: LazyCounter = lazy_counter!( - name: "virtual_cache_evict_bytes", - description: "Number of cache entry evicted in bytes by component", - subsystem: "cache", -); - pub(crate) static FD_CACHE_METRICS: LazyLock = LazyLock::new(|| CacheMetrics::for_component("fd")); @@ -356,15 +262,6 @@ pub static PREDICATE_CACHE: LazyLock = pub(crate) static SEARCHER_SPLIT_CACHE: LazyLock = LazyLock::new(|| CacheMetrics::for_component("searcher_split")); -/// Cache metrics for split footer caches (used to cache split metadata). -pub static SPLIT_FOOTER_CACHE: LazyLock = - LazyLock::new(|| CacheMetrics::for_component("splitfooter")); - -#[cfg(test)] -/// Cache metrics for tests. -pub static CACHE_METRICS_FOR_TESTS: LazyLock = - LazyLock::new(|| CacheMetrics::for_component("fortest")); - pub(crate) fn object_storage_get_slice_in_flight_guards( get_request_size: usize, ) -> (GaugeGuard, GaugeGuard) { diff --git a/quickwit/quickwit-storage/src/object_storage/azure_blob_storage.rs b/quickwit/quickwit-storage/src/object_storage/azure_blob_storage.rs index 5fd11509d8e..6aacae586c6 100644 --- a/quickwit/quickwit-storage/src/object_storage/azure_blob_storage.rs +++ b/quickwit/quickwit-storage/src/object_storage/azure_blob_storage.rs @@ -47,7 +47,6 @@ use tokio_util::io::StreamReader; use tracing::{instrument, warn}; use ulid::Ulid; -use crate::debouncer::DebouncedStorage; use crate::metrics::object_storage_get_slice_in_flight_guards; use crate::object_storage::azure_credentials::{ AzureCredential, build_container_client, resolve_credential, @@ -104,7 +103,7 @@ impl StorageFactory for AzureBlobStorageFactory { credential, Some(transport), )?; - Ok(Arc::new(DebouncedStorage::new(storage))) + Ok(Arc::new(storage)) } } diff --git a/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage.rs b/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage.rs index 61d00bfa635..9e0dc3f774e 100644 --- a/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage.rs +++ b/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage.rs @@ -1280,7 +1280,7 @@ mod tests { use quickwit_common::uri::Uri; use super::*; - use crate::{DebouncedStorage, MultiPartPolicy, S3CompatibleObjectStorage}; + use crate::{MultiPartPolicy, S3CompatibleObjectStorage}; #[tokio::test] async fn test_md5_calc() -> std::io::Result<()> { @@ -1460,7 +1460,7 @@ mod tests { .http_client(client.clone()) .credentials_provider(credentials) .build(); - let storage = DebouncedStorage::new(S3CompatibleObjectStorage { + let storage = S3CompatibleObjectStorage { s3_client: S3Client::from_conf(config), uri: Uri::for_test("s3://bucket/indexes"), bucket: "bucket".to_string(), @@ -1470,7 +1470,7 @@ mod tests { disable_multi_object_delete: false, disable_multipart_upload: false, checksum_algorithm: quickwit_config::ChecksumAlgorithm::Crc32c, - }); + }; let pages: Vec> = storage.list(Path::new("")).try_collect().await.unwrap(); diff --git a/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage_resolver.rs b/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage_resolver.rs index 92b4406486b..2c99ce14e3e 100644 --- a/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage_resolver.rs +++ b/quickwit/quickwit-storage/src/object_storage/s3_compatible_storage_resolver.rs @@ -21,9 +21,7 @@ use quickwit_config::{S3StorageConfig, StorageBackend}; use tokio::sync::OnceCell; use super::s3_compatible_storage::create_s3_client; -use crate::{ - DebouncedStorage, S3CompatibleObjectStorage, Storage, StorageFactory, StorageResolverError, -}; +use crate::{S3CompatibleObjectStorage, Storage, StorageFactory, StorageResolverError}; /// S3 compatible object storage resolver. pub struct S3CompatibleObjectStorageFactory { @@ -61,6 +59,6 @@ impl StorageFactory for S3CompatibleObjectStorageFactory { let storage = S3CompatibleObjectStorage::from_uri_and_client(&self.storage_config, uri, s3_client) .await?; - Ok(Arc::new(DebouncedStorage::new(storage))) + Ok(Arc::new(storage)) } } diff --git a/quickwit/quickwit-storage/src/opendal_storage/google_cloud_storage.rs b/quickwit/quickwit-storage/src/opendal_storage/google_cloud_storage.rs index 632215f8d5b..e09fa061b1d 100644 --- a/quickwit/quickwit-storage/src/opendal_storage/google_cloud_storage.rs +++ b/quickwit/quickwit-storage/src/opendal_storage/google_cloud_storage.rs @@ -28,7 +28,6 @@ use reqsign_google::{ use tracing::info; use super::OpendalStorage; -use crate::debouncer::DebouncedStorage; use crate::{Storage, StorageFactory, StorageResolverError}; // Matches opendal's DEFAULT_GCS_SCOPE, which is more restrictive than `cloud-platform` used by @@ -40,7 +39,7 @@ pub struct GoogleCloudStorageFactory { storage_config: GoogleCloudStorageConfig, // this is technically an unbounded cache, the bound is the number of indexes that have existed // since node start, which should be low enough this isn't catastrophic - storage_cache: Mutex>>>, + storage_cache: Mutex>>, } impl GoogleCloudStorageFactory { @@ -65,7 +64,7 @@ impl StorageFactory for GoogleCloudStorageFactory { if let Some(storage) = cache.get(uri) { storage.clone() } else { - let storage = Arc::new(DebouncedStorage::new(from_uri(&self.storage_config, uri)?)); + let storage = Arc::new(from_uri(&self.storage_config, uri)?); cache.insert(uri.clone(), storage.clone()); storage } diff --git a/quickwit/quickwit-storage/src/split.rs b/quickwit/quickwit-storage/src/split.rs index 9625b81d170..2482af3feff 100644 --- a/quickwit/quickwit-storage/src/split.rs +++ b/quickwit/quickwit-storage/src/split.rs @@ -25,7 +25,7 @@ use hyper::body::{Bytes, Frame}; use pin_project::pin_project; use quickwit_common::shared_consts::{SPLIT_FIELDS_FILE_NAME, SPLIT_RECOVERY_METADATA_FILE_NAME}; -use crate::bundle_storage::{BundleFileRangesVersions, serialize_split_footer_trailer}; +use crate::split_bundle::{BundleFileRangesVersions, serialize_split_footer_trailer}; use crate::{BundleFileRanges, PutPayload, VersionedComponent}; /// Payload of a split which builds the split bundle and hotcache on the fly and streams it to the diff --git a/quickwit/quickwit-storage/src/bundle_storage.rs b/quickwit/quickwit-storage/src/split_bundle.rs similarity index 64% rename from quickwit/quickwit-storage/src/bundle_storage.rs rename to quickwit/quickwit-storage/src/split_bundle.rs index 623dbf52eb2..cb571bbdc38 100644 --- a/quickwit/quickwit-storage/src/bundle_storage.rs +++ b/quickwit/quickwit-storage/src/split_bundle.rs @@ -14,111 +14,119 @@ use std::collections::HashMap; use std::convert::TryInto; -use std::fmt::Debug; use std::ops::Range; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::{fmt, io}; use anyhow::{Context, anyhow, bail, ensure}; -use async_trait::async_trait; use bytes::{Buf, BufMut}; -use quickwit_common::chunk_range; -use quickwit_common::uri::Uri; +use futures::stream::{BoxStream, StreamExt}; use serde::{Deserialize, Serialize}; use tantivy::HasLen; use tantivy::directory::FileSlice; -use tokio::io::{AsyncRead, AsyncWriteExt}; -use tracing::error; - -use crate::storage::SendableAsync; -use crate::{ - BulkDeleteError, OwnedBytes, Storage, StorageError, StorageErrorKind, StorageResult, - VersionedComponent, -}; - -/// BundleStorage bundles together multiple files into a single file. -pub struct BundleStorage { - storage: Arc, - /// The file path of the bundle in the storage. - bundle_filepath: PathBuf, +use tokio::io::AsyncRead; + +use crate::{OwnedBytes, SplitStorageReader, StorageErrorKind, StorageResult, VersionedComponent}; + +/// Read-only view of the files bundled inside a single split object. +/// +/// Maps logical file paths within the split to byte ranges inside the split object and delegates +/// buffered and streamed slice reads to [`SplitStorageReader`]. Deliberately does not implement +/// [`crate::Storage`]. +#[derive(Clone)] +pub struct SplitBundle { + inner: Arc, +} + +struct SplitBundleInner { + reader: SplitStorageReader, + split_path: PathBuf, file_ranges: BundleFileRanges, } -impl BundleStorage { - /// Opens a split bundle by locating its footer directly from object storage. +impl fmt::Debug for SplitBundle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "SplitBundle({:?}, files={:?})", + self.inner.split_path, self.inner.file_ranges + ) + } +} + +impl SplitBundle { + fn from_parts( + reader: SplitStorageReader, + split_path: PathBuf, + file_ranges: BundleFileRanges, + ) -> Self { + Self { + inner: Arc::new(SplitBundleInner { + reader, + split_path, + file_ranges, + }), + } + } + /// Opens a split bundle by locating its footer through `reader`. /// /// New splits expose the footer start in a fixed-size trailer. Legacy splits are supported by /// walking backward through the hotcache and bundle-metadata length fields. - pub async fn open_from_storage( - storage: Arc, - bundle_filepath: PathBuf, + pub async fn open( + reader: SplitStorageReader, + split_path: PathBuf, ) -> anyhow::Result<(Self, OwnedBytes, Range)> { - let split_len = storage.file_num_bytes(&bundle_filepath).await?; - let split_footer_range = - locate_split_footer_range(storage.as_ref(), &bundle_filepath, split_len).await?; + let split_len = reader.file_num_bytes(&split_path).await?; + let split_footer_range = locate_split_footer_range(&reader, &split_path, split_len).await?; let split_footer_range_usize = split_footer_range.start as usize..split_footer_range.end as usize; - let split_footer_bytes = storage - .get_slice(&bundle_filepath, split_footer_range_usize) + let split_footer_bytes = reader + .get_slice(&split_path, split_footer_range_usize) .await?; - let (bundle_storage, hotcache) = - Self::open_from_split_bytes(storage, bundle_filepath, split_footer_bytes)?; - Ok((bundle_storage, hotcache, split_footer_range)) + let (bundle, hotcache) = + Self::open_from_split_bytes(reader, split_path, split_footer_bytes)?; + Ok((bundle, hotcache, split_footer_range)) } - /// Opens a BundleStorage. + /// Opens a `SplitBundle` from already-fetched footer (or full split) bytes. /// - /// The provided bytes must include the footer bytes at the end of the slice, but they can have - /// more up front. + /// The provided bytes must include the footer bytes at the end of the slice, and may include + /// additional bytes up front. /// - /// Returns (Self, Hotcache) + /// Returns `(SplitBundle, hotcache_bytes)`. pub fn open_from_split_bytes( - storage: Arc, - bundle_filepath: PathBuf, + reader: SplitStorageReader, + split_path: PathBuf, split_bytes: OwnedBytes, ) -> anyhow::Result<(Self, OwnedBytes)> { let (file_ranges, hotcache) = BundleFileRanges::open_from_split_bytes(split_bytes)?; - Ok(( - BundleStorage { - storage, - bundle_filepath, - file_ranges, - }, - hotcache, - )) - } - - /// Returns Iterator over files contained in the bundle. - pub fn iter_files(&self) -> impl Iterator { - self.file_ranges.files.keys() + Ok((Self::from_parts(reader, split_path, file_ranges), hotcache)) } - /// Fetches a bundled file from a split. + /// Fetches a single bundled file from a split using a speculative tail read. /// /// Use this only when retrieving a single file from the split. To retrieve multiple files, - /// prefer [`Self::open_from_storage`]. + /// prefer [`Self::open`]. /// /// The split length is provided by the caller (e.g. from object listing metadata) to avoid a /// separate metadata request. /// - /// Returns a `(file_bytes, footer_range)` tuple: `file_bytes` holds the contents of - /// `bundle_filepath`, and `footer_range` is the split footer's byte range in `split_path`. + /// Returns `(file_bytes, footer_range)`. pub async fn fetch_file_from_split( - storage: Arc, + reader: &SplitStorageReader, bundle_filepath: PathBuf, split_path: &Path, split_len: u64, ) -> anyhow::Result<(OwnedBytes, Range)> { let (split_bytes, footer_range) = fetch_split_tail( - storage.as_ref(), + reader, split_path, split_len, DEFAULT_SPLIT_TAIL_WINDOW_NUM_BYTES, ) .await?; - // Parse the bundle file ranges from the split bytes. let tail_start = split_len - split_bytes.len() as u64; let (file_ranges, _hotcache) = BundleFileRanges::open_from_split_bytes(split_bytes.clone())?; @@ -137,8 +145,6 @@ impl BundleStorage { "bundled file range overlaps split footer" ); - // If the initial tail also contains the file, reuse it and complete in one GET (at least). - // Otherwise, fetch the file with an additional GET. let file_bytes = if file_range.start >= tail_start { let relative_start = (file_range.start - tail_start) as usize; let relative_end = (file_range.end - tail_start) as usize; @@ -146,12 +152,77 @@ impl BundleStorage { } else { let relative_start = file_range.start as usize; let relative_end = file_range.end as usize; - storage + reader .get_slice(split_path, relative_start..relative_end) .await? }; Ok((file_bytes, footer_range)) } + + /// Reads a byte range from a bundled file. + pub async fn get_slice(&self, path: &Path, range: Range) -> StorageResult { + let bundle_range = self.bundle_range(path, range)?; + self.inner + .reader + .get_slice(&self.inner.split_path, bundle_range) + .await + } + + /// Streams a byte range from a bundled file. + pub async fn get_slice_stream( + &self, + path: &Path, + range: Range, + ) -> StorageResult> { + let bundle_range = self.bundle_range(path, range)?; + self.inner + .reader + .get_slice_stream(&self.inner.split_path, bundle_range) + .await + } + + /// Streams multiple byte ranges from a bundled file in input order. + pub fn stream_ranges<'a>( + &'a self, + path: &Path, + ranges: Box> + Send>, + ) -> BoxStream<'a, io::Result> { + let file_start = match self.file_range(path) { + Ok(file_range) => file_range.start as usize, + Err(error) => { + return futures::stream::once(async move { Err(io::Error::from(error)) }).boxed(); + } + }; + let bundle_ranges = + Box::new(ranges.map(move |range| file_start + range.start..file_start + range.end)); + self.inner + .reader + .stream_ranges(&self.inner.split_path, bundle_ranges) + } + + /// Reads the entire contents of a bundled file. + pub async fn get_all(&self, path: &Path) -> StorageResult { + let file_range = self.file_range(path)?; + self.inner + .reader + .get_slice( + &self.inner.split_path, + file_range.start as usize..file_range.end as usize, + ) + .await + } + + fn file_range(&self, path: &Path) -> StorageResult> { + self.inner + .file_ranges + .get(path) + .ok_or_else(|| StorageErrorKind::NotFound.with_error(anyhow!("missing file {path:?}"))) + } + + fn bundle_range(&self, path: &Path, range: Range) -> StorageResult> { + let file_start = self.file_range(path)?.start as usize; + Ok(file_start + range.start..file_start + range.end) + } } const HOTCACHE_LEN_NUM_BYTES: usize = std::mem::size_of::(); @@ -197,7 +268,7 @@ fn deserialize_split_footer_trailer(trailer: &[u8]) -> anyhow::Result anyhow::Result> { @@ -207,13 +278,13 @@ pub async fn locate_split_footer_range( ); let end = split_len as usize; let start = end - SPLIT_FOOTER_TRAILER_NUM_BYTES; - let tail_bytes = storage.get_slice(split_path, start..end).await?; + let tail_bytes = reader.get_slice(split_path, start..end).await?; match locate_split_footer_range_in_tail(split_len, &tail_bytes)? { FooterLocation::Located(footer_range) => Ok(footer_range), FooterLocation::ReadBundleMetadataLen(bundle_metadata_len_range) => { let start = bundle_metadata_len_range.start as usize; let end = bundle_metadata_len_range.end as usize; - let bundle_metadata_len_bytes = storage.get_slice(split_path, start..end).await?; + let bundle_metadata_len_bytes = reader.get_slice(split_path, start..end).await?; locate_split_footer_range_from_metadata_len( split_len, bundle_metadata_len_range.start, @@ -291,17 +362,8 @@ fn locate_split_footer_range_in_tail( Ok(FooterLocation::Located(footer_range)) } -/// Reads the tail of a split until it holds the complete bundle footer. -/// -/// `initial_tail_window_num_bytes` is a jump-start hint: a larger window downloads more up front -/// but can save range GETs by covering the footer, and possibly the wanted file, in one read. -/// When the window falls short, the tail is re-read: once for a new split, whose trailer gives -/// the footer start, and up to twice for a legacy split, whose footer length is derived from the -/// trailing hotcache and bundle-metadata lengths. -/// -/// Returns the tail, which may start before the footer, and the footer range within the split. async fn fetch_split_tail( - storage: &dyn Storage, + reader: &SplitStorageReader, split_path: &Path, split_len: u64, initial_tail_window_num_bytes: u64, @@ -311,25 +373,17 @@ async fn fetch_split_tail( "split is too short to contain a footer" ); - // Start with the requested window, but always cover the fixed trailer and never read before - // the beginning of the split. let initial_tail_num_bytes = initial_tail_window_num_bytes.clamp(SPLIT_FOOTER_TRAILER_NUM_BYTES as u64, split_len); let mut tail_bytes = - read_split_tail(storage, split_path, split_len, initial_tail_num_bytes).await?; + read_split_tail(reader, split_path, split_len, initial_tail_num_bytes).await?; - // Locate the footer range. let footer_range = match locate_split_footer_range_in_tail(split_len, &tail_bytes)? { - FooterLocation::Located(footer_range) => { - // The range is known, but the initial tail may not contain the complete footer. - footer_range - } + FooterLocation::Located(footer_range) => footer_range, FooterLocation::ReadBundleMetadataLen(bundle_metadata_len_range) => { - // Extend the tail through the legacy bundle-metadata length field, then use that - // length to locate the beginning of the footer. let required_tail_num_bytes = split_len - bundle_metadata_len_range.start; let metadata_len_tail_bytes = - read_split_tail(storage, split_path, split_len, required_tail_num_bytes).await?; + read_split_tail(reader, split_path, split_len, required_tail_num_bytes).await?; match locate_split_footer_range_in_tail(split_len, &metadata_len_tail_bytes)? { FooterLocation::Located(footer_range) => footer_range, FooterLocation::ReadBundleMetadataLen(_) => { @@ -339,17 +393,15 @@ async fn fetch_split_tail( } }; - // If the initial tail does not contain the entire footer, fetch the exact footer range now - // that its boundaries are known. let footer_num_bytes = footer_range.end - footer_range.start; if (tail_bytes.len() as u64) < footer_num_bytes { - tail_bytes = read_split_tail(storage, split_path, split_len, footer_num_bytes).await?; + tail_bytes = read_split_tail(reader, split_path, split_len, footer_num_bytes).await?; } Ok((tail_bytes, footer_range)) } async fn read_split_tail( - storage: &dyn Storage, + reader: &SplitStorageReader, split_path: &Path, split_len: u64, tail_num_bytes: u64, @@ -359,7 +411,7 @@ async fn read_split_tail( "split tail exceeds split length" ); let start = (split_len - tail_num_bytes) as usize; - let tail_bytes = storage + let tail_bytes = reader .get_slice(split_path, start..split_len as usize) .await?; Ok(tail_bytes) @@ -421,11 +473,14 @@ pub struct BundleFileRanges { } impl BundleFileRanges { - /// File need to include split data (with hotcache at the end). - /// See docs/internals/split-format.md - /// [Files, BundleFileRanges, BundleMetadata Len, HotCache, HotCache Len, Split Footer Trailer] - /// Returns (Self, Hotcache) - fn open_from_split_bytes(split_bytes: OwnedBytes) -> anyhow::Result<(Self, OwnedBytes)> { + /// Parses bundle file ranges and hotcache bytes from a split tail (or full split). + /// + /// Layout (see `docs/internals/split-format.md`): + /// `[Files, BundleFileRanges, BundleMetadata Len, HotCache, HotCache Len, Split Footer + /// Trailer]` + /// + /// Returns `(BundleFileRanges, hotcache_bytes)`. + pub fn open_from_split_bytes(split_bytes: OwnedBytes) -> anyhow::Result<(Self, OwnedBytes)> { let split_slice = FileSlice::new(Arc::new(split_bytes)); let split_slice = strip_split_footer_trailer(split_slice)?; let (bundle_and_hotcache_bytes, hotcache_len_data) = @@ -436,9 +491,9 @@ impl BundleFileRanges { Ok((Self::open(bundle)?, hotcache.read_bytes()?)) } - /// FileSlice needs to end with the bundle (without hotcache from the split at the end). - /// See docs/internals/split-format.md - /// [Files, BundleFileRanges, BundleMetadata Len] + /// Parses bundle file ranges from a slice ending right after the bundle metadata length. + /// + /// Layout: `[Files, BundleFileRanges, BundleMetadata Len]`. pub fn open(file: FileSlice) -> anyhow::Result { let (bundle_and_metadata, bundle_metadata_len_data) = file.split_from_end(BUNDLE_METADATA_LEN_NUM_BYTES); @@ -467,200 +522,70 @@ impl BundleFileRanges { } } -impl BundleStorage { - fn file_range(&self, path: &Path) -> StorageResult> { - self.file_ranges - .get(path) - .ok_or_else(|| StorageErrorKind::NotFound.with_error(anyhow!("missing file {path:?}"))) - } - - fn bundle_range(&self, path: &Path, range: Range) -> StorageResult> { - let file_start = self.file_range(path)?.start as usize; - Ok(file_start + range.start..file_start + range.end) - } -} - -#[async_trait] -impl Storage for BundleStorage { - async fn check_connectivity(&self) -> anyhow::Result<()> { - if !self - .storage - .exists(&self.bundle_filepath) - .await - .unwrap_or(false) - { - bail!("`{}` not found in storage", self.bundle_filepath.display()) - } - Ok(()) - } - - async fn put( - &self, - path: &Path, - _payload: Box, - ) -> crate::StorageResult<()> { - Err(unsupported_operation(&[path])) - } - - async fn copy_to( - &self, - path: &Path, - output: &mut dyn SendableAsync, - ) -> crate::StorageResult<()> { - let file_len = self.file_num_bytes(path).await? as usize; - let block_size = 100_000_000; - for block in chunk_range(0..file_len, block_size) { - let file_content = self.get_slice(path, block).await?; - output.write_all(&file_content).await?; - } - output.flush().await?; - Ok(()) - } - - async fn get_slice( - &self, - path: &Path, - range: Range, - ) -> crate::StorageResult { - let bundle_range = self.bundle_range(path, range)?; - self.storage - .get_slice(&self.bundle_filepath, bundle_range) - .await - } - - async fn get_slice_into( - &self, - path: &Path, - range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - if buffer.is_empty() { - return Ok(()); - } - let bundle_range = self.bundle_range(path, range)?; - self.storage - .get_slice_into(&self.bundle_filepath, bundle_range, buffer) - .await - } - - async fn get_slice_stream( - &self, - path: &Path, - range: Range, - ) -> StorageResult> { - let bundle_range = self.bundle_range(path, range)?; - self.storage - .get_slice_stream(&self.bundle_filepath, bundle_range) - .await - } - - async fn get_all(&self, path: &Path) -> crate::StorageResult { - let file_range = self.file_range(path)?; - self.storage - .get_slice( - &self.bundle_filepath, - file_range.start as usize..file_range.end as usize, - ) - .await - } - - async fn delete(&self, path: &Path) -> crate::StorageResult<()> { - Err(unsupported_operation(&[path])) - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - Err(BulkDeleteError { - error: Some(unsupported_operation(paths)), - ..Default::default() - }) - } - - async fn exists(&self, path: &Path) -> crate::StorageResult { - // also check if self.bundle_file_name exists ? - Ok(self.file_ranges.exists(path)) - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - let file_range = self.file_range(path)?; - Ok(file_range.end - file_range.start) - } - - fn uri(&self) -> &Uri { - self.storage.uri() - } -} - -impl HasLen for BundleStorage { - fn len(&self) -> usize { - unimplemented!() - } -} - -impl fmt::Debug for BundleStorage { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "BundleStorage({:?}, files={:?})", - self.bundle_filepath, self.file_ranges - ) - } -} - -fn unsupported_operation(paths: &[&Path]) -> StorageError { - let msg = "Unsupported operation. BundleStorage only supports async reads"; - error!(paths=?paths, msg); - io::Error::other(format!("{msg}: {paths:?}")).into() -} - #[cfg(test)] mod tests { - use std::fs::{self, File}; - use std::io::Write; + use std::fs::File; + use std::io::{self, Write}; - use super::*; - use crate::{CountingStorage, PutPayload, RamStorageBuilder, SplitPayloadBuilder}; + use quickwit_common::uri::Uri; - const DEFAULT_SPLIT_TAIL_WINDOW_NUM_BYTES: u64 = 1024 * 1024; + use super::*; + use crate::{PutPayload, RamStorageBuilder, SplitPayloadBuilder, Storage}; #[tokio::test] async fn test_stream_maps_bundle_range_and_uses_cache_hits() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let (reader, mut writer) = tokio::io::duplex(1); + let (pipe_reader, mut writer) = tokio::io::duplex(1); let mut backend = crate::MockStorage::default(); backend - .expect_get_slice_stream() + .expect_uri() + .return_const(Uri::for_test("ram:///bucket")); + backend + .expect_get_slice_into() .once() - .return_once(|path, range| { + .returning(|path, range, buffer| { assert_eq!((path, range), (Path::new("split"), 102..105)); - Ok(Box::new(reader)) + buffer.copy_from_slice(b"abc"); + Ok(()) }); - let mut cache = crate::MockStorageCache::default(); - let mut cached_reader = Some(&b"abc"[..]); - cache + backend .expect_get_slice_stream() - .times(2) - .returning(move |path, range| { - assert_eq!((path, range), (Path::new("split"), 102..105)); - // Hit on the first read, miss on the second. Any insertion fails the test. - Some(Box::new(cached_reader.take()?)) + .once() + .return_once(|path, range| { + assert_eq!((path, range), (Path::new("split"), 105..108)); + Ok(Box::new(pipe_reader)) }); - let storage = BundleStorage { - storage: crate::wrap_storage_with_cache(Arc::new(cache), Arc::new(backend)), - bundle_filepath: PathBuf::from("split"), - file_ranges: BundleFileRanges { + let cache = feuer::Cache::builder() + .memory_capacity(1024) + .open() + .unwrap(); + let reader = SplitStorageReader::new(Arc::new(backend)).with_storage_cache(cache); + let bundle = SplitBundle::from_parts( + reader, + PathBuf::from("split"), + BundleFileRanges { files: HashMap::from([(PathBuf::from("file"), 100..110)]), }, - }; - let err = storage + ); + let err = bundle .get_slice_stream(Path::new("missing"), 0..1) .await .err() .unwrap(); assert_eq!(err.kind(), crate::StorageErrorKind::NotFound); + // Populate `file[2..5]` (`split[102..105]`) in Feuer, then stream it from cache. + assert_eq!( + bundle + .get_slice(Path::new("file"), 2..5) + .await + .unwrap() + .as_slice(), + b"abc" + ); let mut bytes = Vec::new(); - storage + bundle .get_slice_stream(Path::new("file"), 2..5) .await .unwrap() @@ -669,8 +594,9 @@ mod tests { .unwrap(); assert_eq!(bytes, b"abc"); - let mut stream = storage - .get_slice_stream(Path::new("file"), 2..5) + // Uncached range `file[5..8]` (`split[105..108]`) streams directly from backend. + let mut stream = bundle + .get_slice_stream(Path::new("file"), 5..8) .await .unwrap(); writer.write_all(b"a").await.unwrap(); @@ -683,7 +609,7 @@ mod tests { } #[tokio::test] - async fn bundle_storage_locates_footer_from_object_storage() { + async fn split_bundle_locates_footer_from_object_storage() { let mut split_payload_builder = SplitPayloadBuilder::default(); split_payload_builder.add_payload("fields".to_string(), Box::new(b"fields".to_vec())); let split_payload = split_payload_builder @@ -698,8 +624,8 @@ mod tests { .build(), ); - let (_bundle_storage, hotcache, footer_range) = - BundleStorage::open_from_storage(storage, split_path) + let (_bundle, hotcache, footer_range) = + SplitBundle::open(SplitStorageReader::new(storage), split_path) .await .unwrap(); @@ -708,7 +634,7 @@ mod tests { } #[tokio::test] - async fn bundle_storage_locates_legacy_footer_from_object_storage() { + async fn split_bundle_locates_legacy_footer_from_object_storage() { let split_payload = SplitPayloadBuilder::get_split_payload(&[], b"fields", None, b"hotcache").unwrap(); let expected_footer_range = split_payload.footer_range.clone(); @@ -719,12 +645,11 @@ mod tests { .put(&split_path.to_string_lossy(), &split_bytes) .build(), ); - let (storage, counters) = CountingStorage::instrument_storage(inner_storage); + let reader = SplitStorageReader::new(inner_storage); + let counters = reader.download_counters().clone(); - let (_bundle_storage, hotcache, footer_range) = - BundleStorage::open_from_storage(storage, split_path) - .await - .unwrap(); + let (_bundle, hotcache, footer_range) = + SplitBundle::open(reader, split_path).await.unwrap(); assert_eq!(hotcache.as_ref(), b"hotcache"); assert_eq!(footer_range, expected_footer_range); @@ -732,7 +657,7 @@ mod tests { } #[tokio::test] - async fn bundle_storage_locates_legacy_footer_with_large_hotcache() { + async fn split_bundle_locates_legacy_footer_with_large_hotcache() { let hotcache_bytes = vec![0u8; 1024]; let split_payload = SplitPayloadBuilder::get_split_payload(&[], b"fields", None, &hotcache_bytes).unwrap(); @@ -744,12 +669,11 @@ mod tests { .put(&split_path.to_string_lossy(), &split_bytes) .build(), ); - let (storage, counters) = CountingStorage::instrument_storage(inner_storage); + let reader = SplitStorageReader::new(inner_storage); + let counters = reader.download_counters().clone(); - let (_bundle_storage, hotcache, footer_range) = - BundleStorage::open_from_storage(storage, split_path) - .await - .unwrap(); + let (_bundle, hotcache, footer_range) = + SplitBundle::open(reader, split_path).await.unwrap(); assert_eq!(hotcache.as_ref(), hotcache_bytes.as_slice()); assert_eq!(footer_range, expected_footer_range); @@ -784,72 +708,22 @@ mod tests { .put(&bundle_filepath.to_string_lossy(), &buffer) .build(); - let bundle_storage = BundleStorage { - file_ranges, - bundle_filepath: bundle_filepath.to_path_buf(), - storage: Arc::new(ram_storage), - }; - let f1_data = bundle_storage.get_all(Path::new("f1")).await?; - assert_eq!(&*f1_data, &[123u8, 76u8]); - - let f2_data = bundle_storage.get_all(Path::new("f2")).await?; - assert_eq!(&f2_data[..], &[99, 55, 44]); - - Ok(()) - } - - #[tokio::test] - async fn bundle_storage_test() -> anyhow::Result<()> { - let temp_dir = tempfile::tempdir()?; - let test_filepath1 = temp_dir.path().join("f1"); - let test_filepath2 = temp_dir.path().join("f2"); - - let mut file1 = File::create(&test_filepath1)?; - file1.write_all(&[123, 76])?; - - let mut file2 = File::create(&test_filepath2)?; - file2.write_all(&[99, 55, 44])?; - - let buffer = SplitPayloadBuilder::get_split_payload( - &[test_filepath1.clone(), test_filepath2.clone()], - &[], - None, - &[1, 3, 3, 7], - )? - .read_all() - .await?; - - let (file_ranges, hotcache) = BundleFileRanges::open_from_split_bytes(buffer.clone())?; - assert_eq!(hotcache.as_ref(), &[1, 3, 3, 7]); - - let bundle_filepath = Path::new("bundle"); - let ram_storage = RamStorageBuilder::default() - .put(&bundle_filepath.to_string_lossy(), &buffer) - .build(); - - let bundle_storage = BundleStorage { + let bundle = SplitBundle::from_parts( + SplitStorageReader::new(Arc::new(ram_storage)), + bundle_filepath.to_path_buf(), file_ranges, - bundle_filepath: bundle_filepath.to_path_buf(), - storage: Arc::new(ram_storage), - }; - let f1_data = bundle_storage.get_all(Path::new("f1")).await?; + ); + let f1_data = bundle.get_all(Path::new("f1")).await?; assert_eq!(&*f1_data, &[123u8, 76u8]); - let f2_data = bundle_storage.get_all(Path::new("f2")).await?; + let f2_data = bundle.get_all(Path::new("f2")).await?; assert_eq!(&f2_data[..], &[99, 55, 44]); - let copy_to_file = temp_dir.path().join("copy_file"); - bundle_storage - .copy_to_file(Path::new("f2"), ©_to_file) - .await?; - let file_content = fs::read(copy_to_file).unwrap(); - assert_eq!(&f2_data[..], file_content); - Ok(()) } #[tokio::test] - async fn bundlestorage_test_empty() -> anyhow::Result<()> { + async fn split_bundle_test_empty() -> anyhow::Result<()> { let buffer = SplitPayloadBuilder::get_split_payload(&[], &[], None, &[])? .read_all() .await?; @@ -860,13 +734,13 @@ mod tests { let ram_storage = RamStorageBuilder::default() .put(&bundle_filepath.to_string_lossy(), &buffer) .build(); - let bundle_storage = BundleStorage { - file_ranges, + let bundle = SplitBundle::from_parts( + SplitStorageReader::new(Arc::new(ram_storage)), bundle_filepath, - storage: Arc::new(ram_storage), - }; + file_ranges, + ); - assert_eq!(bundle_storage.exists(Path::new("blub")).await?, false); + assert!(!bundle.inner.file_ranges.exists(Path::new("blub"))); Ok(()) } @@ -889,10 +763,11 @@ mod tests { .put("split", &split_bytes) .build(), ); - let (storage, counters) = CountingStorage::instrument_storage(inner_storage); + let reader = SplitStorageReader::new(inner_storage); + let counters = reader.download_counters().clone(); - let (target_bytes, footer_range) = BundleStorage::fetch_file_from_split( - storage, + let (target_bytes, footer_range) = SplitBundle::fetch_file_from_split( + &reader, PathBuf::from("target"), Path::new("split"), split_bytes.len() as u64, @@ -920,10 +795,11 @@ mod tests { .put("split", &split_bytes) .build(), ); - let (storage, counters) = CountingStorage::instrument_storage(inner_storage); + let reader = SplitStorageReader::new(inner_storage); + let counters = reader.download_counters().clone(); - let (target_bytes, footer_range) = BundleStorage::fetch_file_from_split( - storage, + let (target_bytes, footer_range) = SplitBundle::fetch_file_from_split( + &reader, PathBuf::from("target"), Path::new("split"), split_bytes.len() as u64, diff --git a/quickwit/quickwit-storage/src/split_cache/mod.rs b/quickwit/quickwit-storage/src/split_cache/mod.rs index 86b62fb2947..7792522dddb 100644 --- a/quickwit/quickwit-storage/src/split_cache/mod.rs +++ b/quickwit/quickwit-storage/src/split_cache/mod.rs @@ -23,7 +23,6 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::{Arc, Mutex}; -use async_trait::async_trait; use quickwit_common::split_file; use quickwit_common::uri::Uri; use quickwit_config::SplitCacheLimits; @@ -36,7 +35,6 @@ use tracing::{error, info, instrument, warn}; use crate::file_descriptor_cache::{FileDescriptorCache, SplitFile}; use crate::split_cache::download_task::spawn_download_task; use crate::split_cache::split_table::SplitTable; -use crate::{Storage, StorageCache, wrap_storage_with_cache}; /// On disk Cache of splits for searchers. /// @@ -126,13 +124,40 @@ impl SearchSplitCache { delete_evicted_splits(&self.root_path, splits_to_evict); } - /// Wraps a storage with our split cache. - pub fn wrap_storage(self_arc: Arc, storage: Arc) -> Arc { - let cache = Arc::new(SplitCacheBackingStorage { - split_cache: self_arc, - storage_root_uri: storage.uri().clone(), - }); - wrap_storage_with_cache(cache, storage) + /// Reads a byte slice from a locally cached split file if present. + pub async fn get_slice( + &self, + storage_root_uri: &Uri, + path: &Path, + byte_range: Range, + ) -> Option { + let result = match self.get_split_file_by_path(storage_root_uri, path).await { + Some(file) => file.get_range(byte_range).await.ok(), + None => None, + }; + crate::metrics::SEARCHER_SPLIT_CACHE.record_get(result.as_ref().map(|bytes| bytes.len())); + result + } + + /// Streams a byte slice from a locally cached split file if present. + pub async fn get_slice_stream( + &self, + storage_root_uri: &Uri, + path: &Path, + byte_range: Range, + ) -> Option> { + let file = self.get_split_file_by_path(storage_root_uri, path).await; + crate::metrics::SEARCHER_SPLIT_CACHE.record_get(file.as_ref().map(|_| byte_range.len())); + Some(Box::new(file?.get_range_stream(byte_range))) + } + + async fn get_split_file_by_path( + &self, + storage_root_uri: &Uri, + path: &Path, + ) -> Option { + self.get_split_file(split_id_from_path(path)?, storage_root_uri) + .await } /// Report the split cache about the existence of new splits. @@ -154,15 +179,13 @@ impl SearchSplitCache { async fn get_split_file(&self, split_id: SplitId, storage_uri: &Uri) -> Option { // We touch before even checking the fd cache in order to update the file's last access time // for the file cache. - let num_bytes_opt: Option = self + let _num_bytes = self .split_table .lock() .unwrap() - .touch(split_id.clone(), storage_uri); - - let num_bytes = num_bytes_opt?; + .touch(split_id.clone(), storage_uri)?; self.fd_cache - .get_or_open_split_file(&self.root_path, split_id, num_bytes) + .get_or_open_split_file(&self.root_path, split_id) .await .ok() } @@ -193,63 +216,6 @@ fn split_id_from_path(split_path: &Path) -> Option { Some(SplitId::from(split_id_str)) } -struct SplitCacheBackingStorage { - split_cache: Arc, - storage_root_uri: Uri, -} - -impl SplitCacheBackingStorage { - async fn get_split_file(&self, path: &Path) -> Option { - self.split_cache - .get_split_file(split_id_from_path(path)?, &self.storage_root_uri) - .await - } - - fn record_hit_metrics(&self, hit_num_bytes: Option) { - let split_metrics = &crate::metrics::SEARCHER_SPLIT_CACHE.cache_metrics; - if let Some(num_bytes) = hit_num_bytes { - split_metrics.hits_num_items.inc(); - split_metrics.hits_num_bytes.inc_by(num_bytes as u64); - } else { - split_metrics.misses_num_items.inc(); - } - } -} - -#[async_trait] -impl StorageCache for SplitCacheBackingStorage { - async fn get(&self, path: &Path, byte_range: Range) -> Option { - let result = match self.get_split_file(path).await { - Some(file) => file.get_range(byte_range).await.ok(), - None => None, - }; - self.record_hit_metrics(result.as_ref().map(|bytes| bytes.len())); - result - } - - async fn get_slice_stream( - &self, - path: &Path, - byte_range: Range, - ) -> Option> { - let file = self.get_split_file(path).await; - self.record_hit_metrics(file.as_ref().map(|_| byte_range.len())); - Some(Box::new(file?.get_range_stream(byte_range))) - } - - async fn get_all(&self, path: &Path) -> Option { - let result = match self.get_split_file(path).await { - Some(file) => file.get_all().await.ok(), - None => None, - }; - self.record_hit_metrics(result.as_ref().map(|bytes| bytes.len())); - result - } - - async fn put(&self, _path: PathBuf, _byte_range: Range, _bytes: OwnedBytes) {} - async fn put_all(&self, _path: PathBuf, _bytes: OwnedBytes) {} -} - #[cfg(test)] mod tests { use std::num::NonZeroU32; @@ -259,7 +225,7 @@ mod tests { use tokio::io::AsyncReadExt; use super::*; - use crate::{RamStorage, StorageResolver}; + use crate::{RamStorage, SplitStorageReader, StorageResolver}; #[tokio::test] async fn split_cache_stream_reads_on_demand_across_eviction() { @@ -280,15 +246,15 @@ mod tests { }, ) .unwrap(); - let storage = - SearchSplitCache::wrap_storage(cache.clone(), Arc::new(RamStorage::default())); - let mut reader = storage.get_slice_stream(path, 7..range_end).await.unwrap(); - assert_eq!(reader.read_u8().await.unwrap(), b'a'); + let reader = SplitStorageReader::new(Arc::new(RamStorage::default())) + .with_split_cache(cache.clone()); + let mut stream = reader.get_slice_stream(path, 7..range_end).await.unwrap(); + assert_eq!(stream.read_u8().await.unwrap(), b'a'); cache.evict(&[SplitId::from("cached")]); // Change the unread tail through the open descriptor to detect eager buffering. file.write_all_at(b"bc", range_end as u64 - 1).unwrap(); let mut remaining_bytes = Vec::new(); - reader.read_to_end(&mut remaining_bytes).await.unwrap(); + stream.read_to_end(&mut remaining_bytes).await.unwrap(); assert_eq!( (remaining_bytes.len(), remaining_bytes.last()), (range_end - 8, Some(&b'b')) diff --git a/quickwit/quickwit-storage/src/split_cache/split_table.rs b/quickwit/quickwit-storage/src/split_cache/split_table.rs index c673c392325..164f0ea74ac 100644 --- a/quickwit/quickwit-storage/src/split_cache/split_table.rs +++ b/quickwit/quickwit-storage/src/split_cache/split_table.rs @@ -154,16 +154,12 @@ impl SplitTable { Status::Downloading { .. } => &mut self.downloading_splits, Status::OnDisk { num_bytes } => { self.on_disk_bytes -= num_bytes; - SEARCHER_SPLIT_CACHE.cache_metrics.in_cache_count.dec(); + SEARCHER_SPLIT_CACHE.in_cache_count.dec(); SEARCHER_SPLIT_CACHE - .cache_metrics .in_cache_num_bytes .dec_by(num_bytes as f64); - SEARCHER_SPLIT_CACHE.cache_metrics.evict_num_items.inc(); - SEARCHER_SPLIT_CACHE - .cache_metrics - .evict_num_bytes - .inc_by(num_bytes); + SEARCHER_SPLIT_CACHE.evict_num_items.inc(); + SEARCHER_SPLIT_CACHE.evict_num_bytes.inc_by(num_bytes); &mut self.on_disk_splits } }; @@ -214,9 +210,8 @@ impl SplitTable { } Status::OnDisk { num_bytes } => { self.on_disk_bytes += num_bytes; - SEARCHER_SPLIT_CACHE.cache_metrics.in_cache_count.inc(); + SEARCHER_SPLIT_CACHE.in_cache_count.inc(); SEARCHER_SPLIT_CACHE - .cache_metrics .in_cache_num_bytes .inc_by(num_bytes as f64); self.on_disk_splits.insert(split_info.split_key.clone()) diff --git a/quickwit/quickwit-storage/src/split_storage_reader.rs b/quickwit/quickwit-storage/src/split_storage_reader.rs new file mode 100644 index 00000000000..e9b9e5bfe92 --- /dev/null +++ b/quickwit/quickwit-storage/src/split_storage_reader.rs @@ -0,0 +1,463 @@ +// Copyright 2021-Present Datadog, Inc. +// +// Licensed 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. + +mod coalesced_range_stream; + +use std::ops::Range; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::{fmt, io}; + +use futures::stream::BoxStream; +use quickwit_common::uri::Uri; +use quickwit_config::StorageTimeoutPolicy; +use tantivy::directory::OwnedBytes; +use tokio::io::AsyncRead; + +use crate::debouncer::StorageDebouncer; +use crate::storage_cache::{get_slice_from_storage_cache, try_get_slice_from_storage_cache}; +use crate::timeout_and_retry::retry_with_timeout; +use crate::{SearchSplitCache, Storage, StorageErrorKind, StorageResult}; + +/// Per-request download counters tracked by [`SplitStorageReader`]. +/// +/// `bytes` accumulates the size of every successfully fulfilled backend download; `requests` +/// counts each backend read request. Cache hits (`storage_cache`, `split_cache`, hotcache, +/// short-lived cache) return before reaching the backend, so the counters measure downloads +/// from object storage. +#[derive(Debug, Default)] +pub struct DownloadCounters { + bytes: AtomicU64, + requests: AtomicU64, +} + +impl DownloadCounters { + /// Snapshots the current counters as `(bytes, requests)`. + pub fn snapshot(&self) -> (u64, u64) { + ( + self.bytes.load(Ordering::Relaxed), + self.requests.load(Ordering::Relaxed), + ) + } + + pub(crate) fn record_read(&self, num_bytes: u64) { + self.bytes.fetch_add(num_bytes, Ordering::Relaxed); + self.requests.fetch_add(1, Ordering::Relaxed); + } +} + +/// Static read pipeline for immutable split files in object storage. +/// +/// Every read passes through the configured stages in a fixed order: +/// +/// 1. `storage_cache` (`feuer::Cache`, canonical slice cache; checked per range in +/// [`Self::stream_ranges`] only when fewer than 10 ranges are requested, without inserting +/// misses) +/// 2. range coalescing (for [`Self::stream_ranges`], bridging nearby gaps up to 4 MiB) +/// 3. `split_cache` (`SearchSplitCache`, optional whole-split local disk cache) +/// 4. `debouncer` (`StorageDebouncer`, skipped for `storage_cache` buffered reads because `feuer` +/// already deduplicates concurrent misses node-globally) +/// 5. `timeout_policy` (retries fresh backend attempts inside the debounced work) +/// 6. `download_counters` (counts successful downloads from `backend`) +/// 7. `backend` (`Arc`) +/// +/// Deliberately does not implement [`Storage`]: it only exposes immutable split reads. +#[derive(Clone)] +pub struct SplitStorageReader { + backend: Arc, + storage_cache: Option, + split_cache: Option>, + debouncer: Option>, + timeout_policy: Option, + download_counters: Arc, +} + +impl fmt::Debug for SplitStorageReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SplitStorageReader") + .field("uri", self.backend.uri()) + .field("storage_cache", &self.storage_cache.is_some()) + .field("split_cache", &self.split_cache.is_some()) + .field("debouncer", &self.debouncer.is_some()) + .field("timeout_policy", &self.timeout_policy) + .field("download_counters", &self.download_counters.snapshot()) + .finish() + } +} + +impl SplitStorageReader { + /// Creates a reader directly backed by `backend` with no cache, debouncer, or timeout policy. + pub fn new(backend: Arc) -> Self { + Self { + backend, + storage_cache: None, + split_cache: None, + debouncer: None, + timeout_policy: None, + download_counters: Arc::new(DownloadCounters::default()), + } + } + + /// Configures the canonical exact-slice cache (`feuer::Cache`). + pub fn with_storage_cache(mut self, storage_cache: feuer::Cache) -> Self { + self.storage_cache = Some(storage_cache); + self + } + + /// Configures the optional whole-split local disk cache (`SearchSplitCache`). + pub fn with_split_cache(mut self, split_cache: Arc) -> Self { + self.split_cache = Some(split_cache); + self + } + + /// Configures concurrent read deduplication. + pub fn with_debouncer(mut self, debouncer: Arc) -> Self { + self.debouncer = Some(debouncer); + self + } + + /// Configures timeout-and-retry behavior for backend slice and stream-open calls. + pub fn with_timeout_policy(mut self, timeout_policy: StorageTimeoutPolicy) -> Self { + self.timeout_policy = Some(timeout_policy); + self + } + + /// Returns the download counters shared by this reader and its clones. + pub fn download_counters(&self) -> &Arc { + &self.download_counters + } + + /// Returns the root URI of the underlying storage backend. + pub fn uri(&self) -> &Uri { + self.backend.uri() + } + + /// Returns the total byte size of an object in the underlying storage backend. + pub async fn file_num_bytes(&self, path: &Path) -> StorageResult { + self.backend.file_num_bytes(path).await + } + + /// Reads an exact byte slice through the configured cache, debouncer, timeout/retry, and + /// backend pipeline. + pub async fn get_slice(&self, path: &Path, range: Range) -> StorageResult { + if range.is_empty() { + return Ok(OwnedBytes::empty()); + } + if let Some(cache) = &self.storage_cache { + let backend = self.backend.clone(); + let split_cache = self.split_cache.clone(); + let timeout_policy = self.timeout_policy.clone(); + let download_counters = self.download_counters.clone(); + let path_owned = path.to_owned(); + let range_clone = range.clone(); + return get_slice_from_storage_cache( + cache, + self.backend.uri(), + path, + range, + move |buffer| { + Box::pin(async move { + if let Some(split_cache) = &split_cache + && let Some(bytes) = split_cache + .get_slice(backend.uri(), &path_owned, range_clone.clone()) + .await + { + if bytes.len() != buffer.len() { + return Err(StorageErrorKind::Io.with_error(anyhow::anyhow!( + "split cache returned {} bytes for range {range_clone:?}", + bytes.len() + ))); + } + buffer.copy_from_slice(&bytes); + return Ok(()); + } + fetch_slice_into_with_timeout( + backend.as_ref(), + timeout_policy.as_ref(), + &path_owned, + range_clone, + buffer, + ) + .await?; + download_counters.record_read(buffer.len() as u64); + Ok(()) + }) + }, + ) + .await; + } + if let Some(split_cache) = &self.split_cache + && let Some(bytes) = split_cache + .get_slice(self.backend.uri(), path, range.clone()) + .await + { + return Ok(bytes); + } + self.fetch_slice_uncached(path, range).await + } + + /// Streams an exact byte slice through the configured pipeline. + /// + /// Cache hits in `storage_cache` or `split_cache` are served directly. Cache misses stream + /// through the configured debouncer and timeout/retry without inserting into `storage_cache`. + pub async fn get_slice_stream( + &self, + path: &Path, + range: Range, + ) -> StorageResult> { + if range.is_empty() { + return Ok(Box::new(tokio::io::empty())); + } + if let Some(cache) = &self.storage_cache + && let Some(bytes) = + try_get_slice_from_storage_cache(cache, self.backend.uri(), path, &range).await? + { + return Ok(Box::new(io::Cursor::new(bytes))); + } + self.get_slice_stream_uncached(path, range).await + } + + /// Streams multiple byte ranges from `path` in input order, coalescing nearby ranges right + /// above `debouncer`. + /// + /// When `storage_cache` is configured and fewer than 10 ranges are requested, each range is + /// checked in `storage_cache` first (serving hits without touching the backend) and only + /// misses are coalesced and streamed without inserting into `storage_cache`. Larger range + /// lists skip `storage_cache` lookups and coalesce directly. + pub fn stream_ranges<'a>( + &'a self, + path: &'a Path, + ranges: Box> + Send>, + ) -> BoxStream<'a, io::Result> { + coalesced_range_stream::stream_ranges(self, path, ranges) + } + + pub(super) async fn get_slice_stream_uncached( + &self, + path: &Path, + range: Range, + ) -> StorageResult> { + if let Some(split_cache) = &self.split_cache + && let Some(stream) = split_cache + .get_slice_stream(self.backend.uri(), path, range.clone()) + .await + { + return Ok(stream); + } + let range_len = range.len() as u64; + let stream = match &self.debouncer { + Some(debouncer) => { + let backend = self.backend.clone(); + let timeout_policy = self.timeout_policy.clone(); + let path_owned = path.to_owned(); + let range_clone = range.clone(); + debouncer + .get_slice_stream(self.backend.uri(), path, range, move || async move { + open_slice_stream_with_timeout( + backend.as_ref(), + timeout_policy.as_ref(), + &path_owned, + range_clone, + ) + .await + }) + .await? + } + None => { + open_slice_stream_with_timeout( + self.backend.as_ref(), + self.timeout_policy.as_ref(), + path, + range, + ) + .await? + } + }; + self.download_counters.record_read(range_len); + Ok(stream) + } + + async fn fetch_slice_uncached( + &self, + path: &Path, + range: Range, + ) -> StorageResult { + let bytes = match &self.debouncer { + Some(debouncer) => { + let backend = self.backend.clone(); + let timeout_policy = self.timeout_policy.clone(); + let path_owned = path.to_owned(); + let range_clone = range.clone(); + debouncer + .get_slice(self.backend.uri(), path, range, move || async move { + fetch_slice_with_timeout( + backend.as_ref(), + timeout_policy.as_ref(), + &path_owned, + range_clone, + ) + .await + }) + .await? + } + None => { + fetch_slice_with_timeout( + self.backend.as_ref(), + self.timeout_policy.as_ref(), + path, + range, + ) + .await? + } + }; + self.download_counters.record_read(bytes.len() as u64); + Ok(bytes) + } +} + +async fn fetch_slice_with_timeout( + backend: &dyn Storage, + timeout_policy: Option<&StorageTimeoutPolicy>, + path: &Path, + range: Range, +) -> StorageResult { + match timeout_policy { + Some(policy) => { + retry_with_timeout( + backend, + policy, + path, + range.len(), + range.len(), + &mut (), + |storage, path, _| storage.get_slice(path, range.clone()), + ) + .await + } + None => backend.get_slice(path, range).await, + } +} + +async fn fetch_slice_into_with_timeout( + backend: &dyn Storage, + timeout_policy: Option<&StorageTimeoutPolicy>, + path: &Path, + range: Range, + buffer: &mut [u8], +) -> StorageResult<()> { + match timeout_policy { + Some(policy) => { + // The timeout covers the whole body read. Each retry overwrites the same buffer, + // and cancellation drops the previous stream. + retry_with_timeout( + backend, + policy, + path, + range.len(), + range.len(), + buffer, + |storage, path, buffer| storage.get_slice_into(path, range.clone(), buffer), + ) + .await + } + None => backend.get_slice_into(path, range, buffer).await, + } +} + +async fn open_slice_stream_with_timeout( + backend: &dyn Storage, + timeout_policy: Option<&StorageTimeoutPolicy>, + path: &Path, + range: Range, +) -> StorageResult> { + match timeout_policy { + Some(policy) => { + // Only opening the stream is timed and retried. Mid-body stalls rely on outer + // deadlines. + retry_with_timeout( + backend, + policy, + path, + range.len(), + 0, + &mut (), + |storage, path, _| storage.get_slice_stream(path, range.clone()), + ) + .await + } + None => backend.get_slice_stream(path, range).await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::RamStorageBuilder; + + #[tokio::test] + async fn test_download_counters_track_slice_and_stream_misses_and_skip_cache_hits() { + let backend = Arc::new( + RamStorageBuilder::default() + .put("foo", b"hello world") + .build(), + ); + let cache = feuer::Cache::builder() + .memory_capacity(1024) + .open() + .unwrap(); + let reader = SplitStorageReader::new(backend).with_storage_cache(cache); + let counters = reader.download_counters().clone(); + + assert_eq!( + reader + .get_slice(Path::new("foo"), 0..5) + .await + .unwrap() + .as_slice(), + b"hello" + ); + assert_eq!(counters.snapshot(), (5, 1)); + + // Second read hits storage_cache and must not increment download counters. + assert_eq!( + reader + .get_slice(Path::new("foo"), 0..5) + .await + .unwrap() + .as_slice(), + b"hello" + ); + assert_eq!(counters.snapshot(), (5, 1)); + + // Streaming the cached range hits storage_cache and does not increment counters. + let _cached_stream = reader + .get_slice_stream(Path::new("foo"), 0..5) + .await + .unwrap(); + assert_eq!(counters.snapshot(), (5, 1)); + + // Streaming an uncached range misses and increments counters. + let _missed_stream = reader + .get_slice_stream(Path::new("foo"), 6..11) + .await + .unwrap(); + assert_eq!(counters.snapshot(), (10, 2)); + + // Failed reads and metadata calls must not increment counters. + assert!(reader.get_slice(Path::new("missing"), 0..5).await.is_err()); + assert_eq!(reader.file_num_bytes(Path::new("foo")).await.unwrap(), 11); + assert_eq!(counters.snapshot(), (10, 2)); + } +} diff --git a/quickwit/quickwit-directories/src/storage_directory/coalesced_range_stream.rs b/quickwit/quickwit-storage/src/split_storage_reader/coalesced_range_stream.rs similarity index 59% rename from quickwit/quickwit-directories/src/storage_directory/coalesced_range_stream.rs rename to quickwit/quickwit-storage/src/split_storage_reader/coalesced_range_stream.rs index 7a112a6b830..a0be3efffe3 100644 --- a/quickwit/quickwit-directories/src/storage_directory/coalesced_range_stream.rs +++ b/quickwit/quickwit-storage/src/split_storage_reader/coalesced_range_stream.rs @@ -18,15 +18,21 @@ use std::ops::Range; use std::path::Path; use futures::stream::{BoxStream, StreamExt, TryStreamExt}; -use quickwit_storage::{OwnedBytes, Storage}; +use tantivy::directory::OwnedBytes; use tantivy_common::VInt; use tokio::io::{AsyncRead, AsyncReadExt, BufReader}; +use super::SplitStorageReader; +use crate::storage_cache::try_get_slice_from_storage_cache; + // Bridge byte gaps up to this size into the same download to issue fewer storage requests. const MAX_GAP_BYTES: usize = 4 * 1024 * 1024; // Yield after coalescing this many ranges so Tokio workers stay responsive and observe // cancellation on large range lists. const COALESCE_YIELD_INTERVAL: usize = 4_096; +// Per-range `storage_cache` lookups are only worthwhile for small range lists; larger automaton +// queries skip per-range lookups and go straight to range coalescing. +const MAX_STORAGE_CACHE_LOOKUP_RANGES: usize = 9; /// Delta-encoded `(gap, len)` `VInt` pairs for one download. /// @@ -83,9 +89,68 @@ async fn coalesce_ranges( Some((download_range, encoded_ranges)) } +/// Streams `ranges` from `path` in input order. +/// +/// Checks `storage_cache` per range when fewer than 10 ranges are requested, coalescing misses +/// above `debouncer`. Larger range lists skip `storage_cache` lookups and coalesce directly. +pub(super) fn stream_ranges<'a>( + reader: &'a SplitStorageReader, + path: &'a Path, + mut ranges: Box> + Send>, +) -> BoxStream<'a, io::Result> { + let Some(cache) = &reader.storage_cache else { + return download_ranges(reader, path, ranges); + }; + futures::stream::once(async move { + let mut head = Vec::with_capacity(MAX_STORAGE_CACHE_LOOKUP_RANGES + 1); + for range in ranges.by_ref().take(MAX_STORAGE_CACHE_LOOKUP_RANGES + 1) { + head.push(range); + } + if head.len() > MAX_STORAGE_CACHE_LOOKUP_RANGES { + let all_ranges = Box::new(head.into_iter().chain(ranges)); + return io::Result::Ok(download_ranges(reader, path, all_ranges)); + } + let slots = futures::future::try_join_all(head.iter().map(|range| { + try_get_slice_from_storage_cache(cache, reader.backend.uri(), path, range) + })) + .await?; + let misses: Vec> = head + .into_iter() + .zip(&slots) + .filter_map(|(range, cached)| cached.is_none().then_some(range)) + .collect(); + let miss_stream = download_ranges(reader, path, Box::new(misses.into_iter())); + let interleaved = futures::stream::try_unfold( + (slots.into_iter(), miss_stream), + |(mut slots, mut miss_stream)| async move { + let Some(slot) = slots.next() else { + return Ok(None); + }; + let bytes = match slot { + Some(cached_bytes) => cached_bytes, + None => miss_stream.try_next().await?.ok_or_else(|| { + io::Error::new( + io::ErrorKind::UnexpectedEof, + "coalesced miss stream ended early", + ) + })?, + }; + Ok(Some((bytes, (slots, miss_stream)))) + }, + ) + .boxed(); + Ok(interleaved) + }) + .try_flatten() + .boxed() +} + /// Download nearby ranges together and yield each range's bytes in input order. -pub(super) fn download_ranges<'a>( - storage: &'a dyn Storage, +/// +/// Opens each coalesced download through [`SplitStorageReader::get_slice_stream_uncached`] +/// (sitting directly above the debouncer). +fn download_ranges<'a>( + reader: &'a SplitStorageReader, path: &'a Path, ranges: Box> + Send>, ) -> BoxStream<'a, io::Result> { @@ -96,7 +161,9 @@ pub(super) fn download_ranges<'a>( let stream: Box = if download_range.is_empty() { Box::new(tokio::io::empty()) } else { - storage.get_slice_stream(path, download_range).await? + reader + .get_slice_stream_uncached(path, download_range) + .await? }; let download = futures::stream::try_unfold( (BufReader::new(stream), encoded_ranges), @@ -130,10 +197,13 @@ mod tests { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; - use quickwit_storage::{MockStorage, StorageErrorKind}; + use bytesize::ByteSize; + use quickwit_common::uri::Uri; + use quickwit_config::StorageCacheConfig; use tokio::io::AsyncWriteExt; use super::*; + use crate::{FeuerIoQueues, MockStorage, StorageErrorKind, open_storage_cache}; #[tokio::test] async fn emits_in_order_across_gaps_and_overlaps() { @@ -147,12 +217,10 @@ mod tests { assert_eq!(range, expected_downloads.next().unwrap()); Ok(Box::new(&content[range])) }); + let reader = SplitStorageReader::new(Arc::new(storage)); let ranges = [3..5, 8..11, 8..11, 1..3]; - let mut stream = download_ranges( - &storage, - Path::new("file"), - Box::new(ranges.clone().into_iter()), - ); + let mut stream = + reader.stream_ranges(Path::new("file"), Box::new(ranges.clone().into_iter())); for range in ranges { assert_eq!( stream.try_next().await.unwrap().unwrap().as_slice(), @@ -180,10 +248,11 @@ mod tests { assert_eq!(range, expected_downloads.next().unwrap()); Ok(Box::new(tokio::io::repeat(7u8).take(range.len() as u64))) }); + let reader = SplitStorageReader::new(Arc::new(storage)); let ranges = (0..NUM_CONTIGUOUS_RANGES) .map(|i| i * RANGE_LEN..(i + 1) * RANGE_LEN) .chain([at_gap_limit, past_gap_limit]); - let mut stream = download_ranges(&storage, Path::new("file"), Box::new(ranges)); + let mut stream = reader.stream_ranges(Path::new("file"), Box::new(ranges)); for _ in 0..NUM_CONTIGUOUS_RANGES + 2 { let bytes = stream.try_next().await.unwrap().unwrap(); assert_eq!((bytes.len(), bytes[0]), (RANGE_LEN, 7)); @@ -203,16 +272,17 @@ mod tests { .inspect(move |_| { pulled_counter.fetch_add(1, Ordering::Relaxed); }); - let (reader, mut writer) = tokio::io::duplex(range_len); + let (reader_pipe, mut writer) = tokio::io::duplex(range_len); let mut storage = MockStorage::default(); storage .expect_get_slice_stream() .once() .return_once(move |_, range| { assert_eq!(range, 0..num_first_download_ranges * range_len); - Ok(Box::new(reader)) + Ok(Box::new(reader_pipe)) }); - let mut stream = download_ranges(&storage, Path::new("file"), Box::new(ranges)); + let reader = SplitStorageReader::new(Arc::new(storage)); + let mut stream = reader.stream_ranges(Path::new("file"), Box::new(ranges)); assert_eq!(num_pulled_ranges.load(Ordering::Relaxed), 0); // Send only the first range. Waiting for the whole download would stall. let first_range_bytes = vec![42u8; range_len]; @@ -245,16 +315,16 @@ mod tests { 1 => Ok(Box::new(&b"0123"[..])), _ => Ok(Box::new(&b"012345678"[..])), }); + let reader = SplitStorageReader::new(Arc::new(storage)); let mut missing_stream = - download_ranges(&storage, Path::new("file"), Box::new(std::iter::once(0..1))); + reader.stream_ranges(Path::new("file"), Box::new(std::iter::once(0..1))); assert_eq!( missing_stream.try_next().await.unwrap_err().kind(), io::ErrorKind::NotFound ); // Truncated in gap (start=1, 4 bytes) and in range (start=2, 9 bytes). for start in [1, 2] { - let mut stream = download_ranges( - &storage, + let mut stream = reader.stream_ranges( Path::new("file"), Box::new([start..start + 2, start + 8..start + 10].into_iter()), ); @@ -266,4 +336,74 @@ mod tests { assert!(stream.try_next().await.unwrap().is_none()); } } + + #[tokio::test] + async fn checks_storage_cache_only_below_ten_ranges() { + let content = b"0123456789abcdefghijklmnopqrstuvwxyz"; + let storage_cache = open_storage_cache( + &StorageCacheConfig { + directory: None, + disk_capacity: ByteSize::b(0), + memory_capacity: ByteSize::mib(1), + }, + &FeuerIoQueues::default(), + ) + .unwrap(); + let mut storage = MockStorage::default(); + storage + .expect_uri() + .return_const(Uri::for_test("ram:///stream-cache-test")); + // Seed 2..4 in storage_cache via get_slice. + storage + .expect_get_slice_into() + .once() + .returning(move |_, range, buf| { + buf.copy_from_slice(&content[range]); + Ok(()) + }); + // First stream (< 10 ranges): 2..4 hits storage_cache; misses [0..2, 6..8] coalesce to + // 0..8. Second stream (>= 10 ranges): skips storage_cache; all 10 ranges coalesce to 0..20. + let mut expected_streams = [0..8, 0..20].into_iter(); + storage + .expect_get_slice_stream() + .times(2) + .returning(move |_, range| { + assert_eq!(range, expected_streams.next().unwrap()); + Ok(Box::new(&content[range])) + }); + let reader = SplitStorageReader::new(Arc::new(storage)).with_storage_cache(storage_cache); + let path = Path::new("split.split"); + + // Warm 2..4 into storage_cache. + assert_eq!( + reader.get_slice(path, 2..4).await.unwrap().as_slice(), + b"23" + ); + + // Fewer than 10 ranges: serves 2..4 from cache and coalesces misses [0..2, 6..8]. + let small_ranges = [0..2, 2..4, 6..8]; + let small_results: Vec<_> = reader + .stream_ranges(path, Box::new(small_ranges.into_iter())) + .try_collect() + .await + .unwrap(); + assert_eq!( + small_results + .iter() + .map(|b| b.as_slice()) + .collect::>(), + vec![&b"01"[..], &b"23"[..], &b"67"[..]] + ); + + // 10 ranges: bypasses storage_cache even though 2..4 is cached. + let ten_ranges: Vec<_> = (0..10).map(|i| i * 2..(i + 1) * 2).collect(); + let large_results: Vec<_> = reader + .stream_ranges(path, Box::new(ten_ranges.clone().into_iter())) + .try_collect() + .await + .unwrap(); + for (range, bytes) in ten_ranges.into_iter().zip(large_results) { + assert_eq!(bytes.as_slice(), &content[range]); + } + } } diff --git a/quickwit/quickwit-storage/src/storage.rs b/quickwit/quickwit-storage/src/storage.rs index 0b94afce147..b8f6b5f63ea 100644 --- a/quickwit/quickwit-storage/src/storage.rs +++ b/quickwit/quickwit-storage/src/storage.rs @@ -121,8 +121,7 @@ pub trait Storage: fmt::Debug + Send + Sync + 'static { /// Empty ranges succeed without accessing storage. /// /// Backends can use [`default_get_slice_into`] to stream directly into the buffer without - /// collecting a separate payload. Wrappers must preserve their caching, retry, and accounting - /// behavior by forwarding this method or copying from their cached reads. + /// collecting a separate payload. async fn get_slice_into( &self, path: &Path, @@ -130,11 +129,7 @@ pub trait Storage: fmt::Debug + Send + Sync + 'static { buffer: &mut [u8], ) -> StorageResult<()>; - /// Opens a reader for a file byte range. Dropping it releases this reader, and shared - /// storage reads stop when their last reader is dropped. - /// - /// Cache wrappers serve hits from cache and forward misses without inserting into the cache. - /// Buffered reads (`get_slice`, `get_slice_into`, `get_all`) retain their caching behavior. + /// Opens a reader for a file byte range. Dropping it releases this reader. /// /// Might panic, return an error or an empty stream if the range is empty. async fn get_slice_stream( diff --git a/quickwit/quickwit-storage/src/storage_cache/access_trace.rs b/quickwit/quickwit-storage/src/storage_cache/access_trace.rs index 9e122def60a..e54c0a1df52 100644 --- a/quickwit/quickwit-storage/src/storage_cache/access_trace.rs +++ b/quickwit/quickwit-storage/src/storage_cache/access_trace.rs @@ -164,8 +164,8 @@ mod tests { #[tokio::test] async fn test_trace_callback_exports_miss_hit_and_error_on_drop() { + use crate::SplitStorageReader; use crate::storage_cache::open_storage_cache; - use crate::wrap_storage_with_storage_cache; let (sender, receiver) = tokio::sync::oneshot::channel(); let mut storage = MockStorage::new(); @@ -200,10 +200,10 @@ mod tests { .returning(|_, _, _| { Err(StorageErrorKind::Io.with_error(anyhow::anyhow!("source failed"))) }); - let storage = wrap_storage_with_storage_cache(cache, Arc::new(lower)); + let reader = SplitStorageReader::new(Arc::new(lower)).with_storage_cache(cache); for _ in 0..2 { assert_eq!( - storage + reader .get_slice(Path::new("object"), 0..4) .await .unwrap() @@ -211,8 +211,8 @@ mod tests { b"data" ); } - assert!(storage.get_slice(Path::new("error"), 0..1).await.is_err()); - drop(storage); + assert!(reader.get_slice(Path::new("error"), 0..1).await.is_err()); + drop(reader); let bytes = tokio::time::timeout(Duration::from_secs(5), receiver) .await .unwrap() diff --git a/quickwit/quickwit-storage/src/storage_cache/disk_tests.rs b/quickwit/quickwit-storage/src/storage_cache/disk_tests.rs index 1ce45c34710..0e36e4d8d59 100644 --- a/quickwit/quickwit-storage/src/storage_cache/disk_tests.rs +++ b/quickwit/quickwit-storage/src/storage_cache/disk_tests.rs @@ -16,7 +16,7 @@ use std::path::Path; use std::sync::Arc; use super::{config_for_test, open_storage_cache}; -use crate::{RamStorageBuilder, wrap_storage_with_storage_cache}; +use crate::{RamStorageBuilder, SplitStorageReader}; #[tokio::test] async fn test_disk_enabled_cache_configuration_and_reads() { @@ -41,10 +41,10 @@ async fn test_disk_enabled_cache_configuration_and_reads() { .put("a.split", b"abcde") .build(), ); - let storage = wrap_storage_with_storage_cache(cache, lower); + let reader = SplitStorageReader::new(lower).with_storage_cache(cache); for _ in 0..2 { assert_eq!( - storage + reader .get_slice(Path::new("a.split"), 1..4) .await .unwrap() diff --git a/quickwit/quickwit-storage/src/storage_cache/mod.rs b/quickwit/quickwit-storage/src/storage_cache/mod.rs index bb1cee30d78..dcc00fa0159 100644 --- a/quickwit/quickwit-storage/src/storage_cache/mod.rs +++ b/quickwit/quickwit-storage/src/storage_cache/mod.rs @@ -16,14 +16,32 @@ mod access_trace; #[cfg(all(test, target_os = "linux"))] mod disk_tests; pub(crate) mod metrics; -mod storage; #[cfg(test)] mod tests; +use std::ops::Range; +use std::path::Path; +use std::sync::{Arc, LazyLock, Mutex}; + +use feuer::GetOrFetchError; +use futures::future::BoxFuture; +use quickwit_common::get_from_env; +use quickwit_common::uri::Uri; use quickwit_config::StorageCacheConfig; -pub use storage::wrap_storage_with_storage_cache; +use tokio::sync::Semaphore; + +use crate::stable_deref_bytes::into_owned_bytes; +use crate::{FeuerIoQueues, OwnedBytes, StorageErrorKind, StorageResolver, StorageResult}; -use crate::{FeuerIoQueues, StorageResolver}; +static FALLTHROUGH_MIN_BYTES: LazyLock = + LazyLock::new(|| get_from_env("QW_STORAGE_CACHE_FALLTHROUGH_MIN_BYTES", 20_000_000, false)); +static FALLTHROUGH_DOWNLOADS: LazyLock = LazyLock::new(|| { + Semaphore::new(get_from_env( + "QW_STORAGE_CACHE_FALLTHROUGH_MAX_IN_FLIGHT", + 32, + false, + )) +}); /// Optionally export native traces from an opened cache to `QW_FEUER_ACCESS_TRACE_URI`. pub async fn attach_storage_cache_access_trace( @@ -50,7 +68,7 @@ pub fn open_storage_cache( config: &StorageCacheConfig, queues: &FeuerIoQueues, ) -> anyhow::Result { - let scorer = std::sync::Arc::new(feuer::FetchCostScorer { + let scorer = Arc::new(feuer::FetchCostScorer { cost_per_request: 256_000.0, ..Default::default() }); @@ -58,22 +76,215 @@ pub fn open_storage_cache( queues.open(config, "storage_cache", "storage", scorer, 1, 1024 * 1024) } -#[cfg(test)] -#[test] -fn test_memory_only_storage_cache_needs_no_directory_or_runtime() { - let config = StorageCacheConfig { - directory: None, - disk_capacity: bytesize::ByteSize::b(0), - memory_capacity: bytesize::ByteSize::mb(1), - }; - open_storage_cache(&config, &FeuerIoQueues::default()).unwrap(); +/// Fetches an exact slice through `feuer`, filling Feuer's aligned buffer via `fetch_into` on miss. +/// +/// Cache hits require matching `(storage_uri / path)` and `byte_range`. Concurrent misses on the +/// same key are deduplicated by `feuer`. +pub(crate) async fn get_slice_from_storage_cache( + cache: &feuer::Cache, + storage_uri: &Uri, + path: &Path, + byte_range: Range, + fetch_into: F, +) -> StorageResult +where + F: for<'a> FnOnce(&'a mut [u8]) -> BoxFuture<'a, StorageResult<()>> + Send + 'static, +{ + if byte_range.is_empty() { + return Ok(OwnedBytes::empty()); + } + let object_uri = storage_uri + .join(path) + .map_err(|error| StorageErrorKind::Internal.with_error(error))? + .into_string(); + let cache_key = split_slice_key(&object_uri, &byte_range); + let cache_clone = cache.clone(); + let download_size = byte_range.len(); + let permit_slot = Arc::new(Mutex::new(None)); + let decision_slot = permit_slot.clone(); + cache + .get_or_fetch_with_disk_fallthrough( + &cache_key, + move || { + if download_size < *FALLTHROUGH_MIN_BYTES { + return false; + } + let Ok(permit) = FALLTHROUGH_DOWNLOADS.try_acquire() else { + return false; + }; + *decision_slot.lock().unwrap() = Some(permit); + true + }, + move || async move { + // Ordinary misses have no fallthrough permit. + let _permit = permit_slot.lock().unwrap().take(); + let mut buffer = cache_clone.allocate_buffer(download_size)?; + fetch_into(buffer.as_mut()).await?; + Ok(buffer) + }, + ) + .await + .map(into_owned_bytes) + .map_err(|GetOrFetchError::Callback(error)| error) +} + +/// Checks `feuer` for an exact cached slice without inserting on miss. +pub(crate) async fn try_get_slice_from_storage_cache( + cache: &feuer::Cache, + storage_uri: &Uri, + path: &Path, + byte_range: &Range, +) -> StorageResult> { + if byte_range.is_empty() { + return Ok(Some(OwnedBytes::empty())); + } + let object_uri = storage_uri + .join(path) + .map_err(|error| StorageErrorKind::Internal.with_error(error))? + .into_string(); + let cache_key = split_slice_key(&object_uri, byte_range); + Ok(cache.get(&cache_key).await.map(into_owned_bytes)) +} + +fn split_slice_key<'a>( + object_uri: &'a str, + byte_range: &Range, +) -> (&'static str, &'a str, usize, usize) { + ( + "split-slice-v1", + object_uri, + byte_range.start, + byte_range.end, + ) } #[cfg(all(test, target_os = "linux"))] -pub(crate) fn config_for_test(path: impl AsRef) -> StorageCacheConfig { +pub(crate) fn config_for_test(path: impl AsRef) -> StorageCacheConfig { StorageCacheConfig { directory: Some(path.as_ref().to_path_buf()), disk_capacity: bytesize::ByteSize::mib(512), memory_capacity: bytesize::ByteSize::mib(8), } } + +#[cfg(test)] +mod slice_tests { + use std::io; + + use tokio::io::AsyncReadExt; + + use super::*; + use crate::SplitStorageReader; + + #[test] + fn test_memory_only_storage_cache_needs_no_directory_or_runtime() { + let config = StorageCacheConfig { + directory: None, + disk_capacity: bytesize::ByteSize::b(0), + memory_capacity: bytesize::ByteSize::mb(1), + }; + open_storage_cache(&config, &FeuerIoQueues::default()).unwrap(); + } + + #[tokio::test] + async fn test_get_slice_stream_serves_cache_hit_and_does_not_insert_on_miss() { + let mut backend = crate::MockStorage::new(); + backend + .expect_uri() + .return_const(Uri::for_test("ram:///bucket")); + backend + .expect_get_slice_into() + .times(1) + .returning(|_, range, buffer| { + buffer.copy_from_slice(&b"hello world"[range]); + Ok(()) + }); + backend + .expect_get_slice_stream() + .times(2) + .returning(|_, range| Ok(Box::new(io::Cursor::new(b"hello world"[range].to_vec())))); + + let cache = feuer::Cache::builder() + .memory_capacity(1024) + .open() + .unwrap(); + let reader = SplitStorageReader::new(Arc::new(backend)).with_storage_cache(cache); + let path = Path::new("split"); + + // Populate `0..5` via buffered read; streaming that exact range must hit cache. + assert_eq!( + reader.get_slice(path, 0..5).await.unwrap().as_slice(), + b"hello" + ); + let mut buf = Vec::new(); + reader + .get_slice_stream(path, 0..5) + .await + .unwrap() + .read_to_end(&mut buf) + .await + .unwrap(); + assert_eq!(buf, b"hello"); + + // Streaming an uncached range must miss twice (never inserted into Feuer). + for _ in 0..2 { + buf.clear(); + reader + .get_slice_stream(path, 6..11) + .await + .unwrap() + .read_to_end(&mut buf) + .await + .unwrap(); + assert_eq!(buf, b"world"); + } + } + + #[tokio::test] + async fn test_cache_miss_does_not_wait_for_fallthrough_capacity() { + let mut permits = Vec::new(); + while let Ok(permit) = FALLTHROUGH_DOWNLOADS.try_acquire() { + permits.push(permit); + } + let payload = vec![42; 20_000_000]; + let cache = feuer::Cache::builder() + .memory_capacity(1024) + .open() + .unwrap(); + let reader = SplitStorageReader::new(Arc::new( + crate::RamStorageBuilder::default() + .put("split", &payload) + .build(), + )) + .with_storage_cache(cache); + let bytes = tokio::time::timeout( + std::time::Duration::from_secs(5), + reader.get_slice(Path::new("split"), 0..payload.len()), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(bytes.as_slice(), payload); + } + + #[test] + fn test_split_slice_keys_include_uri_and_both_bounds() { + let cache = feuer::Cache::builder() + .memory_capacity(1024) + .open() + .unwrap(); + let hash_key = + |uri: &str, range: &Range| cache.hash_key(&split_slice_key(uri, range)); + let key = hash_key("s3://bucket/a.split", &(1..4)); + assert_eq!(key, hash_key("s3://bucket/a.split", &(1..4))); + for (uri, range) in [ + ("s3://other/a.split", 1..4), + ("s3://bucket/a.split", 0..4), + ("s3://bucket/a.split", 1..5), + ("s3://bucket/a.split:1:4", 1..4), + ] { + assert_ne!(key, hash_key(uri, &range)); + } + assert_ne!(key, cache.hash_key("s3://bucket/a.split")); + } +} diff --git a/quickwit/quickwit-storage/src/storage_cache/storage.rs b/quickwit/quickwit-storage/src/storage_cache/storage.rs deleted file mode 100644 index ce301ee5fc8..00000000000 --- a/quickwit/quickwit-storage/src/storage_cache/storage.rs +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2021-Present Datadog, Inc. -// -// Licensed 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 std::io; -use std::ops::Range; -use std::path::Path; -use std::sync::{Arc, LazyLock, Mutex}; - -use async_trait::async_trait; -use feuer::GetOrFetchError; -use quickwit_common::get_from_env; -use quickwit_common::uri::Uri; -use tokio::io::AsyncRead; -use tokio::sync::Semaphore; -use tracing::error; - -use crate::stable_deref_bytes::into_owned_bytes; -use crate::storage::SendableAsync; -use crate::{ - BulkDeleteError, OwnedBytes, PutPayload, Storage, StorageError, StorageErrorKind, StorageResult, -}; - -static FALLTHROUGH_MIN_BYTES: LazyLock = - LazyLock::new(|| get_from_env("QW_STORAGE_CACHE_FALLTHROUGH_MIN_BYTES", 20_000_000, false)); -static FALLTHROUGH_DOWNLOADS: LazyLock = LazyLock::new(|| { - Semaphore::new(get_from_env( - "QW_STORAGE_CACHE_FALLTHROUGH_MAX_IN_FLIGHT", - 32, - false, - )) -}); - -/// Read-only storage decorator caching exact slices of immutable split objects. -#[derive(Debug)] -struct FeuerStorage { - inner: Arc, - cache: feuer::Cache, -} - -/// Wrap `storage` with the supplied cache. -/// Cache hits require matching object URIs and byte ranges. -pub fn wrap_storage_with_storage_cache( - cache: feuer::Cache, - storage: Arc, -) -> Arc { - Arc::new(FeuerStorage { - inner: storage, - cache, - }) -} - -fn unsupported_operation(paths: &[&Path]) -> StorageError { - let msg = "Unsupported operation. FeuerStorage only supports async reads"; - error!(paths=?paths, msg); - io::Error::other(format!("{msg}: {paths:?}")).into() -} - -#[async_trait] -impl Storage for FeuerStorage { - async fn check_connectivity(&self) -> anyhow::Result<()> { - self.inner.check_connectivity().await - } - - async fn put(&self, path: &Path, _payload: Box) -> StorageResult<()> { - Err(unsupported_operation(&[path])) - } - - async fn copy_to(&self, path: &Path, output: &mut dyn SendableAsync) -> StorageResult<()> { - self.inner.copy_to(path, output).await - } - - async fn get_slice(&self, path: &Path, byte_range: Range) -> StorageResult { - if byte_range.is_empty() { - return Ok(OwnedBytes::empty()); - } - let object_uri = self - .inner - .uri() - .join(path) - .map_err(|error| StorageErrorKind::Internal.with_error(error))? - .into_string(); - let cache_key = split_slice_key(&object_uri, &byte_range); - let cache = self.cache.clone(); - let storage = self.inner.clone(); - let path = path.to_owned(); - let download_size = byte_range.len(); - let permit_slot = Arc::new(Mutex::new(None)); - let decision_slot = permit_slot.clone(); - self.cache - .get_or_fetch_with_disk_fallthrough( - &cache_key, - move || { - if download_size < *FALLTHROUGH_MIN_BYTES { - return false; - } - let Ok(permit) = FALLTHROUGH_DOWNLOADS.try_acquire() else { - return false; - }; - *decision_slot.lock().unwrap() = Some(permit); - true - }, - move || async move { - // Ordinary misses have no fallthrough permit. - let _permit = permit_slot.lock().unwrap().take(); - let mut buffer = cache.allocate_buffer(download_size)?; - storage - .get_slice_into(&path, byte_range, buffer.as_mut()) - .await?; - Ok(buffer) - }, - ) - .await - .map(into_owned_bytes) - .map_err(|GetOrFetchError::Callback(error)| error) - } - - async fn get_slice_into( - &self, - path: &Path, - range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - // Feuer owns the cached allocation, so copy from it into the caller's buffer. - let bytes = self.get_slice(path, range).await?; - buffer.copy_from_slice(&bytes); - Ok(()) - } - - async fn get_slice_stream( - &self, - path: &Path, - range: Range, - ) -> StorageResult> { - if range.is_empty() { - return Ok(Box::new(tokio::io::empty())); - } - let object_uri = self - .inner - .uri() - .join(path) - .map_err(|error| StorageErrorKind::Internal.with_error(error))? - .into_string(); - let cache_key = split_slice_key(&object_uri, &range); - if let Some(bytes) = self.cache.get(&cache_key).await { - return Ok(Box::new(io::Cursor::new(bytes))); - } - self.inner.get_slice_stream(path, range).await - } - - async fn get_all(&self, path: &Path) -> StorageResult { - self.inner.get_all(path).await - } - - async fn delete(&self, path: &Path) -> StorageResult<()> { - Err(unsupported_operation(&[path])) - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - Err(BulkDeleteError { - error: Some(unsupported_operation(paths)), - ..Default::default() - }) - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - self.inner.file_num_bytes(path).await - } - - fn uri(&self) -> &Uri { - self.inner.uri() - } -} - -fn split_slice_key<'a>( - object_uri: &'a str, - byte_range: &Range, -) -> (&'static str, &'a str, usize, usize) { - ( - "split-slice-v1", - object_uri, - byte_range.start, - byte_range.end, - ) -} - -#[cfg(test)] -mod tests { - use tokio::io::AsyncReadExt; - - use super::*; - - #[tokio::test] - async fn test_get_slice_stream_serves_cache_hit_and_does_not_insert_on_miss() { - let mut backend = crate::MockStorage::new(); - backend - .expect_uri() - .return_const(Uri::for_test("ram:///bucket")); - backend - .expect_get_slice_into() - .times(1) - .returning(|_, range, buffer| { - buffer.copy_from_slice(&b"hello world"[range]); - Ok(()) - }); - backend - .expect_get_slice_stream() - .times(2) - .returning(|_, range| Ok(Box::new(io::Cursor::new(b"hello world"[range].to_vec())))); - - let cache = feuer::Cache::builder() - .memory_capacity(1024) - .open() - .unwrap(); - let storage = wrap_storage_with_storage_cache(cache, Arc::new(backend)); - let path = Path::new("split"); - - // Populate `0..5` via buffered read; streaming that exact range must hit cache. - assert_eq!( - storage.get_slice(path, 0..5).await.unwrap().as_slice(), - b"hello" - ); - let mut buf = Vec::new(); - storage - .get_slice_stream(path, 0..5) - .await - .unwrap() - .read_to_end(&mut buf) - .await - .unwrap(); - assert_eq!(buf, b"hello"); - - // Streaming an uncached range must miss twice (never inserted into Feuer). - for _ in 0..2 { - buf.clear(); - storage - .get_slice_stream(path, 6..11) - .await - .unwrap() - .read_to_end(&mut buf) - .await - .unwrap(); - assert_eq!(buf, b"world"); - } - } - - #[tokio::test] - async fn test_cache_miss_does_not_wait_for_fallthrough_capacity() { - let mut permits = Vec::new(); - while let Ok(permit) = FALLTHROUGH_DOWNLOADS.try_acquire() { - permits.push(permit); - } - let payload = vec![42; 20_000_000]; - let storage = wrap_storage_with_storage_cache( - feuer::Cache::builder() - .memory_capacity(1024) - .open() - .unwrap(), - Arc::new( - crate::RamStorageBuilder::default() - .put("split", &payload) - .build(), - ), - ); - let bytes = tokio::time::timeout( - std::time::Duration::from_secs(5), - storage.get_slice(Path::new("split"), 0..payload.len()), - ) - .await - .unwrap() - .unwrap(); - assert_eq!(bytes.as_slice(), payload); - } - - #[test] - fn test_split_slice_keys_include_uri_and_both_bounds() { - let cache = feuer::Cache::builder() - .memory_capacity(1024) - .open() - .unwrap(); - let hash_key = - |uri: &str, range: &Range| cache.hash_key(&split_slice_key(uri, range)); - let key = hash_key("s3://bucket/a.split", &(1..4)); - assert_eq!(key, hash_key("s3://bucket/a.split", &(1..4))); - for (uri, range) in [ - ("s3://other/a.split", 1..4), - ("s3://bucket/a.split", 0..4), - ("s3://bucket/a.split", 1..5), - ("s3://bucket/a.split:1:4", 1..4), - ] { - assert_ne!(key, hash_key(uri, &range)); - } - assert_ne!(key, cache.hash_key("s3://bucket/a.split")); - } -} diff --git a/quickwit/quickwit-storage/src/storage_cache/tests.rs b/quickwit/quickwit-storage/src/storage_cache/tests.rs index 4fc9d06d622..fc7092f7599 100644 --- a/quickwit/quickwit-storage/src/storage_cache/tests.rs +++ b/quickwit/quickwit-storage/src/storage_cache/tests.rs @@ -26,8 +26,8 @@ use tokio::sync::watch; use super::open_storage_cache; use crate::storage::SendableAsync; use crate::{ - BulkDeleteError, MockStorage, OwnedBytes, PutPayload, RamStorageBuilder, Storage, - StorageErrorKind, StorageResult, wrap_storage_with_storage_cache, + BulkDeleteError, MockStorage, OwnedBytes, PutPayload, RamStorageBuilder, SplitStorageReader, + Storage, StorageErrorKind, StorageResult, }; async fn memory_cache() -> feuer::Cache { @@ -116,8 +116,8 @@ async fn test_download_errors_are_forwarded_and_retried() { buffer.copy_from_slice(b"bcd"); Ok(()) }); - let storage = wrap_storage_with_storage_cache(memory_cache().await, Arc::new(lower)); - let error = storage + let reader = SplitStorageReader::new(Arc::new(lower)).with_storage_cache(memory_cache().await); + let error = reader .get_slice(Path::new(SPLIT_PATH), 1..4) .await .unwrap_err(); @@ -125,7 +125,7 @@ async fn test_download_errors_are_forwarded_and_retried() { assert!(error.to_string().contains("missing split")); for _ in 0..2 { assert_eq!( - storage + reader .get_slice(Path::new(SPLIT_PATH), 1..4) .await .unwrap() @@ -136,48 +136,14 @@ async fn test_download_errors_are_forwarded_and_retried() { } #[tokio::test] -async fn test_writes_are_unsupported() { +async fn test_metadata_and_stream_reads_are_forwarded() { let fixture = Fixture::new(true).await; let path = Path::new(SPLIT_PATH); - let put_error = fixture - .storage - .put(path, Box::new(b"x".to_vec())) - .await - .unwrap_err(); - assert_eq!(put_error.kind(), StorageErrorKind::Io); - assert!( - put_error - .to_string() - .contains("Unsupported operation. FeuerStorage only supports async reads") - ); - assert_eq!( - fixture.storage.delete(path).await.unwrap_err().kind(), - StorageErrorKind::Io - ); - let bulk_error = fixture.storage.bulk_delete(&[path]).await.unwrap_err(); - assert_eq!( - bulk_error.error.as_ref().unwrap().kind(), - StorageErrorKind::Io - ); -} - -#[tokio::test] -async fn test_other_reads_are_forwarded() { - let fixture = Fixture::new(true).await; - let path = Path::new(SPLIT_PATH); - fixture.storage.check_connectivity().await.unwrap(); assert_eq!(fixture.storage.uri(), fixture.lower.uri()); assert_eq!( fixture.storage.file_num_bytes(path).await.unwrap(), SPLIT_BYTES.len() as u64 ); - assert_eq!( - fixture.storage.get_all(path).await.unwrap().as_slice(), - SPLIT_BYTES - ); - let mut copied = Vec::new(); - fixture.storage.copy_to(path, &mut copied).await.unwrap(); - assert_eq!(copied, SPLIT_BYTES); let mut stream = fixture.storage.get_slice_stream(path, 1..4).await.unwrap(); let mut streamed = Vec::new(); stream.read_to_end(&mut streamed).await.unwrap(); @@ -208,10 +174,10 @@ async fn test_object_keys_do_not_alias() { Ok(()) }); } - let storage = wrap_storage_with_storage_cache(cache.clone(), Arc::new(lower)); + let reader = SplitStorageReader::new(Arc::new(lower)).with_storage_cache(cache.clone()); for _ in 0..2 { assert_eq!( - storage + reader .get_slice(Path::new("a.split"), 0..4) .await .unwrap() @@ -219,7 +185,7 @@ async fn test_object_keys_do_not_alias() { expected ); assert_eq!( - storage + reader .get_slice(Path::new("b.split"), 0..4) .await .unwrap() @@ -304,7 +270,7 @@ impl Storage for LowerProbe { } struct Fixture { - storage: Arc, + storage: SplitStorageReader, lower: Arc, gate_tx: watch::Sender, } @@ -323,7 +289,8 @@ impl Fixture { download_address: AtomicUsize::new(0), gate: gate_rx, }); - let storage = wrap_storage_with_storage_cache(memory_cache().await, lower.clone()); + let storage = + SplitStorageReader::new(lower.clone()).with_storage_cache(memory_cache().await); Self { storage, lower, diff --git a/quickwit/quickwit-storage/src/timeout_and_retry_storage.rs b/quickwit/quickwit-storage/src/timeout_and_retry.rs similarity index 53% rename from quickwit/quickwit-storage/src/timeout_and_retry_storage.rs rename to quickwit/quickwit-storage/src/timeout_and_retry.rs index d20b50cdba3..78785ab2de2 100644 --- a/quickwit/quickwit-storage/src/timeout_and_retry_storage.rs +++ b/quickwit/quickwit-storage/src/timeout_and_retry.rs @@ -12,208 +12,91 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::ops::Range; use std::path::Path; -use std::sync::Arc; -use async_trait::async_trait; use futures::future::BoxFuture; -use quickwit_common::uri::Uri; use quickwit_common::{rate_limited_info, rate_limited_warn}; use quickwit_config::StorageTimeoutPolicy; -use tantivy::directory::OwnedBytes; -use tokio::io::AsyncRead; -use crate::storage::SendableAsync; -use crate::{ - BulkDeleteError, ListObjectsStream, PutPayload, Storage, StorageErrorKind, StorageResult, -}; +use crate::{Storage, StorageErrorKind, StorageResult}; -/// Storage proxy that implements a retry operation if the underlying storage -/// takes too long. -/// -/// This is useful in order to ensure a low latency on S3. -/// Retrying agressively is recommended for S3. +/// Retries an underlying storage read if an attempt takes longer than allowed by +/// `storage_timeout_policy`. /// +/// Retrying aggressively is recommended for latency-sensitive object storage reads: /// -#[derive(Clone, Debug)] -pub struct TimeoutAndRetryStorage { - underlying: Arc, - storage_timeout_policy: StorageTimeoutPolicy, -} - -impl TimeoutAndRetryStorage { - /// Creates a new `TimeoutAndRetryStorage`. - /// - /// See [StorageTimeoutPolicy] for more information. - pub fn new(storage: Arc, storage_timeout_policy: StorageTimeoutPolicy) -> Self { - TimeoutAndRetryStorage { - underlying: storage, - storage_timeout_policy, - } - } - - async fn retry_with_timeout( - &self, - path: &Path, - num_bytes: usize, - timeout_num_bytes: usize, - state: &mut S, - mut op: F, - ) -> StorageResult - where - S: Send + ?Sized, - F: for<'a> FnMut(&'a dyn Storage, &'a Path, &'a mut S) -> BoxFuture<'a, StorageResult>, +pub(crate) async fn retry_with_timeout( + storage: &dyn Storage, + storage_timeout_policy: &StorageTimeoutPolicy, + path: &Path, + num_bytes: usize, + timeout_num_bytes: usize, + state: &mut S, + mut op: F, +) -> StorageResult +where + S: Send + ?Sized, + F: for<'a> FnMut(&'a dyn Storage, &'a Path, &'a mut S) -> BoxFuture<'a, StorageResult>, +{ + for (attempt_id, timeout_duration) in storage_timeout_policy + .compute_timeout(timeout_num_bytes) + .enumerate() { - for (attempt_id, timeout_duration) in self - .storage_timeout_policy - .compute_timeout(timeout_num_bytes) - .enumerate() - { - // TODO test avoid aborting timed out requests. #5468 - match tokio::time::timeout(timeout_duration, op(self.underlying.as_ref(), path, state)) - .await - { - Ok(Ok(output)) => { - match attempt_id { - 0 => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_0_TIMEOUT.inc(), - 1 => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_1_TIMEOUT.inc(), - _ => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_2_PLUS_TIMEOUT.inc(), - } - return Ok(output); - } - Ok(Err(error)) => return Err(error), - Err(_elapsed) => { - rate_limited_info!(limit_per_min=60, num_bytes=num_bytes, path=%path.display(), timeout_secs=timeout_duration.as_secs_f32(), "get timeout elapsed"); + // TODO test avoid aborting timed out requests. #5468 + match tokio::time::timeout(timeout_duration, op(storage, path, state)).await { + Ok(Ok(output)) => { + match attempt_id { + 0 => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_0_TIMEOUT.inc(), + 1 => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_1_TIMEOUT.inc(), + _ => crate::metrics::GET_SLICE_TIMEOUT_SUCCESS_AFTER_2_PLUS_TIMEOUT.inc(), } + return Ok(output); + } + Ok(Err(error)) => return Err(error), + Err(_elapsed) => { + rate_limited_info!( + limit_per_min = 60, + num_bytes = num_bytes, + path = %path.display(), + timeout_secs = timeout_duration.as_secs_f32(), + "get timeout elapsed" + ); } } - rate_limited_warn!(limit_per_min=60, num_bytes=num_bytes, path=%path.display(), "all get_slice attempts timeouted"); - crate::metrics::GET_SLICE_TIMEOUT_ALL_TIMEOUTS.inc(); - Err(StorageErrorKind::Timeout.with_error(anyhow::anyhow!("internal timeout on get_slice"))) - } -} - -#[async_trait] -impl Storage for TimeoutAndRetryStorage { - async fn check_connectivity(&self) -> anyhow::Result<()> { - self.underlying.check_connectivity().await - } - - async fn put(&self, path: &Path, payload: Box) -> StorageResult<()> { - self.underlying.put(path, payload).await - } - - fn copy_to<'life0, 'life1, 'life2, 'async_trait>( - &'life0 self, - path: &'life1 Path, - output: &'life2 mut dyn SendableAsync, - ) -> ::core::pin::Pin< - Box< - dyn ::core::future::Future> - + ::core::marker::Send - + 'async_trait, - >, - > - where - 'life0: 'async_trait, - 'life1: 'async_trait, - 'life2: 'async_trait, - Self: 'async_trait, - { - self.underlying.copy_to(path, output) - } - - async fn copy_to_file(&self, path: &Path, output_path: &Path) -> StorageResult { - self.underlying.copy_to_file(path, output_path).await - } - - /// Downloads a slice of a file from the storage, and returns an in memory buffer - async fn get_slice(&self, path: &Path, range: Range) -> StorageResult { - self.retry_with_timeout( - path, - range.len(), - range.len(), - &mut (), - |storage, path, _| storage.get_slice(path, range.clone()), - ) - .await - } - - async fn get_slice_into( - &self, - path: &Path, - range: Range, - buffer: &mut [u8], - ) -> StorageResult<()> { - // The timeout covers the whole body read. Each retry overwrites the same buffer, - // and cancellation drops the previous stream. - self.retry_with_timeout( - path, - range.len(), - range.len(), - buffer, - |storage, path, buffer| storage.get_slice_into(path, range.clone(), buffer), - ) - .await - } - - async fn get_slice_stream( - &self, - path: &Path, - range: Range, - ) -> StorageResult> { - // Only opening the stream is timed and retried. Mid-body stalls rely on outer deadlines. - self.retry_with_timeout(path, range.len(), 0, &mut (), |storage, path, _| { - storage.get_slice_stream(path, range.clone()) - }) - .await - } - - async fn get_all(&self, path: &Path) -> StorageResult { - self.underlying.get_all(path).await - } - - async fn delete(&self, path: &Path) -> StorageResult<()> { - self.underlying.delete(path).await - } - - async fn bulk_delete<'a>(&self, paths: &[&'a Path]) -> Result<(), BulkDeleteError> { - self.underlying.bulk_delete(paths).await - } - - fn list(&self, prefix: &Path) -> ListObjectsStream { - self.underlying.list(prefix) - } - - async fn exists(&self, path: &Path) -> StorageResult { - self.underlying.exists(path).await - } - - async fn file_num_bytes(&self, path: &Path) -> StorageResult { - self.underlying.file_num_bytes(path).await - } - - fn uri(&self) -> &Uri { - self.underlying.uri() } + rate_limited_warn!( + limit_per_min = 60, + num_bytes = num_bytes, + path = %path.display(), + "all get_slice attempts timeouted" + ); + crate::metrics::GET_SLICE_TIMEOUT_ALL_TIMEOUTS.inc(); + Err(StorageErrorKind::Timeout.with_error(anyhow::anyhow!("internal timeout on get_slice"))) } #[cfg(test)] mod tests { - - use std::sync::Mutex; + use std::ops::Range; + use std::sync::{Arc, Mutex}; use std::time::Duration; + use async_trait::async_trait; use bytes::Bytes; use futures::StreamExt; - use tokio::io::AsyncReadExt; + use quickwit_common::uri::Uri; + use tantivy::directory::OwnedBytes; + use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::time::Instant; use super::*; + use crate::storage::SendableAsync; + use crate::{ + BulkDeleteError, ListObjectsStream, PutPayload, SplitStorageReader, StorageDebouncer, + }; #[derive(Debug)] struct StorageWithDelay { + uri: Uri, // Each attempt specifies its delay and the byte used to fill its response. attempts: Mutex>, delay_stream_open: bool, @@ -223,6 +106,7 @@ mod tests { pub fn new(mut attempts: Vec<(Duration, u8)>) -> StorageWithDelay { attempts.reverse(); StorageWithDelay { + uri: Uri::for_test("ram:///delay"), attempts: Mutex::new(attempts), delay_stream_open: false, } @@ -237,7 +121,7 @@ mod tests { #[async_trait] impl Storage for StorageWithDelay { fn uri(&self) -> &Uri { - todo!(); + &self.uri } async fn check_connectivity(&self) -> anyhow::Result<()> { @@ -246,23 +130,11 @@ mod tests { async fn put(&self, _path: &Path, _payload: Box) -> StorageResult<()> { todo!(); } - fn copy_to<'life0, 'life1, 'life2, 'async_trait>( - &'life0 self, - _path: &'life1 Path, - _output: &'life2 mut dyn SendableAsync, - ) -> ::core::pin::Pin< - Box< - dyn ::core::future::Future> - + ::core::marker::Send - + 'async_trait, - >, - > - where - 'life0: 'async_trait, - 'life1: 'async_trait, - 'life2: 'async_trait, - Self: 'async_trait, - { + async fn copy_to( + &self, + _path: &Path, + _output: &mut dyn SendableAsync, + ) -> StorageResult<()> { todo!(); } @@ -321,6 +193,9 @@ mod tests { async fn bulk_delete<'a>(&self, _paths: &[&'a Path]) -> Result<(), BulkDeleteError> { todo!(); } + fn list(&self, _prefix: &Path) -> ListObjectsStream { + todo!() + } async fn exists(&self, _path: &Path) -> StorageResult { todo!() } @@ -343,21 +218,22 @@ mod tests { (Duration::from_secs(5), b'a'), (Duration::from_secs(second_delay), retry_byte), ])); - let storage = TimeoutAndRetryStorage::new(lower.clone(), timeout_policy.clone()); - let mut buffer = [99; 90]; - let address = buffer.as_ptr(); + let cache = feuer::Cache::builder() + .memory_capacity(1024 * 1024) + .open() + .unwrap(); + let reader = SplitStorageReader::new(lower.clone()) + .with_storage_cache(cache) + .with_timeout_policy(timeout_policy.clone()); let start = Instant::now(); - let result = storage - .get_slice_into(Path::new("foo/bar"), 10..100, &mut buffer) - .await; + let result = reader.get_slice(Path::new("foo/bar"), 10..100).await; assert!( lower.attempts.lock().unwrap().is_empty(), "both attempts must run" ); - assert_eq!(buffer.as_ptr(), address); if succeeds { - result.unwrap(); - assert_eq!(buffer, [retry_byte; 90]); + let bytes = result.unwrap(); + assert_eq!(bytes.as_slice(), [retry_byte; 90]); // Tokio timers round deadlines to millisecond ticks. assert!(start.elapsed().as_millis().abs_diff(3_000) < 10); } else { @@ -383,10 +259,11 @@ mod tests { ]) .with_delayed_stream_open(), ); - let storage = TimeoutAndRetryStorage::new(lower.clone(), timeout_policy.clone()); + let reader = + SplitStorageReader::new(lower.clone()).with_timeout_policy(timeout_policy.clone()); let start = Instant::now(); // Large range ensures open timeout uses `timeout_millis` rather than full-body time. - let result = storage + let result = reader .get_slice_stream(Path::new("foo/bar"), 0..1_000_000) .await; assert!( @@ -394,9 +271,9 @@ mod tests { "both attempts must run" ); if succeeds { - let mut reader = result.unwrap(); + let mut stream = result.unwrap(); let mut prefix = [0; 4]; - reader.read_exact(&mut prefix).await.unwrap(); + stream.read_exact(&mut prefix).await.unwrap(); assert_eq!(prefix, [retry_byte; 4]); assert!(start.elapsed().as_millis().abs_diff(3_000) < 10); } else { @@ -410,38 +287,28 @@ mod tests { #[tokio::test] async fn test_storage_errors_are_returned_without_retry() { let mut backend = crate::MockStorage::new(); + backend + .expect_uri() + .return_const(Uri::for_test("ram:///bucket")); backend.expect_get_slice().times(1).returning(|_, _| { Err(StorageErrorKind::NotFound.with_error(anyhow::anyhow!("missing object"))) }); - backend - .expect_get_slice_into() - .times(1) - .returning(|_, _, _| { - Err(StorageErrorKind::NotFound.with_error(anyhow::anyhow!("missing object"))) - }); backend .expect_get_slice_stream() .times(1) .returning(|_, _| { Err(StorageErrorKind::NotFound.with_error(anyhow::anyhow!("missing object"))) }); - let storage = TimeoutAndRetryStorage::new( - Arc::new(backend), - StorageTimeoutPolicy { + let reader = + SplitStorageReader::new(Arc::new(backend)).with_timeout_policy(StorageTimeoutPolicy { min_throughtput_bytes_per_secs: 100_000, timeout_millis: 2_000, max_num_retries: 1, - }, - ); + }); let path = Path::new("missing"); - let error = storage.get_slice(path, 0..3).await.unwrap_err(); + let error = reader.get_slice(path, 0..3).await.unwrap_err(); assert_eq!(error.kind(), StorageErrorKind::NotFound); - let error = storage - .get_slice_into(path, 0..3, &mut [0; 3]) - .await - .unwrap_err(); - assert_eq!(error.kind(), StorageErrorKind::NotFound); - let error = storage + let error = reader .get_slice_stream(path, 0..3) .await .err() @@ -449,28 +316,24 @@ mod tests { assert_eq!(error.kind(), StorageErrorKind::NotFound); } - #[tokio::test] - async fn test_timeout_and_retry_storage() { - tokio::time::pause(); - + #[tokio::test(start_paused = true)] + async fn test_timeout_and_retry_get_slice() { let timeout_policy = StorageTimeoutPolicy { min_throughtput_bytes_per_secs: 100_000, timeout_millis: 2_000, max_num_retries: 1, }; - let path = Path::new("foo/bar"); - { let now = Instant::now(); let storage_with_delay = StorageWithDelay::new(vec![ (Duration::from_secs(5), 0), (Duration::from_secs(3), 0), ]); - let storage = - TimeoutAndRetryStorage::new(Arc::new(storage_with_delay), timeout_policy.clone()); + let reader = SplitStorageReader::new(Arc::new(storage_with_delay)) + .with_timeout_policy(timeout_policy.clone()); assert_eq!( - storage.get_slice(path, 10..100).await.unwrap_err().kind, + reader.get_slice(path, 10..100).await.unwrap_err().kind, StorageErrorKind::Timeout ); let elapsed = now.elapsed().as_millis(); @@ -482,10 +345,39 @@ mod tests { (Duration::from_secs(5), 0), (Duration::from_secs(1), 0), ]); - let storage = TimeoutAndRetryStorage::new(Arc::new(storage_with_delay), timeout_policy); - assert!(storage.get_slice(path, 10..100).await.is_ok(),); + let reader = SplitStorageReader::new(Arc::new(storage_with_delay)) + .with_timeout_policy(timeout_policy); + assert!(reader.get_slice(path, 10..100).await.is_ok()); let elapsed = now.elapsed().as_millis(); assert!(elapsed.abs_diff(2_000 + 1_000) < 100); } } + + #[tokio::test(start_paused = true)] + async fn test_timeout_below_debouncer_retries_fresh_backend_call_for_shared_waiters() { + let timeout_policy = StorageTimeoutPolicy { + min_throughtput_bytes_per_secs: 100_000, + timeout_millis: 2_000, + max_num_retries: 1, + }; + // First backend call stalls for 5s; second succeeds in 1s. + // Because timeout/retry runs inside the debounced future, both concurrent callers share + // the retried attempt and get `b'b'` after 3s (instead of re-joining the stalled 5s call). + let lower = Arc::new(StorageWithDelay::new(vec![ + (Duration::from_secs(5), b'a'), + (Duration::from_secs(1), b'b'), + ])); + let reader = SplitStorageReader::new(lower.clone()) + .with_debouncer(Arc::new(StorageDebouncer::default())) + .with_timeout_policy(timeout_policy); + let start = Instant::now(); + let (first, second) = tokio::join!( + reader.get_slice(Path::new("foo/bar"), 10..100), + reader.get_slice(Path::new("foo/bar"), 10..100), + ); + assert_eq!(first.unwrap().as_slice(), [b'b'; 90]); + assert_eq!(second.unwrap().as_slice(), [b'b'; 90]); + assert!(lower.attempts.lock().unwrap().is_empty()); + assert!(start.elapsed().as_millis().abs_diff(3_000) < 10); + } } diff --git a/quickwit/scripts/inspect_split.py b/quickwit/scripts/inspect_split.py index 0f6063ffdb2..3dfd73b7f4d 100755 --- a/quickwit/scripts/inspect_split.py +++ b/quickwit/scripts/inspect_split.py @@ -10,8 +10,8 @@ [ 4 bytes LE u32: hotcache length ] [ optional 16-byte split footer trailer: footer start (u64), version (u32), QWFT ] -See `BundleStorage::open_from_split_bytes` in -`quickwit/quickwit-storage/src/bundle_storage.rs` for the authoritative reader. +See `SplitBundle::open_from_split_bytes` in +`quickwit/quickwit-storage/src/split_bundle.rs` for the authoritative reader. """ import argparse