1use std::clone::Clone;
16use std::collections::VecDeque;
17use std::ops::Deref;
18use std::pin::Pin;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicUsize, Ordering};
21
22use await_tree::{InstrumentAwait, SpanExt};
23use bytes::Bytes;
24use fail::fail_point;
25use foyer::{
26 Cache, CacheBuilder, CacheEntry, EventListener, Hint, HybridCache, HybridCacheBuilder,
27 HybridCacheEntry, HybridCacheProperties,
28};
29use futures::{FutureExt, StreamExt, future};
30use prost::Message;
31use risingwave_hummock_sdk::sstable_info::SstableInfo;
32use risingwave_hummock_sdk::vector_index::{HnswGraphFileInfo, VectorFileInfo};
33use risingwave_hummock_sdk::{
34 HummockHnswGraphFileId, HummockObjectId, HummockRawObjectId, HummockSstableObjectId,
35 HummockVectorFileId, SST_OBJECT_SUFFIX,
36};
37use risingwave_hummock_trace::TracedCachePolicy;
38use risingwave_object_store::object::{
39 ObjectError, ObjectMetadataIter, ObjectResult, ObjectStoreRef, ObjectStreamingUploader,
40};
41use risingwave_pb::hummock::PbHnswGraph;
42use serde::{Deserialize, Serialize};
43use thiserror_ext::AsReport;
44use tokio::time::Instant;
45
46use super::{
47 BatchUploadWriter, Block, BlockMeta, BlockResponse, RecentFilter, Sstable, SstableMeta,
48 SstableWriterOptions,
49};
50use crate::hummock::block_stream::{BlockDataStream, MemoryUsageTracker, PrefetchBlockStream};
51use crate::hummock::none::NoneRecentFilter;
52use crate::hummock::vector::file::{VectorBlock, VectorBlockMeta, VectorFileMeta};
53use crate::hummock::vector::monitor::VectorStoreCacheStats;
54use crate::hummock::{BlockEntry, BlockHolder, HummockError, HummockResult, RecentFilterTrait};
55use crate::monitor::{HummockStateStoreMetrics, StoreLocalStatistic};
56
57macro_rules! impl_vector_index_meta_file {
58 ($($type_name:ident),+) => {
59 pub enum HummockVectorIndexMetaFile {
60 $(
61 $type_name(Pin<Box<$type_name>>),
62 )+
63 }
64
65 $(
66 impl From<$type_name> for HummockVectorIndexMetaFile {
67 fn from(v: $type_name) -> Self {
68 Self::$type_name(Box::pin(v))
69 }
70 }
71
72 unsafe impl Send for VectorMetaFileHolder<$type_name> {}
73
74 impl VectorMetaFileHolder<$type_name> {
75 fn try_from_entry(
76 entry: CacheEntry<HummockRawObjectId, HummockVectorIndexMetaFile>,
77 object_id: HummockRawObjectId
78 ) -> HummockResult<Self> {
79 let HummockVectorIndexMetaFile::$type_name(file_meta) = &*entry else {
80 return Err(HummockError::decode_error(format!(
81 "expect {} for object {}",
82 stringify!($type_name),
83 object_id
84 )));
85 };
86 let ptr = file_meta.as_ref().get_ref() as *const _;
87 Ok(VectorMetaFileHolder {
88 _cache_entry: entry,
89 ptr,
90 })
91 }
92 }
93 )+
94 };
95}
96
97impl_vector_index_meta_file!(VectorFileMeta, PbHnswGraph);
98
99pub struct VectorMetaFileHolder<T> {
100 _cache_entry: CacheEntry<HummockRawObjectId, HummockVectorIndexMetaFile>,
101 ptr: *const T,
102}
103
104impl<T> Deref for VectorMetaFileHolder<T> {
105 type Target = T;
106
107 fn deref(&self) -> &Self::Target {
108 unsafe { &*self.ptr }
110 }
111}
112
113#[derive(Debug)]
118pub struct SstableMetaCacheValue(Box<Sstable>);
119
120impl From<Sstable> for SstableMetaCacheValue {
121 fn from(sstable: Sstable) -> Self {
122 Self(Box::new(sstable))
123 }
124}
125
126impl Deref for SstableMetaCacheValue {
127 type Target = Sstable;
128
129 fn deref(&self) -> &Self::Target {
130 &self.0
131 }
132}
133
134impl AsRef<Sstable> for SstableMetaCacheValue {
135 fn as_ref(&self) -> &Sstable {
136 &self.0
137 }
138}
139
140impl foyer::Code for SstableMetaCacheValue {
141 fn encode(&self, writer: &mut impl std::io::Write) -> foyer::Result<()> {
142 bincode::serialize_into(writer, &self.0).map_err(foyer::Error::bincode_error)
143 }
144
145 fn decode(reader: &mut impl std::io::Read) -> foyer::Result<Self> {
146 bincode::deserialize_from(reader)
147 .map(Self)
148 .map_err(foyer::Error::bincode_error)
149 }
150
151 fn estimated_size(&self) -> usize {
152 self.0.serde_encoded_size()
153 }
154}
155
156pub type TableHolder = HybridCacheEntry<HummockSstableObjectId, SstableMetaCacheValue>;
157
158pub type VectorBlockHolder = CacheEntry<(HummockVectorFileId, usize), Box<VectorBlock>>;
159
160pub type VectorFileHolder = VectorMetaFileHolder<VectorFileMeta>;
161pub type HnswGraphFileHolder = VectorMetaFileHolder<PbHnswGraph>;
162
163#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
164pub struct SstableBlockIndex {
165 pub sst_id: HummockSstableObjectId,
166 pub block_idx: u64,
167}
168
169pub struct BlockCacheEventListener {
170 metrics: Arc<HummockStateStoreMetrics>,
171}
172
173impl BlockCacheEventListener {
174 pub fn new(metrics: Arc<HummockStateStoreMetrics>) -> Self {
175 Self { metrics }
176 }
177}
178
179impl EventListener for BlockCacheEventListener {
180 type Key = SstableBlockIndex;
181 type Value = Box<Block>;
182
183 fn on_leave(&self, _reason: foyer::Event, _key: &Self::Key, value: &Self::Value)
184 where
185 Self::Key: foyer::Key,
186 Self::Value: foyer::Value,
187 {
188 self.metrics
189 .block_efficiency_histogram
190 .observe(value.efficiency());
191 }
192}
193
194#[derive(Clone, Copy, Eq, PartialEq)]
196pub enum CachePolicy {
197 Disable,
199 Fill(Hint),
201 NotFill,
203}
204
205impl Default for CachePolicy {
206 fn default() -> Self {
207 CachePolicy::Fill(Hint::Normal)
208 }
209}
210
211impl From<TracedCachePolicy> for CachePolicy {
212 fn from(policy: TracedCachePolicy) -> Self {
213 match policy {
214 TracedCachePolicy::Disable => Self::Disable,
215 TracedCachePolicy::Fill(priority) => Self::Fill(priority.into()),
216 TracedCachePolicy::NotFill => Self::NotFill,
217 }
218 }
219}
220
221impl From<CachePolicy> for TracedCachePolicy {
222 fn from(policy: CachePolicy) -> Self {
223 match policy {
224 CachePolicy::Disable => Self::Disable,
225 CachePolicy::Fill(priority) => Self::Fill(priority.into()),
226 CachePolicy::NotFill => Self::NotFill,
227 }
228 }
229}
230
231pub struct SstableStoreConfig {
232 pub store: ObjectStoreRef,
233 pub path: String,
234
235 pub prefetch_buffer_capacity: usize,
236 pub max_prefetch_block_number: usize,
237 pub recent_filter: Arc<RecentFilter<(HummockSstableObjectId, usize)>>,
238 pub state_store_metrics: Arc<HummockStateStoreMetrics>,
239 pub use_new_object_prefix_strategy: bool,
240 pub skip_bloom_filter_in_serde: bool,
241
242 pub meta_cache: HybridCache<HummockSstableObjectId, SstableMetaCacheValue>,
243 pub block_cache: HybridCache<SstableBlockIndex, Box<Block>>,
244
245 pub vector_meta_cache: Cache<HummockRawObjectId, HummockVectorIndexMetaFile>,
246 pub vector_block_cache: Cache<(HummockVectorFileId, usize), Box<VectorBlock>>,
247}
248
249pub struct SstableStore {
250 path: Arc<str>,
251 store: ObjectStoreRef,
252
253 meta_cache: HybridCache<HummockSstableObjectId, SstableMetaCacheValue>,
254 block_cache: HybridCache<SstableBlockIndex, Box<Block>>,
255 pub vector_meta_cache: Cache<HummockRawObjectId, HummockVectorIndexMetaFile>,
256 pub vector_block_cache: Cache<(HummockVectorFileId, usize), Box<VectorBlock>>,
257
258 recent_filter: Arc<RecentFilter<(HummockSstableObjectId, usize)>>,
262 prefetch_buffer_usage: Arc<AtomicUsize>,
263 prefetch_buffer_capacity: usize,
264 max_prefetch_block_number: usize,
265 use_new_object_prefix_strategy: bool,
274
275 skip_bloom_filter_in_serde: bool,
279}
280
281impl SstableStore {
282 pub fn new(config: SstableStoreConfig) -> Self {
283 Self {
287 path: config.path.into(),
288 store: config.store,
289
290 meta_cache: config.meta_cache,
291 block_cache: config.block_cache,
292 vector_meta_cache: config.vector_meta_cache,
293 vector_block_cache: config.vector_block_cache,
294
295 recent_filter: config.recent_filter,
296 prefetch_buffer_usage: Arc::new(AtomicUsize::new(0)),
297 prefetch_buffer_capacity: config.prefetch_buffer_capacity,
298 max_prefetch_block_number: config.max_prefetch_block_number,
299 use_new_object_prefix_strategy: config.use_new_object_prefix_strategy,
300 skip_bloom_filter_in_serde: config.skip_bloom_filter_in_serde,
301 }
302 }
303
304 #[expect(clippy::borrowed_box)]
307 pub async fn for_compactor(
308 store: ObjectStoreRef,
309 path: String,
310 block_cache_capacity: usize,
311 meta_cache_capacity: usize,
312 use_new_object_prefix_strategy: bool,
313 ) -> HummockResult<Self> {
314 let meta_cache = HybridCacheBuilder::new()
315 .memory(meta_cache_capacity)
316 .with_shards(1)
317 .with_weighter(
318 |_: &HummockSstableObjectId, value: &SstableMetaCacheValue| {
319 std::mem::size_of::<HummockSstableObjectId>()
320 + value.estimated_meta_cache_memory_weight()
321 },
322 )
323 .storage()
324 .build()
325 .await
326 .map_err(HummockError::foyer_error)?;
327
328 let block_cache = HybridCacheBuilder::new()
329 .memory(block_cache_capacity)
330 .with_shards(1)
331 .with_weighter(|_: &SstableBlockIndex, value: &Box<Block>| {
332 std::mem::size_of::<SstableBlockIndex>() + value.estimated_memory_weight()
333 })
334 .storage()
335 .build()
336 .await
337 .map_err(HummockError::foyer_error)?;
338
339 Ok(Self {
340 path: path.into(),
341 store,
342
343 prefetch_buffer_usage: Arc::new(AtomicUsize::new(0)),
344 prefetch_buffer_capacity: block_cache_capacity,
345 max_prefetch_block_number: 16, recent_filter: Arc::new(NoneRecentFilter::default().into()),
347 use_new_object_prefix_strategy,
348 skip_bloom_filter_in_serde: false,
349
350 meta_cache,
351 block_cache,
352 vector_meta_cache: CacheBuilder::new(1 << 10).build(),
353 vector_block_cache: CacheBuilder::new(1 << 10).build(),
354 })
355 }
356
357 pub async fn delete(&self, object_id: HummockSstableObjectId) -> HummockResult<()> {
358 self.store
359 .delete(self.get_sst_data_path(object_id).as_str())
360 .await?;
361 self.meta_cache.remove(&object_id);
362 Ok(())
364 }
365
366 pub(crate) async fn put_sst_data(
367 &self,
368 object_id: HummockSstableObjectId,
369 data: Bytes,
370 ) -> HummockResult<()> {
371 let data_path = self.get_sst_data_path(object_id);
372 self.store
373 .upload(&data_path, data)
374 .await
375 .map_err(Into::into)
376 }
377
378 pub async fn prefetch_blocks(
382 &self,
383 sst: &Sstable,
384 block_index: usize,
385 end_index: usize,
386 policy: CachePolicy,
387 stats: &mut StoreLocalStatistic,
388 ) -> HummockResult<Box<PrefetchBlockStream>> {
389 let object_id = sst.id;
390 if self.prefetch_buffer_usage.load(Ordering::Acquire) > self.prefetch_buffer_capacity {
391 let block = self.get(sst, block_index, policy, stats).await?;
392 return Ok(Box::new(PrefetchBlockStream::new(
393 VecDeque::from([block]),
394 block_index,
395 None,
396 )));
397 }
398 if policy != CachePolicy::Disable
399 && let Some(entry) = self
400 .block_cache
401 .get(&SstableBlockIndex {
402 sst_id: object_id,
403 block_idx: block_index as _,
404 })
405 .await
406 .map_err(HummockError::foyer_error)?
407 {
408 stats.cache_data_block_total += 1;
409 if entry.source() == foyer::Source::Outer {
410 stats.cache_data_block_miss += 1;
411 }
412 let block = BlockHolder::from_hybrid_cache_entry(entry);
413 return Ok(Box::new(PrefetchBlockStream::new(
414 VecDeque::from([block]),
415 block_index,
416 None,
417 )));
418 }
419 let end_index = std::cmp::min(
420 end_index,
421 block_index.saturating_add(self.max_prefetch_block_number),
422 );
423 let mut end_index = std::cmp::min(end_index, sst.meta.block_metas.len());
424 let start_offset = sst.meta.block_metas[block_index].offset as usize;
425 if policy != CachePolicy::Disable {
426 let mut min_hit_index = end_index;
427 let mut hit_count = 0;
428 for idx in block_index..end_index {
429 if self.block_cache.contains(&SstableBlockIndex {
430 sst_id: object_id,
431 block_idx: idx as _,
432 }) {
433 if min_hit_index > idx && idx > block_index {
434 min_hit_index = idx;
435 }
436 hit_count += 1;
437 }
438 }
439
440 if hit_count * 3 >= (end_index - block_index)
441 || min_hit_index * 2 > block_index + end_index
442 {
443 end_index = min_hit_index;
444 }
445 }
446 stats.cache_data_prefetch_count += 1;
447 stats.cache_data_prefetch_block_count += (end_index - block_index) as u64;
448 let end_offset = start_offset
449 + sst.meta.block_metas[block_index..end_index]
450 .iter()
451 .map(|meta| meta.len as usize)
452 .sum::<usize>();
453 let data_path = self.get_sst_data_path(object_id);
454 let memory_usage = end_offset - start_offset;
455 let tracker = MemoryUsageTracker::new(self.prefetch_buffer_usage.clone(), memory_usage);
456 let span = await_tree::span!("Prefetch SST-{}", object_id).verbose();
457 let store = self.store.clone();
458 let join_handle = tokio::spawn(async move {
459 store
460 .read(&data_path, start_offset..end_offset)
461 .instrument_await(span)
462 .await
463 });
464 let buf = match join_handle.await {
465 Ok(Ok(data)) => data,
466 Ok(Err(e)) => {
467 tracing::error!(
468 "prefetch meet error when read {}..{} from sst-{} ({})",
469 start_offset,
470 end_offset,
471 object_id,
472 sst.meta.estimated_size,
473 );
474 return Err(e.into());
475 }
476 Err(_) => {
477 return Err(HummockError::other("cancel by other thread"));
478 }
479 };
480 let mut offset = 0;
481 let mut blocks = VecDeque::default();
482 for idx in block_index..end_index {
483 let end = offset + sst.meta.block_metas[idx].len as usize;
484 if end > buf.len() {
485 return Err(ObjectError::internal("read unexpected EOF").into());
486 }
487 let block = Block::decode_with_copy(
489 buf.slice(offset..end),
490 sst.meta.block_metas[idx].uncompressed_size as usize,
491 true,
492 )?;
493 let holder = if let CachePolicy::Fill(hint) = policy {
494 let hint = if idx == block_index { hint } else { Hint::Low };
495 let entry = self.block_cache.insert_with_properties(
496 SstableBlockIndex {
497 sst_id: object_id,
498 block_idx: idx as _,
499 },
500 Box::new(block),
501 HybridCacheProperties::default().with_hint(hint),
502 );
503 BlockHolder::from_hybrid_cache_entry(entry)
504 } else {
505 BlockHolder::from_owned_block(Box::new(block))
506 };
507
508 blocks.push_back(holder);
509 offset = end;
510 }
511 Ok(Box::new(PrefetchBlockStream::new(
512 blocks,
513 block_index,
514 Some(tracker),
515 )))
516 }
517
518 pub async fn get_block_response(
519 &self,
520 sst: &Sstable,
521 block_index: usize,
522 policy: CachePolicy,
523 ) -> HummockResult<BlockResponse> {
524 let object_id = sst.id;
525 let (range, uncompressed_capacity) = sst.calculate_block_info(block_index);
526 let store = self.store.clone();
527
528 let file_size = sst.meta.estimated_size;
529 let data_path = self.get_sst_data_path(object_id);
530
531 let disable_cache: fn() -> bool = || {
532 fail_point!("disable_block_cache", |_| true);
533 false
534 };
535
536 let policy = if disable_cache() {
537 CachePolicy::Disable
538 } else {
539 policy
540 };
541
542 let idx = SstableBlockIndex {
543 sst_id: object_id,
544 block_idx: block_index as _,
545 };
546
547 self.recent_filter
548 .extend([(object_id, usize::MAX), (object_id, block_index)]);
549
550 let fetch_block = async move {
552 let block_data = match store
553 .read(&data_path, range.clone())
554 .instrument_await("get_block_response".verbose())
555 .await
556 {
557 Ok(data) => data,
558 Err(e) => {
559 tracing::error!(
560 "get_block_response meet error when read {:?} from sst-{}, total length: {}",
561 range,
562 object_id,
563 file_size
564 );
565 return Err(HummockError::from(e));
566 }
567 };
568 let block = Box::new(Block::decode(block_data, uncompressed_capacity)?);
569 Ok(block)
570 };
571
572 match policy {
573 CachePolicy::Fill(hint) => {
574 let properties = HybridCacheProperties::default().with_hint(hint);
575 let fetch = self.block_cache.get_or_fetch(&idx, || {
576 fetch_block.map(|res| res.map(|block| (block, properties)))
577 });
578 Ok(BlockResponse::Fetch(fetch))
579 }
580 CachePolicy::NotFill => {
581 match self
582 .block_cache
583 .get(&idx)
584 .await
585 .map_err(HummockError::foyer_error)?
586 {
587 Some(entry) => Ok(BlockResponse::Block(BlockHolder::from_hybrid_cache_entry(
588 entry,
589 ))),
590 _ => {
591 let block = fetch_block.await?;
592 Ok(BlockResponse::Block(BlockHolder::from_owned_block(block)))
593 }
594 }
595 }
596 CachePolicy::Disable => {
597 let block = fetch_block.await?;
598 Ok(BlockResponse::Block(BlockHolder::from_owned_block(block)))
599 }
600 }
601 }
602
603 pub async fn get(
604 &self,
605 sst: &Sstable,
606 block_index: usize,
607 policy: CachePolicy,
608 stats: &mut StoreLocalStatistic,
609 ) -> HummockResult<BlockHolder> {
610 let block_response = self.get_block_response(sst, block_index, policy).await?;
611 let block_holder = block_response.wait().await?;
612 stats.cache_data_block_total += 1;
613 if let BlockEntry::HybridCache(entry) = block_holder.entry()
614 && entry.source() == foyer::Source::Outer
615 {
616 stats.cache_data_block_miss += 1;
617 }
618 Ok(block_holder)
619 }
620
621 pub async fn get_vector_file_meta(
622 &self,
623 vector_file: &VectorFileInfo,
624 stats: &mut VectorStoreCacheStats,
625 ) -> HummockResult<VectorFileHolder> {
626 let store = self.store.clone();
627 let path = self.get_object_data_path(HummockObjectId::VectorFile(vector_file.object_id));
628 let meta_offset = vector_file.meta_offset;
629 let entry = self
630 .vector_meta_cache
631 .get_or_fetch(&vector_file.object_id.as_raw(), || async move {
632 let encoded_footer = store.read(&path, meta_offset..).await?;
633 let meta = VectorFileMeta::decode_footer(&encoded_footer)?;
634 Ok::<_, anyhow::Error>(HummockVectorIndexMetaFile::from(meta))
635 })
636 .await?;
637 stats.file_meta_total += 1;
638 if entry.source() == foyer::Source::Outer {
639 stats.file_meta_miss += 1;
640 }
641 VectorFileHolder::try_from_entry(entry, vector_file.object_id.as_raw())
642 }
643
644 pub async fn get_vector_block(
645 &self,
646 vector_file: &VectorFileInfo,
647 block_idx: usize,
648 block_meta: &VectorBlockMeta,
649 stats: &mut VectorStoreCacheStats,
650 ) -> HummockResult<VectorBlockHolder> {
651 let store = self.store.clone();
652 let path = self.get_object_data_path(HummockObjectId::VectorFile(vector_file.object_id));
653 let start_offset = block_meta.offset;
654 let end_offset = start_offset + block_meta.block_size;
655 let entry = self
656 .vector_block_cache
657 .get_or_fetch(&(vector_file.object_id, block_idx), || async move {
658 let encoded_block = store.read(&path, start_offset..end_offset).await?;
659 let block = VectorBlock::decode(&encoded_block)?;
660 Ok::<_, anyhow::Error>(Box::new(block))
661 })
662 .await
663 .map_err(HummockError::foyer_error)?;
664
665 stats.file_block_total += 1;
666 if entry.source() == foyer::Source::Outer {
667 stats.file_block_miss += 1;
668 }
669 Ok(entry)
670 }
671
672 pub fn insert_vector_cache(
673 &self,
674 object_id: HummockVectorFileId,
675 meta: VectorFileMeta,
676 blocks: Vec<VectorBlock>,
677 ) {
678 self.vector_meta_cache
679 .insert(object_id.as_raw(), meta.into());
680 for (idx, block) in blocks.into_iter().enumerate() {
681 self.vector_block_cache
682 .insert((object_id, idx), Box::new(block));
683 }
684 }
685
686 pub fn insert_hnsw_graph_cache(&self, object_id: HummockHnswGraphFileId, graph: PbHnswGraph) {
687 self.vector_meta_cache
688 .insert(object_id.as_raw(), graph.into());
689 }
690
691 pub async fn get_hnsw_graph(
692 &self,
693 graph_file: &HnswGraphFileInfo,
694 stats: &mut VectorStoreCacheStats,
695 ) -> HummockResult<HnswGraphFileHolder> {
696 let store = self.store.clone();
697 let graph_file_path =
698 self.get_object_data_path(HummockObjectId::HnswGraphFile(graph_file.object_id));
699 let entry = self
700 .vector_meta_cache
701 .get_or_fetch(&graph_file.object_id.as_raw(), || async move {
702 let encoded_graph = store.read(&graph_file_path, ..).await?;
703 let graph = PbHnswGraph::decode(encoded_graph.as_ref())?;
704 Ok::<_, anyhow::Error>(HummockVectorIndexMetaFile::from(graph))
705 })
706 .await
707 .map_err(HummockError::foyer_error)?;
708 stats.hnsw_graph_total += 1;
709 if entry.source() == foyer::Source::Outer {
710 stats.hnsw_graph_miss += 1;
711 }
712 HnswGraphFileHolder::try_from_entry(entry, graph_file.object_id.as_raw())
713 }
714
715 pub fn get_sst_data_path(&self, object_id: impl Into<HummockSstableObjectId>) -> String {
716 self.get_object_data_path(HummockObjectId::Sstable(object_id.into()))
717 }
718
719 pub fn get_object_data_path(&self, object_id: HummockObjectId) -> String {
720 Self::build_object_data_path(
721 &self.store,
722 &self.path,
723 self.use_new_object_prefix_strategy,
724 object_id,
725 )
726 }
727
728 fn build_object_data_path(
729 store: &ObjectStoreRef,
730 directory: &str,
731 use_new_object_prefix_strategy: bool,
732 object_id: HummockObjectId,
733 ) -> String {
734 let prefix = store.get_object_prefix(
735 object_id.as_raw().as_raw_id(),
736 use_new_object_prefix_strategy,
737 );
738 risingwave_hummock_sdk::get_object_data_path(&prefix, directory, object_id)
739 }
740
741 pub fn get_object_id_from_path(path: &str) -> HummockObjectId {
742 risingwave_hummock_sdk::get_object_id_from_path(path)
743 }
744
745 pub fn store(&self) -> ObjectStoreRef {
746 self.store.clone()
747 }
748
749 #[cfg(any(test, feature = "test"))]
750 pub async fn clear_block_cache(&self) -> HummockResult<()> {
751 self.block_cache
752 .clear()
753 .await
754 .map_err(HummockError::foyer_error)
755 }
756
757 #[cfg(any(test, feature = "test"))]
758 pub async fn clear_meta_cache(&self) -> HummockResult<()> {
759 self.meta_cache
760 .clear()
761 .await
762 .map_err(HummockError::foyer_error)
763 }
764
765 pub async fn sstable_cached(
766 &self,
767 sst_obj_id: HummockSstableObjectId,
768 ) -> HummockResult<Option<TableHolder>> {
769 self.meta_cache
770 .get(&sst_obj_id)
771 .await
772 .map_err(HummockError::foyer_error)
773 }
774
775 pub async fn sstable(
777 &self,
778 sstable_info_ref: &SstableInfo,
779 stats: &mut StoreLocalStatistic,
780 ) -> HummockResult<TableHolder> {
781 let object_id = sstable_info_ref.object_id;
782 let store = self.store.clone();
783 let directory = self.path.clone();
784 let use_new_prefix = self.use_new_object_prefix_strategy;
785 let stats_ptr = stats.remote_io_time.clone();
786 let range = sstable_info_ref.meta_offset as usize..;
787 let skip_bloom_filter_in_serde = self.skip_bloom_filter_in_serde;
788
789 let fetch = self.meta_cache.get_or_fetch(&object_id, || async move {
790 let meta_path = Self::build_object_data_path(
791 &store,
792 &directory,
793 use_new_prefix,
794 HummockObjectId::Sstable(object_id),
795 );
796 let now = Instant::now();
797 let buf = store
798 .read(&meta_path, range)
799 .instrument_await("get_meta_response".verbose())
800 .await?;
801 let sst = Sstable::from_meta_bytes(object_id, &buf, skip_bloom_filter_in_serde)?;
802 let add = (now.elapsed().as_secs_f64() * 1000.0).ceil();
803 stats_ptr.fetch_add(add as u64, Ordering::Relaxed);
804 Ok::<_, anyhow::Error>(SstableMetaCacheValue::from(sst))
805 });
806
807 stats.cache_meta_block_total += 1;
808 let entry = fetch
809 .instrument_await("fetch_meta".verbose())
810 .await
811 .map_err(HummockError::foyer_error);
812 if let Ok(ref entry) = entry
813 && entry.source() == foyer::Source::Outer
814 {
815 stats.cache_meta_block_miss += 1;
816 }
817 entry
818 }
819
820 pub async fn list_sst_object_metadata_from_object_store(
821 &self,
822 prefix: Option<String>,
823 ) -> HummockResult<ObjectMetadataIter> {
824 let list_path = format!("{}/{}", self.path, prefix.unwrap_or("".into()));
825 let raw_iter = self.store.list(&list_path).await?;
826 let iter = raw_iter.filter(|r| match r {
827 Ok(i) => future::ready(i.key.ends_with(&format!(".{}", SST_OBJECT_SUFFIX))),
828 Err(_) => future::ready(true),
829 });
830 Ok(Box::pin(iter))
831 }
832
833 pub fn create_sst_writer(
834 self: Arc<Self>,
835 object_id: impl Into<HummockSstableObjectId>,
836 options: SstableWriterOptions,
837 ) -> BatchUploadWriter {
838 BatchUploadWriter::new(object_id, self, options)
839 }
840
841 pub fn insert_meta_cache(&self, object_id: HummockSstableObjectId, meta: SstableMeta) {
842 let sst = Sstable::new(object_id, meta, self.skip_bloom_filter_in_serde);
843 self.meta_cache
844 .insert(object_id, SstableMetaCacheValue::from(sst));
845 }
846
847 pub fn get_prefetch_memory_usage(&self) -> usize {
848 self.prefetch_buffer_usage.load(Ordering::Acquire)
849 }
850
851 pub async fn get_stream_for_blocks(
852 &self,
853 object_id: HummockSstableObjectId,
854 metas: &[BlockMeta],
855 ) -> HummockResult<BlockDataStream> {
856 fail_point!("get_stream_err");
857 let data_path = self.get_sst_data_path(object_id);
858 let store = self.store();
859 let block_meta = &metas[0];
860 let start_pos = block_meta.offset as usize;
861 let end_pos = metas.iter().map(|meta| meta.len as usize).sum::<usize>() + start_pos;
862 let range = start_pos..end_pos;
863 let ret = tokio::spawn(async move { store.streaming_read(&data_path, range).await }).await;
865
866 let reader = match ret {
867 Ok(Ok(reader)) => reader,
868 Ok(Err(e)) => return Err(HummockError::from(e)),
869 Err(e) => {
870 return Err(HummockError::other(format!(
871 "failed to get result, this read request may be canceled: {}",
872 e.as_report()
873 )));
874 }
875 };
876 Ok(BlockDataStream::new(reader, metas))
877 }
878
879 pub fn meta_cache(&self) -> &HybridCache<HummockSstableObjectId, SstableMetaCacheValue> {
880 &self.meta_cache
881 }
882
883 pub fn block_cache(&self) -> &HybridCache<SstableBlockIndex, Box<Block>> {
884 &self.block_cache
885 }
886
887 pub fn recent_filter(&self) -> &Arc<RecentFilter<(HummockSstableObjectId, usize)>> {
888 &self.recent_filter
889 }
890
891 pub async fn create_streaming_uploader(
892 &self,
893 path: &str,
894 ) -> ObjectResult<ObjectStreamingUploader> {
895 self.store.streaming_upload(path).await
896 }
897}
898
899pub type SstableStoreRef = Arc<SstableStore>;
900#[cfg(test)]
901mod tests {
902 use std::ops::Range;
903 use std::sync::Arc;
904
905 use risingwave_hummock_sdk::HummockObjectId;
906 use risingwave_hummock_sdk::sstable_info::SstableInfo;
907
908 use super::{SstableStoreRef, SstableWriterOptions};
909 use crate::hummock::iterator::HummockIterator;
910 use crate::hummock::iterator::test_utils::{iterator_test_key_of, mock_sstable_store};
911 use crate::hummock::sstable::SstableIteratorReadOptions;
912 use crate::hummock::test_utils::{
913 default_builder_opt_for_test, gen_default_test_sstable, gen_test_sstable_data, put_sst,
914 test_key_of,
915 };
916 use crate::hummock::value::HummockValue;
917 use crate::hummock::{CachePolicy, SstableIterator, SstableMeta, SstableStore};
918 use crate::monitor::StoreLocalStatistic;
919
920 const SST_ID: u64 = 1;
921
922 fn get_hummock_value(x: usize) -> HummockValue<Vec<u8>> {
923 HummockValue::put(format!("overlapped_new_{}", x).as_bytes().to_vec())
924 }
925
926 async fn validate_sst(
927 sstable_store: SstableStoreRef,
928 info: &SstableInfo,
929 mut meta: SstableMeta,
930 x_range: Range<usize>,
931 ) {
932 let mut stats = StoreLocalStatistic::default();
933 let holder = sstable_store.sstable(info, &mut stats).await.unwrap();
934 std::mem::take(&mut meta.bloom_filter);
935 assert_eq!(holder.meta, meta);
936 let holder = sstable_store.sstable(info, &mut stats).await.unwrap();
937 assert_eq!(holder.meta, meta);
938 let mut iter = SstableIterator::new(
939 holder,
940 sstable_store,
941 Arc::new(SstableIteratorReadOptions::default()),
942 info,
943 );
944 iter.rewind().await.unwrap();
945 for i in x_range {
946 let key = iter.key();
947 let value = iter.value();
948 assert_eq!(key, iterator_test_key_of(i).to_ref());
949 assert_eq!(value, get_hummock_value(i).as_slice());
950 iter.next().await.unwrap();
951 }
952 }
953
954 #[tokio::test]
955 async fn test_batch_upload() {
956 let sstable_store = mock_sstable_store().await;
957 let x_range = 0..100;
958 let (data, meta) = gen_test_sstable_data(
959 default_builder_opt_for_test(),
960 x_range
961 .clone()
962 .map(|x| (iterator_test_key_of(x), get_hummock_value(x))),
963 )
964 .await;
965 let writer_opts = SstableWriterOptions {
966 capacity_hint: None,
967 tracker: None,
968 policy: CachePolicy::Disable,
969 };
970 let info = put_sst(
971 SST_ID,
972 data.clone(),
973 meta.clone(),
974 sstable_store.clone(),
975 writer_opts,
976 vec![0],
977 )
978 .await
979 .unwrap();
980
981 validate_sst(sstable_store, &info, meta, x_range).await;
982 }
983
984 #[tokio::test]
985 async fn test_streaming_upload() {
986 let sstable_store = mock_sstable_store().await;
988 let x_range = 0..100;
989 let (data, meta) = gen_test_sstable_data(
990 default_builder_opt_for_test(),
991 x_range
992 .clone()
993 .map(|x| (iterator_test_key_of(x), get_hummock_value(x))),
994 )
995 .await;
996 let writer_opts = SstableWriterOptions {
997 capacity_hint: None,
998 tracker: None,
999 policy: CachePolicy::Disable,
1000 };
1001 let info = put_sst(
1002 SST_ID,
1003 data.clone(),
1004 meta.clone(),
1005 sstable_store.clone(),
1006 writer_opts,
1007 vec![0],
1008 )
1009 .await
1010 .unwrap();
1011
1012 validate_sst(sstable_store, &info, meta, x_range).await;
1013 }
1014
1015 #[tokio::test]
1016 async fn test_empty_prefetch_falls_back_to_block_get() {
1017 let mut sstable_store = mock_sstable_store().await;
1018 Arc::get_mut(&mut sstable_store)
1020 .unwrap()
1021 .max_prefetch_block_number = 0;
1022 let (sstable, info) =
1023 gen_default_test_sstable(default_builder_opt_for_test(), 0, sstable_store.clone())
1024 .await;
1025 sstable_store.clear_block_cache().await.unwrap();
1026 let mut iter = SstableIterator::new(
1027 sstable,
1028 sstable_store.clone(),
1029 Arc::new(SstableIteratorReadOptions {
1030 prefetch: true,
1031 cache_policy: CachePolicy::Disable,
1032 ..Default::default()
1033 }),
1034 &info,
1035 );
1036 tokio::time::timeout(std::time::Duration::from_secs(5), iter.rewind())
1037 .await
1038 .expect("empty prefetch must not cause an unbounded refill loop")
1039 .unwrap();
1040 assert_eq!(iter.key(), test_key_of(0).to_ref());
1041 let mut stats = StoreLocalStatistic::default();
1042 iter.collect_local_statistic(&mut stats);
1043 assert_eq!(stats.cache_data_prefetch_count, 1);
1044 assert_eq!(stats.cache_data_block_total, 1);
1045 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1046 }
1047
1048 #[tokio::test]
1049 async fn test_prefetch_failure_falls_back_and_releases_tracker() {
1050 for truncate in [true, false] {
1051 let sstable_store = mock_sstable_store().await;
1052 let (sstable, info) =
1053 gen_default_test_sstable(default_builder_opt_for_test(), 0, sstable_store.clone())
1054 .await;
1055 assert!(sstable.meta.block_metas.len() > 1);
1056 sstable_store.clear_block_cache().await.unwrap();
1057 let path = sstable_store.get_sst_data_path(sstable.id);
1058 let mut data = sstable_store.store.read(&path, ..).await.unwrap().to_vec();
1059 let second_offset = sstable.meta.block_metas[1].offset as usize;
1060 if truncate {
1061 data.truncate(second_offset);
1063 } else {
1064 data[second_offset] ^= 1;
1066 }
1067 sstable_store
1068 .store
1069 .upload(&path, data.into())
1070 .await
1071 .unwrap();
1072 let mut iter = SstableIterator::new(
1073 sstable.clone(),
1074 sstable_store.clone(),
1075 Arc::new(SstableIteratorReadOptions {
1076 prefetch: true,
1077 cache_policy: CachePolicy::Disable,
1078 ..Default::default()
1079 }),
1080 &info,
1081 );
1082 iter.rewind().await.unwrap();
1083 assert_eq!(iter.key(), test_key_of(0).to_ref());
1084 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1085 let mut stats = StoreLocalStatistic::default();
1086 iter.collect_local_statistic(&mut stats);
1087 assert_eq!(stats.cache_data_prefetch_count, 1);
1088 assert_eq!(stats.cache_data_block_total, 1);
1089 let second_key = risingwave_hummock_sdk::key::FullKey::decode(
1091 &sstable.meta.block_metas[1].smallest_key,
1092 );
1093 assert!(iter.seek(second_key).await.is_err());
1094 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1095 }
1096 }
1097
1098 #[tokio::test]
1099 async fn test_prefetch_releases_old_budget_before_refill() {
1100 let mut sstable_store = mock_sstable_store().await;
1101 Arc::get_mut(&mut sstable_store)
1104 .unwrap()
1105 .prefetch_buffer_capacity = 0;
1106 let (sstable, info) =
1107 gen_default_test_sstable(default_builder_opt_for_test(), 0, sstable_store.clone())
1108 .await;
1109 sstable_store.clear_block_cache().await.unwrap();
1110 let next_batch = sstable_store.max_prefetch_block_number;
1111 assert!(sstable.meta.block_metas.len() > next_batch + 1);
1112 let mut iter = SstableIterator::new(
1113 sstable.clone(),
1114 sstable_store.clone(),
1115 Arc::new(SstableIteratorReadOptions {
1116 prefetch: true,
1117 cache_policy: CachePolicy::Disable,
1118 ..Default::default()
1119 }),
1120 &info,
1121 );
1122 for idx in [0, next_batch] {
1123 let key = risingwave_hummock_sdk::key::FullKey::decode(
1124 &sstable.meta.block_metas[idx].smallest_key,
1125 );
1126 iter.seek(key).await.unwrap();
1127 assert_eq!(iter.key(), key);
1128 assert!(sstable_store.get_prefetch_memory_usage() > 0);
1129 }
1130 let mut stats = StoreLocalStatistic::default();
1131 iter.collect_local_statistic(&mut stats);
1132 assert_eq!(stats.cache_data_prefetch_count, 2);
1133 assert_eq!(stats.cache_data_block_total, 0);
1134 drop(iter);
1135 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1136 }
1137
1138 #[tokio::test]
1139 async fn test_prefetch_producer_large_limit() {
1140 let mut sstable_store = mock_sstable_store().await;
1141 Arc::get_mut(&mut sstable_store)
1142 .unwrap()
1143 .max_prefetch_block_number = usize::MAX;
1144 let (sstable, _) =
1145 gen_default_test_sstable(default_builder_opt_for_test(), 0, sstable_store.clone())
1146 .await;
1147 sstable_store.clear_block_cache().await.unwrap();
1148 let mut stats = StoreLocalStatistic::default();
1149 let mut stream = sstable_store
1150 .prefetch_blocks(&sstable, 1, 3, CachePolicy::Disable, &mut stats)
1151 .await
1152 .unwrap();
1153 assert_eq!(stats.cache_data_prefetch_block_count, 2);
1154 for idx in [1, 2] {
1155 assert!(matches!(
1156 stream.take_block(idx),
1157 crate::hummock::block_stream::PrefetchLookup::Hit(_)
1158 ));
1159 }
1160 assert!(matches!(
1161 stream.take_block(3),
1162 crate::hummock::block_stream::PrefetchLookup::Exhausted
1163 ));
1164 drop(stream);
1165 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1166 }
1167
1168 #[tokio::test]
1169 async fn test_prefetch_producer_respects_disabled_cache() {
1170 let sstable_store = mock_sstable_store().await;
1171 let (sstable, _) =
1172 gen_default_test_sstable(default_builder_opt_for_test(), 0, sstable_store.clone())
1173 .await;
1174 sstable_store.clear_block_cache().await.unwrap();
1175 sstable_store
1177 .get(
1178 &sstable,
1179 1,
1180 CachePolicy::Fill(foyer::Hint::Normal),
1181 &mut StoreLocalStatistic::default(),
1182 )
1183 .await
1184 .unwrap();
1185 let mut stats = StoreLocalStatistic::default();
1186 let stream = sstable_store
1187 .prefetch_blocks(&sstable, 0, 3, CachePolicy::Disable, &mut stats)
1188 .await
1189 .unwrap();
1190 assert_eq!(stats.cache_data_prefetch_block_count, 3);
1191 drop(stream);
1192 assert!(
1193 !sstable_store
1194 .block_cache
1195 .contains(&super::SstableBlockIndex {
1196 sst_id: sstable.id,
1197 block_idx: 0,
1198 })
1199 );
1200
1201 sstable_store
1203 .get(
1204 &sstable,
1205 0,
1206 CachePolicy::Fill(foyer::Hint::Normal),
1207 &mut StoreLocalStatistic::default(),
1208 )
1209 .await
1210 .unwrap();
1211 sstable_store.delete(sstable.id).await.unwrap();
1212 assert!(
1213 sstable_store
1214 .prefetch_blocks(
1215 &sstable,
1216 0,
1217 3,
1218 CachePolicy::NotFill,
1219 &mut StoreLocalStatistic::default()
1220 )
1221 .await
1222 .is_ok()
1223 );
1224 assert!(
1225 sstable_store
1226 .prefetch_blocks(
1227 &sstable,
1228 0,
1229 3,
1230 CachePolicy::Disable,
1231 &mut StoreLocalStatistic::default()
1232 )
1233 .await
1234 .is_err()
1235 );
1236 assert_eq!(sstable_store.get_prefetch_memory_usage(), 0);
1237 }
1238
1239 #[tokio::test]
1240 async fn test_basic() {
1241 let sstable_store = mock_sstable_store().await;
1242 let object_id = 123;
1243 let data_path = sstable_store.get_sst_data_path(object_id);
1244 assert_eq!(data_path, "test/123.data");
1245 assert_eq!(
1246 SstableStore::get_object_id_from_path(&data_path),
1247 HummockObjectId::Sstable(object_id.into())
1248 );
1249 }
1250
1251 #[tokio::test]
1252 async fn test_clear_file_cache_and_refetch() {
1253 let sstable_store = mock_sstable_store().await;
1254 let x_range = 0..10;
1255 let (data, meta) = gen_test_sstable_data(
1256 default_builder_opt_for_test(),
1257 x_range.map(|x| (iterator_test_key_of(x), get_hummock_value(x))),
1258 )
1259 .await;
1260 let info = put_sst(
1261 SST_ID,
1262 data,
1263 meta,
1264 sstable_store.clone(),
1265 SstableWriterOptions {
1266 capacity_hint: None,
1267 tracker: None,
1268 policy: CachePolicy::Fill(foyer::Hint::Normal),
1269 },
1270 vec![0],
1271 )
1272 .await
1273 .unwrap();
1274
1275 let mut stats = StoreLocalStatistic::default();
1276 assert!(
1277 sstable_store
1278 .sstable_cached(info.object_id)
1279 .await
1280 .unwrap()
1281 .is_some()
1282 );
1283 let sstable = sstable_store.sstable(&info, &mut stats).await.unwrap();
1284 sstable_store
1285 .get(
1286 &sstable,
1287 0,
1288 CachePolicy::Fill(foyer::Hint::Normal),
1289 &mut stats,
1290 )
1291 .await
1292 .unwrap();
1293 assert!(
1294 sstable_store
1295 .block_cache()
1296 .get(&super::SstableBlockIndex {
1297 sst_id: info.object_id,
1298 block_idx: 0,
1299 })
1300 .await
1301 .unwrap()
1302 .is_some()
1303 );
1304
1305 sstable_store.clear_meta_cache().await.unwrap();
1306 assert!(
1307 sstable_store
1308 .sstable_cached(info.object_id)
1309 .await
1310 .unwrap()
1311 .is_none()
1312 );
1313 sstable_store.sstable(&info, &mut stats).await.unwrap();
1314 assert!(
1315 sstable_store
1316 .sstable_cached(info.object_id)
1317 .await
1318 .unwrap()
1319 .is_some()
1320 );
1321
1322 sstable_store.clear_block_cache().await.unwrap();
1323 assert!(
1324 sstable_store
1325 .block_cache()
1326 .get(&super::SstableBlockIndex {
1327 sst_id: info.object_id,
1328 block_idx: 0,
1329 })
1330 .await
1331 .unwrap()
1332 .is_none()
1333 );
1334 sstable_store
1335 .get(
1336 &sstable,
1337 0,
1338 CachePolicy::Fill(foyer::Hint::Normal),
1339 &mut stats,
1340 )
1341 .await
1342 .unwrap();
1343 assert!(
1344 sstable_store
1345 .block_cache()
1346 .get(&super::SstableBlockIndex {
1347 sst_id: info.object_id,
1348 block_idx: 0,
1349 })
1350 .await
1351 .unwrap()
1352 .is_some()
1353 );
1354 }
1355}