1use std::collections::hash_map::HashMap;
16use std::collections::{HashSet, VecDeque};
17use std::future::poll_fn;
18use std::hash::Hash;
19use std::ops::{Bound, Range};
20use std::sync::{Arc, LazyLock};
21use std::task::Poll;
22use std::time::{Duration, Instant};
23
24use foyer::RangeBoundsExt;
25use futures::future::{join_all, try_join_all};
26use futures::{Future, FutureExt};
27use itertools::Itertools;
28use prometheus::core::{AtomicU64, GenericCounter, GenericCounterVec};
29use prometheus::{
30 Histogram, HistogramVec, IntGauge, Registry, register_histogram_vec_with_registry,
31 register_int_counter_vec_with_registry, register_int_gauge_with_registry,
32};
33use risingwave_common::bitmap::Bitmap;
34use risingwave_common::config::Role;
35use risingwave_common::config::streaming::CacheRefillPolicy;
36use risingwave_common::hash::VirtualNode;
37use risingwave_common::license::Feature;
38use risingwave_common::monitor::GLOBAL_METRICS_REGISTRY;
39use risingwave_common::util::iter_util::ZipEqFast;
40use risingwave_hummock_sdk::compaction_group::hummock_version_ext::SstDeltaInfo;
41use risingwave_hummock_sdk::key::{FullKey, vnode_range};
42use risingwave_hummock_sdk::{HummockSstableObjectId, KeyComparator};
43use risingwave_pb::id::TableId;
44use thiserror_ext::AsReport;
45use tokio::sync::Semaphore;
46use tokio::task::JoinHandle;
47
48use crate::hummock::local_version::pinned_version::PinnedVersion;
49use crate::hummock::{
50 Block, HummockError, HummockResult, RecentFilterTrait, Sstable, SstableBlockIndex,
51 SstableStoreRef, TableHolder,
52};
53use crate::monitor::StoreLocalStatistic;
54use crate::opts::StorageOpts;
55
56pub static GLOBAL_CACHE_REFILL_METRICS: LazyLock<CacheRefillMetrics> =
57 LazyLock::new(|| CacheRefillMetrics::new(&GLOBAL_METRICS_REGISTRY));
58
59pub struct CacheRefillMetrics {
60 pub refill_duration: HistogramVec,
61 pub refill_total: GenericCounterVec<AtomicU64>,
62 pub refill_bytes: GenericCounterVec<AtomicU64>,
63
64 pub data_refill_success_duration: Histogram,
65 pub meta_refill_success_duration: Histogram,
66
67 pub data_refill_filtered_total: GenericCounter<AtomicU64>,
68 pub data_refill_attempts_total: GenericCounter<AtomicU64>,
69 pub data_refill_started_total: GenericCounter<AtomicU64>,
70 pub meta_refill_attempts_total: GenericCounter<AtomicU64>,
71
72 pub data_refill_parent_meta_lookup_hit_total: GenericCounter<AtomicU64>,
73 pub data_refill_parent_meta_lookup_miss_total: GenericCounter<AtomicU64>,
74 pub data_refill_unit_inheritance_hit_total: GenericCounter<AtomicU64>,
75 pub data_refill_unit_inheritance_miss_total: GenericCounter<AtomicU64>,
76
77 pub data_refill_block_unfiltered_total: GenericCounter<AtomicU64>,
78 pub data_refill_block_success_total: GenericCounter<AtomicU64>,
79
80 pub data_refill_ideal_bytes: GenericCounter<AtomicU64>,
81 pub data_refill_success_bytes: GenericCounter<AtomicU64>,
82
83 pub refill_queue_total: IntGauge,
84}
85
86impl CacheRefillMetrics {
87 pub fn new(registry: &Registry) -> Self {
88 let refill_duration = register_histogram_vec_with_registry!(
89 "refill_duration",
90 "refill duration",
91 &["type", "op"],
92 registry,
93 )
94 .unwrap();
95 let refill_total = register_int_counter_vec_with_registry!(
96 "refill_total",
97 "refill total",
98 &["type", "op"],
99 registry,
100 )
101 .unwrap();
102 let refill_bytes = register_int_counter_vec_with_registry!(
103 "refill_bytes",
104 "refill bytes",
105 &["type", "op"],
106 registry,
107 )
108 .unwrap();
109
110 let data_refill_success_duration = refill_duration
111 .get_metric_with_label_values(&["data", "success"])
112 .unwrap();
113 let meta_refill_success_duration = refill_duration
114 .get_metric_with_label_values(&["meta", "success"])
115 .unwrap();
116
117 let data_refill_filtered_total = refill_total
118 .get_metric_with_label_values(&["data", "filtered"])
119 .unwrap();
120 let data_refill_attempts_total = refill_total
121 .get_metric_with_label_values(&["data", "attempts"])
122 .unwrap();
123 let data_refill_started_total = refill_total
124 .get_metric_with_label_values(&["data", "started"])
125 .unwrap();
126 let meta_refill_attempts_total = refill_total
127 .get_metric_with_label_values(&["meta", "attempts"])
128 .unwrap();
129
130 let data_refill_parent_meta_lookup_hit_total = refill_total
131 .get_metric_with_label_values(&["parent_meta", "hit"])
132 .unwrap();
133 let data_refill_parent_meta_lookup_miss_total = refill_total
134 .get_metric_with_label_values(&["parent_meta", "miss"])
135 .unwrap();
136 let data_refill_unit_inheritance_hit_total = refill_total
137 .get_metric_with_label_values(&["unit_inheritance", "hit"])
138 .unwrap();
139 let data_refill_unit_inheritance_miss_total = refill_total
140 .get_metric_with_label_values(&["unit_inheritance", "miss"])
141 .unwrap();
142
143 let data_refill_block_unfiltered_total = refill_total
144 .get_metric_with_label_values(&["block", "unfiltered"])
145 .unwrap();
146 let data_refill_block_success_total = refill_total
147 .get_metric_with_label_values(&["block", "success"])
148 .unwrap();
149
150 let data_refill_ideal_bytes = refill_bytes
151 .get_metric_with_label_values(&["data", "ideal"])
152 .unwrap();
153 let data_refill_success_bytes = refill_bytes
154 .get_metric_with_label_values(&["data", "success"])
155 .unwrap();
156
157 let refill_queue_total = register_int_gauge_with_registry!(
158 "refill_queue_total",
159 "refill queue total",
160 registry,
161 )
162 .unwrap();
163
164 Self {
165 refill_duration,
166 refill_total,
167 refill_bytes,
168
169 data_refill_success_duration,
170 meta_refill_success_duration,
171 data_refill_filtered_total,
172 data_refill_attempts_total,
173 data_refill_started_total,
174 meta_refill_attempts_total,
175
176 data_refill_parent_meta_lookup_hit_total,
177 data_refill_parent_meta_lookup_miss_total,
178 data_refill_unit_inheritance_hit_total,
179 data_refill_unit_inheritance_miss_total,
180
181 data_refill_block_unfiltered_total,
182 data_refill_block_success_total,
183
184 data_refill_ideal_bytes,
185 data_refill_success_bytes,
186
187 refill_queue_total,
188 }
189 }
190}
191
192#[derive(Debug)]
193pub struct CacheRefillConfig {
194 pub timeout: Duration,
196
197 pub data_refill_levels: HashSet<u32>,
199
200 pub meta_refill_concurrency: usize,
202
203 pub concurrency: usize,
205
206 pub unit: usize,
208
209 pub threshold: f64,
213
214 pub skip_recent_filter: bool,
216
217 pub skip_inheritance_filter: bool,
219
220 pub table_cache_refill_default_policy: CacheRefillPolicy,
222}
223
224impl CacheRefillConfig {
225 pub fn from_storage_opts(options: &StorageOpts) -> Self {
226 let data_refill_levels = match Feature::ElasticDiskCache.check_available() {
227 Ok(_) => options
228 .cache_refill_data_refill_levels
229 .iter()
230 .copied()
231 .collect(),
232 Err(e) => {
233 tracing::warn!(error = %e.as_report(), "ElasticDiskCache is not available.");
234 HashSet::new()
235 }
236 };
237
238 Self {
239 timeout: Duration::from_millis(options.cache_refill_timeout_ms),
240 data_refill_levels,
241 concurrency: options.cache_refill_concurrency,
242 meta_refill_concurrency: options.cache_refill_meta_refill_concurrency,
243 unit: options.cache_refill_unit,
244 threshold: options.cache_refill_threshold,
245 skip_recent_filter: options.cache_refill_skip_recent_filter,
246 skip_inheritance_filter: options.cache_refill_skip_inheritance_filter,
247 table_cache_refill_default_policy: options
248 .cache_refill_table_cache_refill_default_policy,
249 }
250 }
251}
252
253struct Item {
254 handle: JoinHandle<()>,
255 event: CacheRefillerEvent,
256}
257
258pub(crate) type SpawnRefillTask = Arc<
259 dyn Fn(Vec<SstDeltaInfo>, CacheRefillContext, PinnedVersion, PinnedVersion) -> JoinHandle<()>
261 + Send
262 + Sync
263 + 'static,
264>;
265
266pub type TableCacheRefillContextMap = HashMap<TableId, TableCacheRefillContext>;
267
268#[derive(Clone)]
271pub struct TableCacheRefillContext {
272 pub streaming_vnode_bitmap: Option<Bitmap>,
274 pub serving_vnode_bitmap: Option<Bitmap>,
276 pub policy: CacheRefillPolicy,
278}
279
280#[derive(Clone)]
284pub struct TableCacheRefillMonitorSnapshot {
285 pub contexts: TableCacheRefillContextMap,
286 pub policies: HashMap<TableId, CacheRefillPolicy>,
287 pub default_policy: CacheRefillPolicy,
288 pub streaming_table_vnode_mapping: HashMap<TableId, Bitmap>,
289 pub serving_table_vnode_mapping: HashMap<TableId, Bitmap>,
290}
291
292fn vnode_range_overlaps_bitmap(vnode_range: (usize, usize), bitmap: &Bitmap) -> bool {
293 assert!(vnode_range.0 <= vnode_range.1);
294 let start = vnode_range.0.min(bitmap.len());
295 let end = vnode_range.1.min(bitmap.len());
296 if start == end || !bitmap.any() {
297 return false;
298 }
299 if bitmap.all() {
300 return true;
301 }
302 (start..end).any(|vnode| bitmap.is_set(vnode))
303}
304
305impl TableCacheRefillContext {
306 fn allows_normal_data_refill_block(&self, sstable: &Sstable, block_index: usize) -> bool {
307 if self.policy.is_unscoped_enabled() {
308 return true;
309 }
310
311 (self.policy.is_streaming_scoped()
312 && self.check_table_refill_streaming_vnodes(sstable, block_index))
313 || (self.policy.is_serving_scoped()
314 && self.check_table_refill_serving_vnodes(sstable, block_index))
315 }
316
317 fn allows_insert_only_data_refill_block(&self, sstable: &Sstable, block_index: usize) -> bool {
318 (self.policy.is_unscoped_enabled() || self.policy.is_serving_scoped())
322 && self.check_table_refill_serving_vnodes(sstable, block_index)
323 }
324
325 fn check_table_refill_streaming_vnodes(&self, sstable: &Sstable, block_index: usize) -> bool {
326 self.streaming_vnode_bitmap.as_ref().is_some_and(|bitmap| {
327 let vnode_range = block_vnode_range(sstable, block_index);
328 vnode_range_overlaps_bitmap(vnode_range, bitmap)
329 })
330 }
331
332 fn check_table_refill_serving_vnodes(&self, sstable: &Sstable, block_index: usize) -> bool {
333 self.serving_vnode_bitmap.as_ref().is_some_and(|bitmap| {
334 let vnode_range = block_vnode_range(sstable, block_index);
335 vnode_range_overlaps_bitmap(vnode_range, bitmap)
336 })
337 }
338}
339
340fn block_vnode_range(sstable: &Sstable, block_index: usize) -> (usize, usize) {
341 let block_meta = &sstable.meta.block_metas[block_index];
342 let block_smallest_key = FullKey::decode(&block_meta.smallest_key);
343 let table_key_end = match sstable.meta.block_metas.get(block_index + 1) {
344 Some(next_block_meta) if next_block_meta.table_id() != block_meta.table_id() => {
347 Bound::Unbounded
348 }
349 Some(next_block_meta) => Bound::Included(
352 FullKey::decode(&next_block_meta.smallest_key)
353 .user_key
354 .table_key,
355 ),
356 None => Bound::Included(
360 FullKey::decode(&sstable.meta.largest_key)
361 .user_key
362 .table_key,
363 ),
364 };
365
366 let table_key_range = (
367 Bound::Included(block_smallest_key.user_key.table_key),
368 table_key_end,
369 );
370 if match &table_key_range.0 {
374 Bound::Included(key) | Bound::Excluded(key) => key.as_ref().len() < VirtualNode::SIZE,
375 Bound::Unbounded => false,
376 } || match &table_key_range.1 {
377 Bound::Included(key) | Bound::Excluded(key) => key.as_ref().len() < VirtualNode::SIZE,
378 Bound::Unbounded => false,
379 } {
380 return (0, VirtualNode::MAX_REPRESENTABLE.to_index() + 1);
381 }
382 vnode_range(&table_key_range)
383}
384
385pub(crate) struct CacheRefiller {
387 queue: VecDeque<Item>,
389
390 spawn_refill_task: SpawnRefillTask,
391
392 config: Arc<CacheRefillConfig>,
393 meta_refill_concurrency: Option<Arc<Semaphore>>,
394 concurrency: Arc<Semaphore>,
395 sstable_store: SstableStoreRef,
396
397 role: Role,
398 default_policy: CacheRefillPolicy,
399 table_cache_refill_policies: HashMap<TableId, CacheRefillPolicy>,
400 streaming_table_vnode_mapping: HashMap<TableId, Bitmap>,
401 serving_table_vnode_mapping: HashMap<TableId, Bitmap>,
402}
403
404impl CacheRefiller {
405 pub(crate) fn new(
406 role: Role,
407 config: CacheRefillConfig,
408 sstable_store: SstableStoreRef,
409 spawn_refill_task: SpawnRefillTask,
410 ) -> Self {
411 let config = Arc::new(config);
412 let concurrency = Arc::new(Semaphore::new(config.concurrency));
413 let default_policy = config.table_cache_refill_default_policy;
414 let meta_refill_concurrency = if config.meta_refill_concurrency == 0 {
415 None
416 } else {
417 Some(Arc::new(Semaphore::new(config.meta_refill_concurrency)))
418 };
419 Self {
420 queue: VecDeque::new(),
421 spawn_refill_task,
422 config,
423 meta_refill_concurrency,
424 concurrency,
425 sstable_store,
426 role,
427 default_policy,
428 table_cache_refill_policies: HashMap::new(),
429 streaming_table_vnode_mapping: HashMap::new(),
430 serving_table_vnode_mapping: HashMap::new(),
431 }
432 }
433
434 pub(crate) fn default_spawn_refill_task() -> SpawnRefillTask {
435 Arc::new(|deltas, context, _, _| {
436 let task = CacheRefillTask { deltas, context };
437 tokio::spawn(task.run())
438 })
439 }
440
441 pub(crate) fn start_cache_refill(
442 &mut self,
443 mut deltas: Vec<SstDeltaInfo>,
444 pinned_version: PinnedVersion,
445 new_pinned_version: PinnedVersion,
446 ) {
447 for delta in &mut deltas {
448 let for_serving = self.role.for_serving();
449 let for_streaming =
452 self.role.for_streaming() && !delta.delete_sst_object_ids.is_empty();
453
454 if !for_serving && !for_streaming {
455 delta.insert_sst_infos.clear();
456 continue;
457 }
458
459 delta.insert_sst_infos.retain(|sst| {
464 sst.table_ids.iter().any(|table_id| {
465 let policy = self
468 .table_cache_refill_policies
469 .get(table_id)
470 .copied()
471 .unwrap_or(self.default_policy);
472
473 match policy {
476 CacheRefillPolicy::Enabled => for_streaming || for_serving,
477 CacheRefillPolicy::Disabled => false,
478 CacheRefillPolicy::Streaming => {
479 for_streaming
480 && self.streaming_table_vnode_mapping.contains_key(table_id)
481 }
482 CacheRefillPolicy::Serving => {
483 for_serving && self.serving_table_vnode_mapping.contains_key(table_id)
484 }
485 CacheRefillPolicy::Both => {
486 (for_streaming
487 && self.streaming_table_vnode_mapping.contains_key(table_id))
488 || (for_serving
489 && self.serving_table_vnode_mapping.contains_key(table_id))
490 }
491 }
492 })
493 });
494 }
495 let context = self.new_cache_refill_context(&deltas);
496 let handle = (self.spawn_refill_task)(
497 deltas,
498 context,
499 pinned_version.clone(),
500 new_pinned_version.clone(),
501 );
502 let event = CacheRefillerEvent {
503 pinned_version,
504 new_pinned_version,
505 };
506 let item = Item { handle, event };
507 self.queue.push_back(item);
508 GLOBAL_CACHE_REFILL_METRICS.refill_queue_total.add(1);
509 }
510
511 fn new_cache_refill_context(&self, deltas: &[SstDeltaInfo]) -> CacheRefillContext {
512 let table_ids = deltas.iter().flat_map(|delta| {
513 delta
514 .insert_sst_infos
515 .iter()
516 .flat_map(|sst| sst.table_ids.iter().copied())
517 });
518 CacheRefillContext {
519 config: self.config.clone(),
520 meta_refill_concurrency: self.meta_refill_concurrency.clone(),
521 concurrency: self.concurrency.clone(),
522 sstable_store: self.sstable_store.clone(),
523 table_cache_refill_context_map: Arc::new(self.table_cache_refill_contexts(table_ids)),
524 }
525 }
526
527 pub(crate) fn last_new_pinned_version(&self) -> Option<&PinnedVersion> {
528 self.queue.back().map(|item| &item.event.new_pinned_version)
529 }
530
531 pub(crate) fn replace_table_cache_refill_policies(
533 &mut self,
534 policies: HashMap<TableId, CacheRefillPolicy>,
535 ) {
536 self.table_cache_refill_policies = policies;
537 }
538
539 pub(crate) fn replace_serving_table_vnode_mapping(
541 &mut self,
542 mapping: HashMap<TableId, Bitmap>,
543 ) {
544 self.serving_table_vnode_mapping = mapping;
545 }
546
547 pub(crate) fn update_streaming_table_vnodes(
548 &mut self,
549 table_id: TableId,
550 streaming_vnodes: Option<Bitmap>,
551 ) {
552 if let Some(streaming_vnodes) = streaming_vnodes {
553 self.streaming_table_vnode_mapping
554 .insert(table_id, streaming_vnodes);
555 } else {
556 self.streaming_table_vnode_mapping.remove(&table_id);
557 }
558 }
559
560 fn table_cache_refill_contexts(
561 &self,
562 table_ids: impl IntoIterator<Item = TableId>,
563 ) -> TableCacheRefillContextMap {
564 let for_streaming = self.role.for_streaming();
565 let for_serving = self.role.for_serving();
566 table_ids
567 .into_iter()
568 .filter_map(|table_id| {
569 if for_serving
570 && !for_streaming
571 && !self.serving_table_vnode_mapping.contains_key(&table_id)
572 {
573 return None;
574 }
575 let policy = self
576 .table_cache_refill_policies
577 .get(&table_id)
578 .copied()
579 .unwrap_or(self.default_policy);
580 let streaming_vnode_bitmap = (for_streaming && policy.is_streaming_scoped())
581 .then(|| self.streaming_table_vnode_mapping.get(&table_id).cloned())
582 .flatten();
583 let serving_vnode_bitmap = (for_serving
586 && (policy.is_serving_scoped() || policy.is_unscoped_enabled()))
587 .then(|| self.serving_table_vnode_mapping.get(&table_id).cloned())
588 .flatten();
589 Some((
590 table_id,
591 TableCacheRefillContext {
592 streaming_vnode_bitmap,
593 serving_vnode_bitmap,
594 policy,
595 },
596 ))
597 })
598 .collect()
599 }
600
601 pub(crate) fn table_cache_refill_monitor_snapshot(&self) -> TableCacheRefillMonitorSnapshot {
602 let table_ids = self
603 .table_cache_refill_policies
604 .keys()
605 .chain(self.streaming_table_vnode_mapping.keys())
606 .chain(self.serving_table_vnode_mapping.keys())
607 .copied();
608 TableCacheRefillMonitorSnapshot {
609 contexts: self.table_cache_refill_contexts(table_ids),
610 policies: self.table_cache_refill_policies.clone(),
611 default_policy: self.default_policy,
612 streaming_table_vnode_mapping: self.streaming_table_vnode_mapping.clone(),
613 serving_table_vnode_mapping: self.serving_table_vnode_mapping.clone(),
614 }
615 }
616}
617
618impl CacheRefiller {
619 pub(crate) fn next_events(&mut self) -> impl Future<Output = Vec<CacheRefillerEvent>> + '_ {
620 poll_fn(|cx| {
621 const MAX_BATCH_SIZE: usize = 16;
622 let mut events = None;
623 while let Some(item) = self.queue.front_mut()
624 && let Poll::Ready(result) = item.handle.poll_unpin(cx)
625 {
626 result.unwrap();
627 let item = self.queue.pop_front().unwrap();
628 GLOBAL_CACHE_REFILL_METRICS.refill_queue_total.sub(1);
629 let events = events.get_or_insert_with(|| Vec::with_capacity(MAX_BATCH_SIZE));
630 events.push(item.event);
631 if events.len() >= MAX_BATCH_SIZE {
632 break;
633 }
634 }
635 if let Some(events) = events {
636 Poll::Ready(events)
637 } else {
638 Poll::Pending
639 }
640 })
641 }
642}
643
644pub struct CacheRefillerEvent {
645 pub pinned_version: PinnedVersion,
646 pub new_pinned_version: PinnedVersion,
647}
648
649#[derive(Clone)]
650pub(crate) struct CacheRefillContext {
651 config: Arc<CacheRefillConfig>,
652 meta_refill_concurrency: Option<Arc<Semaphore>>,
653 concurrency: Arc<Semaphore>,
654 sstable_store: SstableStoreRef,
655 table_cache_refill_context_map: Arc<TableCacheRefillContextMap>,
656}
657
658struct DataCacheRefillTaskGenerator<'a> {
659 context: &'a CacheRefillContext,
660 delta: &'a SstDeltaInfo,
661 ssts: &'a [TableHolder],
662}
663
664impl DataCacheRefillTaskGenerator<'_> {
665 fn generate_unfiltered_tasks(&self) -> Vec<DataCacheRefillTask> {
666 let mut tasks = Vec::new();
667
668 if !self.context.sstable_store.block_cache().is_hybrid() {
670 return tasks;
671 }
672
673 if self.delta.insert_sst_infos.is_empty() {
674 return tasks;
675 }
676
677 let has_parent_ssts = !self.delta.delete_sst_object_ids.is_empty();
678 debug_assert!(has_parent_ssts || self.delta.insert_sst_level == 0);
681
682 if !self
684 .context
685 .config
686 .data_refill_levels
687 .contains(&self.delta.insert_sst_level)
688 {
689 return tasks;
690 }
691
692 let unit = self.context.config.unit;
695 assert!(unit > 0, "cache refill unit must be positive");
696 let table_cache_refill_context_map = &self.context.table_cache_refill_context_map;
697 for (sst_info, sst) in self.delta.insert_sst_infos.iter().zip_eq_fast(self.ssts) {
698 debug_assert_eq!(sst_info.object_id, sst.id);
699 debug_assert!(sst_info.table_ids.is_sorted());
700 let mut blk_start = 0;
701 while blk_start < sst.block_count() {
702 let table_id = sst.meta.block_metas[blk_start].table_id();
706 let mut blk_end = std::cmp::min(sst.block_count(), blk_start + unit);
707 if let Some(table_boundary) = (blk_start + 1..blk_end)
708 .find(|&block_index| sst.meta.block_metas[block_index].table_id() != table_id)
709 {
710 blk_end = table_boundary;
711 }
712
713 let should_refill = sst_info.table_ids.binary_search(&table_id).is_ok()
714 && (blk_start..blk_end).any(|block_index| {
715 table_cache_refill_context_map
716 .get(&table_id)
717 .is_some_and(|context| {
718 if has_parent_ssts {
719 context.allows_normal_data_refill_block(sst, block_index)
720 } else {
721 context.allows_insert_only_data_refill_block(sst, block_index)
722 }
723 })
724 });
725 if should_refill {
726 tasks.push(DataCacheRefillTask {
727 sst: sst.clone(),
728 blks: blk_start..blk_end,
729 });
730 }
731 blk_start = blk_end;
732 }
733 }
734
735 if tasks.is_empty() {
736 return tasks;
737 }
738
739 if has_parent_ssts
742 && !self.context.config.skip_recent_filter
743 && !self.filter_by_recent_filter()
744 {
745 GLOBAL_CACHE_REFILL_METRICS
746 .data_refill_filtered_total
747 .inc_by(self.delta.delete_sst_object_ids.len() as u64);
748 return vec![];
749 }
750
751 tasks
752 }
753
754 async fn filter_by_inheritance_if_needed(
755 &self,
756 tasks: Vec<DataCacheRefillTask>,
757 ) -> Vec<DataCacheRefillTask> {
758 let should_filter_by_inheritance = !tasks.is_empty()
761 && !self.delta.delete_sst_object_ids.is_empty()
762 && self.delta.insert_sst_level != 0
763 && !self.context.config.skip_recent_filter
764 && !self.context.config.skip_inheritance_filter;
765 if should_filter_by_inheritance {
766 self.filter_by_inheritance_filter(tasks).await
767 } else {
768 tasks
769 }
770 }
771
772 fn filter_by_recent_filter(&self) -> bool {
774 let recent_filter = self.context.sstable_store.recent_filter();
775 let targets = self
776 .delta
777 .delete_sst_object_ids
778 .iter()
779 .map(|id| (*id, usize::MAX))
780 .collect_vec();
781 recent_filter.contains_any(targets.iter())
782 }
783
784 async fn filter_by_inheritance_filter(
785 &self,
786 originals: Vec<DataCacheRefillTask>,
787 ) -> Vec<DataCacheRefillTask> {
788 let sstable_store = self.context.sstable_store.clone();
790 let futures = self.delta.delete_sst_object_ids.iter().map(|sst_obj_id| {
791 let store = &sstable_store;
792 async move {
793 let res = store.sstable_cached(*sst_obj_id).await;
794 match res {
795 Ok(Some(_)) => GLOBAL_CACHE_REFILL_METRICS
796 .data_refill_parent_meta_lookup_hit_total
797 .inc(),
798 Ok(None) => GLOBAL_CACHE_REFILL_METRICS
799 .data_refill_parent_meta_lookup_miss_total
800 .inc(),
801 _ => {}
802 }
803 res
804 }
805 });
806 let parent_ssts = match try_join_all(futures).await {
807 Ok(parent_ssts) => parent_ssts.into_iter().flatten(),
808 Err(e) => {
809 tracing::error!(error = %e.as_report(), "get old meta from cache error");
810 return vec![];
811 }
812 };
813
814 if cfg!(debug_assertions) {
816 originals.iter().tuple_windows().for_each(|(a, b)| {
817 debug_assert_ne!(
818 KeyComparator::compare_encoded_full_key(a.largest_key(), b.smallest_key()),
819 std::cmp::Ordering::Greater
820 )
821 });
822 }
823
824 let mut filtered: HashSet<SstableUnit> = HashSet::default();
825 let recent_filter = self.context.sstable_store.recent_filter();
826 for psst in parent_ssts {
827 for pblk in 0..psst.block_count() {
828 let pleft = &psst.meta.block_metas[pblk].smallest_key;
829 let pright = if pblk + 1 == psst.block_count() {
830 &psst.meta.largest_key
832 } else {
833 &psst.meta.block_metas[pblk + 1].smallest_key
834 };
835
836 let uleft = originals.partition_point(|task| {
838 KeyComparator::compare_encoded_full_key(task.largest_key(), pleft)
839 == std::cmp::Ordering::Less
840 });
841 let uright = originals.partition_point(|task| {
843 KeyComparator::compare_encoded_full_key(task.smallest_key(), pright)
844 != std::cmp::Ordering::Greater
845 });
846
847 for task in originals.iter().take(uright).skip(uleft) {
849 let unit = task.unit();
850 if filtered.contains(&unit) {
851 continue;
852 }
853 if recent_filter.contains(&(psst.id, pblk)) {
854 filtered.insert(unit);
855 }
856 }
857 }
858 }
859
860 let hit = filtered.len();
861 let miss = originals.len() - hit;
862 GLOBAL_CACHE_REFILL_METRICS
863 .data_refill_unit_inheritance_hit_total
864 .inc_by(hit as u64);
865 GLOBAL_CACHE_REFILL_METRICS
866 .data_refill_unit_inheritance_miss_total
867 .inc_by(miss as u64);
868
869 originals
870 .into_iter()
871 .filter(|task| filtered.contains(&task.unit()))
872 .collect()
873 }
874}
875
876#[derive(Debug)]
877struct DataCacheRefillTask {
878 sst: TableHolder,
879 blks: Range<usize>,
880}
881
882impl DataCacheRefillTask {
883 fn unit(&self) -> SstableUnit {
884 SstableUnit {
885 sst_obj_id: self.sst.id,
886 blks: self.blks.clone(),
887 }
888 }
889
890 fn smallest_key(&self) -> &[u8] {
891 &self.sst.meta.block_metas[self.blks.start].smallest_key
892 }
893
894 fn largest_key(&self) -> &[u8] {
895 if self.blks.end == self.sst.block_count() {
896 &self.sst.meta.largest_key
897 } else {
898 &self.sst.meta.block_metas[self.blks.end].smallest_key
899 }
900 }
901}
902
903struct CacheRefillTask {
904 deltas: Vec<SstDeltaInfo>,
905 context: CacheRefillContext,
906}
907
908impl CacheRefillTask {
909 async fn run(self) {
910 let tasks = self
911 .deltas
912 .iter()
913 .map(|delta| {
914 let context = self.context.clone();
915 async move {
916 let holders = match Self::meta_cache_refill(&context, delta).await {
917 Ok(holders) => holders,
918 Err(e) => {
919 tracing::warn!(error = %e.as_report(), "meta cache refill error");
920 return;
921 }
922 };
923 let generator = DataCacheRefillTaskGenerator {
924 context: &context,
925 delta,
926 ssts: &holders,
927 };
928 let tasks = generator.generate_unfiltered_tasks();
929
930 let unfiltered_block_count =
932 tasks.iter().map(|task| task.blks.len() as u64).sum();
933 GLOBAL_CACHE_REFILL_METRICS
934 .data_refill_block_unfiltered_total
935 .inc_by(unfiltered_block_count);
936
937 let tasks = generator.filter_by_inheritance_if_needed(tasks).await;
938 Self::data_cache_refill(&context, tasks).await;
939 }
940 })
941 .collect_vec();
942 let future = join_all(tasks);
943
944 let _ = tokio::time::timeout(self.context.config.timeout, future).await;
945 }
946
947 async fn meta_cache_refill(
948 context: &CacheRefillContext,
949 delta: &SstDeltaInfo,
950 ) -> HummockResult<Vec<TableHolder>> {
951 let tasks = delta
952 .insert_sst_infos
953 .iter()
954 .map(|info| async {
955 let mut stats = StoreLocalStatistic::default();
956 GLOBAL_CACHE_REFILL_METRICS.meta_refill_attempts_total.inc();
957
958 let permit = if let Some(c) = &context.meta_refill_concurrency {
959 Some(c.acquire().await.unwrap())
960 } else {
961 None
962 };
963
964 let now = Instant::now();
965 let res = context.sstable_store.sstable(info, &mut stats).await;
966 stats.discard();
967 GLOBAL_CACHE_REFILL_METRICS
968 .meta_refill_success_duration
969 .observe(now.elapsed().as_secs_f64());
970 drop(permit);
971
972 res
973 })
974 .collect_vec();
975 let holders = try_join_all(tasks).await?;
976 Ok(holders)
977 }
978
979 async fn data_cache_refill(context: &CacheRefillContext, tasks: Vec<DataCacheRefillTask>) {
980 let mut futures = Vec::with_capacity(tasks.len());
981 for task in tasks {
982 context
984 .sstable_store
985 .recent_filter()
986 .insert((task.sst.id, usize::MAX));
987
988 let blocks = task.blks.len();
989 let mut contexts = Vec::with_capacity(blocks);
990 let mut admits = 0;
991
992 let (range_first, _) = task.sst.calculate_block_info(task.blks.start);
993 let (range_last, _) = task.sst.calculate_block_info(task.blks.end - 1);
994 let range = range_first.start..range_last.end;
995
996 let size = range.size().unwrap();
997
998 GLOBAL_CACHE_REFILL_METRICS
999 .data_refill_ideal_bytes
1000 .inc_by(size as _);
1001
1002 for blk in task.blks {
1003 let (range, uncompressed_capacity) = task.sst.calculate_block_info(blk);
1004 let key = SstableBlockIndex {
1005 sst_id: task.sst.id,
1006 block_idx: blk as u64,
1007 };
1008
1009 let mut writer = context.sstable_store.block_cache().storage_writer(key);
1010
1011 if writer.filter(size).is_admitted() {
1012 admits += 1;
1013 }
1014
1015 contexts.push((writer, range, uncompressed_capacity))
1016 }
1017
1018 if admits as f64 / contexts.len() as f64 >= context.config.threshold {
1019 let sstable_store = context.sstable_store.clone();
1020 let context = context.clone();
1021 let future = async move {
1022 GLOBAL_CACHE_REFILL_METRICS.data_refill_attempts_total.inc();
1023
1024 let permit = context.concurrency.acquire().await.unwrap();
1025
1026 GLOBAL_CACHE_REFILL_METRICS.data_refill_started_total.inc();
1027
1028 let timer = GLOBAL_CACHE_REFILL_METRICS
1029 .data_refill_success_duration
1030 .start_timer();
1031
1032 let data = sstable_store
1033 .store()
1034 .read(&sstable_store.get_sst_data_path(task.sst.id), range.clone())
1035 .await?;
1036 let mut apply_disk_cache_futures = vec![];
1037 for (w, r, uc) in contexts {
1038 let offset = r.start - range.start;
1039 let len = r.end - r.start;
1040 let bytes = data.slice(offset..offset + len);
1041 let future = async move {
1042 let value = Box::new(Block::decode(bytes, uc)?);
1043 if let Some(_entry) = w.force().insert(value) {
1045 GLOBAL_CACHE_REFILL_METRICS
1046 .data_refill_success_bytes
1047 .inc_by(len as u64);
1048 GLOBAL_CACHE_REFILL_METRICS
1049 .data_refill_block_success_total
1050 .inc();
1051 }
1052 Ok::<_, HummockError>(())
1053 };
1054 apply_disk_cache_futures.push(future);
1055 }
1056 try_join_all(apply_disk_cache_futures)
1057 .await
1058 .map_err(HummockError::file_cache)?;
1059
1060 drop(permit);
1061 drop(timer);
1062
1063 Ok::<_, HummockError>(())
1064 };
1065 futures.push(future);
1066 }
1067 }
1068
1069 let futures = futures.into_iter().map(|future| async move {
1070 if let Err(e) = future.await {
1071 tracing::error!(error = %e.as_report(), "data cache refill task error");
1072 }
1073 });
1074
1075 join_all(futures).await;
1076 }
1077}
1078
1079#[derive(Debug)]
1080pub struct SstableBlock {
1081 pub sst_obj_id: HummockSstableObjectId,
1082 pub blk_idx: usize,
1083}
1084
1085#[derive(Debug, Hash, PartialEq, Eq)]
1086pub struct SstableUnit {
1087 pub sst_obj_id: HummockSstableObjectId,
1088 pub blks: Range<usize>,
1089}
1090
1091impl Ord for SstableUnit {
1092 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1093 match self.sst_obj_id.cmp(&other.sst_obj_id) {
1094 std::cmp::Ordering::Equal => {}
1095 ord => return ord,
1096 }
1097 match self.blks.start.cmp(&other.blks.start) {
1098 std::cmp::Ordering::Equal => {}
1099 ord => return ord,
1100 }
1101 self.blks.end.cmp(&other.blks.end)
1102 }
1103}
1104
1105impl PartialOrd for SstableUnit {
1106 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1107 Some(self.cmp(other))
1108 }
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113 use std::collections::{HashMap, HashSet};
1114 use std::sync::Arc;
1115 use std::time::Duration;
1116
1117 use bytes::Bytes;
1118 use parking_lot::Mutex;
1119 use risingwave_common::bitmap::Bitmap;
1120 use risingwave_common::config::Role;
1121 use risingwave_common::config::streaming::CacheRefillPolicy;
1122 use risingwave_common::hash::VirtualNode;
1123 use risingwave_common::util::epoch::test_epoch;
1124 use risingwave_hummock_sdk::compaction_group::group_split::split_sst_with_table_ids;
1125 use risingwave_hummock_sdk::key::{FullKey, UserKey, prefix_slice_with_vnode};
1126 use risingwave_hummock_sdk::sstable_info::{SstableInfo, SstableInfoInner};
1127 use risingwave_hummock_sdk::version::HummockVersion;
1128 use risingwave_hummock_sdk::{EpochWithGap, HummockSstableObjectId};
1129 use risingwave_pb::hummock::PbHummockVersion;
1130 use risingwave_pb::id::TableId;
1131 use tokio::sync::mpsc::unbounded_channel;
1132
1133 use super::{
1134 CacheRefillConfig, CacheRefillContext, CacheRefiller, DataCacheRefillTaskGenerator,
1135 SpawnRefillTask, SstDeltaInfo, block_vnode_range, vnode_range_overlaps_bitmap,
1136 };
1137 use crate::hummock::iterator::test_utils::{
1138 iterator_test_table_key_of, mock_sstable_store, mock_sstable_store_with_recent_filter,
1139 };
1140 use crate::hummock::local_version::pinned_version::PinnedVersion;
1141 use crate::hummock::recent_filter::simple::SimpleRecentFilter;
1142 use crate::hummock::test_utils::{
1143 default_builder_opt_for_test, gen_test_sstable_with_table_ids,
1144 };
1145 use crate::hummock::value::HummockValue;
1146 use crate::hummock::{RecentFilter, RecentFilterTrait, SstableStoreRef, TableHolder};
1147
1148 fn test_refill_config(default_policy: CacheRefillPolicy) -> CacheRefillConfig {
1149 CacheRefillConfig {
1150 timeout: Duration::from_secs(1),
1151 data_refill_levels: HashSet::new(),
1152 meta_refill_concurrency: 1,
1153 concurrency: 1,
1154 unit: 1,
1155 threshold: 0.0,
1156 skip_recent_filter: true,
1157 skip_inheritance_filter: true,
1158 table_cache_refill_default_policy: default_policy,
1159 }
1160 }
1161
1162 fn pinned_version_for_test() -> PinnedVersion {
1163 PinnedVersion::new(
1164 HummockVersion::from(PbHummockVersion::default()),
1165 unbounded_channel().0,
1166 )
1167 }
1168
1169 async fn gen_test_sst_with_object_id(
1170 table_id: TableId,
1171 sstable_store: SstableStoreRef,
1172 object_id: u64,
1173 ) -> (TableHolder, SstableInfo) {
1174 gen_test_sstable_with_table_ids(
1175 default_builder_opt_for_test(),
1176 object_id,
1177 (0..2).map(|idx| {
1178 (
1179 FullKey {
1180 user_key: risingwave_hummock_sdk::key::UserKey::for_test(
1181 table_id,
1182 iterator_test_table_key_of(idx),
1183 ),
1184 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
1185 },
1186 HummockValue::put(vec![idx as u8]),
1187 )
1188 }),
1189 sstable_store,
1190 vec![table_id.as_raw_id()],
1191 )
1192 .await
1193 }
1194
1195 struct DataRefillGeneratorTestFixture {
1196 table_id: TableId,
1197 sstable_store: SstableStoreRef,
1198 sst: TableHolder,
1199 sst_info: SstableInfo,
1200 deleted_sst_object_id: HummockSstableObjectId,
1201 }
1202
1203 impl DataRefillGeneratorTestFixture {
1204 async fn new(
1205 recent_filter: Option<Arc<RecentFilter<(HummockSstableObjectId, usize)>>>,
1206 ) -> Self {
1207 let table_id = TableId::from(233);
1208 let sstable_store = match recent_filter {
1209 Some(recent_filter) => mock_sstable_store_with_recent_filter(recent_filter).await,
1210 None => mock_sstable_store().await,
1211 };
1212 let (sst, sst_info) =
1213 gen_test_sst_with_object_id(table_id, sstable_store.clone(), 1).await;
1214 Self {
1215 table_id,
1216 sstable_store,
1217 sst,
1218 sst_info,
1219 deleted_sst_object_id: 2330.into(),
1220 }
1221 }
1222
1223 fn context(
1224 &self,
1225 policy: CacheRefillPolicy,
1226 streaming_vnode_bitmap: Option<Bitmap>,
1227 serving_vnode_bitmap: Option<Bitmap>,
1228 configure: impl FnOnce(&mut CacheRefillConfig),
1229 ) -> CacheRefillContext {
1230 let mut config = test_refill_config(CacheRefillPolicy::Enabled);
1231 config.data_refill_levels.insert(0);
1232 configure(&mut config);
1233 CacheRefillContext {
1234 config: Arc::new(config),
1235 meta_refill_concurrency: None,
1236 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
1237 sstable_store: self.sstable_store.clone(),
1238 table_cache_refill_context_map: Arc::new(HashMap::from([(
1239 self.table_id,
1240 super::TableCacheRefillContext {
1241 streaming_vnode_bitmap,
1242 serving_vnode_bitmap,
1243 policy,
1244 },
1245 )])),
1246 }
1247 }
1248
1249 fn normal_delta(
1250 &self,
1251 insert_sst_level: u32,
1252 deleted_sst_object_id: HummockSstableObjectId,
1253 ) -> SstDeltaInfo {
1254 SstDeltaInfo {
1255 insert_sst_infos: vec![self.sst_info.clone()],
1256 delete_sst_object_ids: vec![deleted_sst_object_id],
1257 insert_sst_level,
1258 }
1259 }
1260
1261 fn normal_l0_delta(&self) -> SstDeltaInfo {
1262 self.normal_delta(0, self.deleted_sst_object_id)
1263 }
1264
1265 fn l0_insert_only_delta(&self) -> SstDeltaInfo {
1266 SstDeltaInfo {
1267 insert_sst_infos: vec![self.sst_info.clone()],
1268 delete_sst_object_ids: vec![],
1269 insert_sst_level: 0,
1270 }
1271 }
1272
1273 async fn generate(
1274 &self,
1275 context: &CacheRefillContext,
1276 delta: &SstDeltaInfo,
1277 ) -> Vec<super::DataCacheRefillTask> {
1278 let generator = DataCacheRefillTaskGenerator {
1279 context,
1280 delta,
1281 ssts: std::slice::from_ref(&self.sst),
1282 };
1283 let tasks = generator.generate_unfiltered_tasks();
1284 generator.filter_by_inheritance_if_needed(tasks).await
1285 }
1286 }
1287
1288 #[tokio::test]
1289 async fn test_table_cache_refill_contexts_by_role_and_policy() {
1290 struct Case {
1291 name: &'static str,
1292 role: Role,
1293 default_policy: CacheRefillPolicy,
1294 policy: Option<CacheRefillPolicy>,
1295 has_streaming_vnodes: bool,
1296 has_serving_vnodes: bool,
1297 expected: Option<(CacheRefillPolicy, bool, bool)>,
1298 }
1299
1300 let cases = [
1301 Case {
1302 name: "streaming role uses streaming side of Both",
1303 role: Role::Streaming,
1304 default_policy: CacheRefillPolicy::Disabled,
1305 policy: Some(CacheRefillPolicy::Both),
1306 has_streaming_vnodes: true,
1307 has_serving_vnodes: true,
1308 expected: Some((CacheRefillPolicy::Both, true, false)),
1309 },
1310 Case {
1311 name: "serving role uses serving side of Both",
1312 role: Role::Serving,
1313 default_policy: CacheRefillPolicy::Disabled,
1314 policy: Some(CacheRefillPolicy::Both),
1315 has_streaming_vnodes: true,
1316 has_serving_vnodes: true,
1317 expected: Some((CacheRefillPolicy::Both, false, true)),
1318 },
1319 Case {
1320 name: "both role keeps both sides",
1321 role: Role::Both,
1322 default_policy: CacheRefillPolicy::Disabled,
1323 policy: Some(CacheRefillPolicy::Both),
1324 has_streaming_vnodes: true,
1325 has_serving_vnodes: true,
1326 expected: Some((CacheRefillPolicy::Both, true, true)),
1327 },
1328 Case {
1329 name: "both role keeps streaming-only ownership",
1330 role: Role::Both,
1331 default_policy: CacheRefillPolicy::Disabled,
1332 policy: Some(CacheRefillPolicy::Both),
1333 has_streaming_vnodes: true,
1334 has_serving_vnodes: false,
1335 expected: Some((CacheRefillPolicy::Both, true, false)),
1336 },
1337 Case {
1338 name: "streaming scope without ownership has no usable bitmap",
1339 role: Role::Streaming,
1340 default_policy: CacheRefillPolicy::Disabled,
1341 policy: Some(CacheRefillPolicy::Streaming),
1342 has_streaming_vnodes: false,
1343 has_serving_vnodes: false,
1344 expected: Some((CacheRefillPolicy::Streaming, false, false)),
1345 },
1346 Case {
1347 name: "pure serving worker excludes unmapped table",
1348 role: Role::Serving,
1349 default_policy: CacheRefillPolicy::Disabled,
1350 policy: Some(CacheRefillPolicy::Serving),
1351 has_streaming_vnodes: true,
1352 has_serving_vnodes: false,
1353 expected: None,
1354 },
1355 Case {
1356 name: "default Enabled retains serving ownership",
1357 role: Role::Serving,
1358 default_policy: CacheRefillPolicy::Enabled,
1359 policy: None,
1360 has_streaming_vnodes: false,
1361 has_serving_vnodes: true,
1362 expected: Some((CacheRefillPolicy::Enabled, false, true)),
1363 },
1364 Case {
1365 name: "explicit policy overrides default",
1366 role: Role::Serving,
1367 default_policy: CacheRefillPolicy::Enabled,
1368 policy: Some(CacheRefillPolicy::Disabled),
1369 has_streaming_vnodes: false,
1370 has_serving_vnodes: true,
1371 expected: Some((CacheRefillPolicy::Disabled, false, false)),
1372 },
1373 ];
1374
1375 let table_id = TableId::from(233);
1376 let streaming_vnodes = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1, 3]);
1377 let serving_vnodes = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [2, 4]);
1378 let sstable_store = mock_sstable_store().await;
1379 for case in cases {
1380 let mut refiller = CacheRefiller::new(
1381 case.role,
1382 test_refill_config(case.default_policy),
1383 sstable_store.clone(),
1384 CacheRefiller::default_spawn_refill_task(),
1385 );
1386 if let Some(policy) = case.policy {
1387 refiller.replace_table_cache_refill_policies(HashMap::from([(table_id, policy)]));
1388 }
1389 if case.has_streaming_vnodes {
1390 refiller.update_streaming_table_vnodes(table_id, Some(streaming_vnodes.clone()));
1391 }
1392 if case.has_serving_vnodes {
1393 refiller.replace_serving_table_vnode_mapping(HashMap::from([(
1394 table_id,
1395 serving_vnodes.clone(),
1396 )]));
1397 }
1398
1399 let contexts = refiller.table_cache_refill_contexts([table_id]);
1400 let actual = contexts.get(&table_id).map(|context| {
1401 (
1402 context.policy,
1403 context.streaming_vnode_bitmap.as_ref(),
1404 context.serving_vnode_bitmap.as_ref(),
1405 )
1406 });
1407 let expected = case.expected.map(|(policy, streaming, serving)| {
1408 (
1409 policy,
1410 streaming.then_some(&streaming_vnodes),
1411 serving.then_some(&serving_vnodes),
1412 )
1413 });
1414 assert_eq!(actual, expected, "{}", case.name);
1415 }
1416 }
1417
1418 #[tokio::test]
1419 async fn test_refill_task_captures_runtime_context_snapshot() {
1420 let table_id = TableId::from(233);
1421 let old_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
1422 let new_vnodes = Bitmap::from_range(VirtualNode::COUNT_FOR_TEST, 0..8);
1423 let captured_context = Arc::new(Mutex::new(None::<CacheRefillContext>));
1424 let captured_context_clone = captured_context.clone();
1425 let spawn_refill_task: SpawnRefillTask = Arc::new(move |_, context, _, _| {
1426 *captured_context_clone.lock() = Some(context);
1427 tokio::spawn(async {})
1428 });
1429 let mut refiller = CacheRefiller::new(
1430 Role::Serving,
1431 test_refill_config(CacheRefillPolicy::Enabled),
1432 mock_sstable_store().await,
1433 spawn_refill_task,
1434 );
1435
1436 refiller.replace_table_cache_refill_policies(HashMap::from([(
1437 table_id,
1438 CacheRefillPolicy::Serving,
1439 )]));
1440 refiller
1441 .replace_serving_table_vnode_mapping(HashMap::from([(table_id, old_vnodes.clone())]));
1442
1443 refiller.start_cache_refill(
1444 vec![SstDeltaInfo {
1445 insert_sst_infos: vec![SstableInfo::from(SstableInfoInner {
1446 table_ids: vec![table_id],
1447 ..Default::default()
1448 })],
1449 ..Default::default()
1450 }],
1451 pinned_version_for_test(),
1452 pinned_version_for_test(),
1453 );
1454 refiller.replace_table_cache_refill_policies(HashMap::from([(
1455 table_id,
1456 CacheRefillPolicy::Disabled,
1457 )]));
1458 refiller.replace_serving_table_vnode_mapping(HashMap::from([(table_id, new_vnodes)]));
1459
1460 let captured_context = captured_context.lock();
1461 let context = captured_context
1462 .as_ref()
1463 .unwrap()
1464 .table_cache_refill_context_map
1465 .get(&table_id)
1466 .unwrap();
1467 assert_eq!(context.policy, CacheRefillPolicy::Serving);
1468 assert_eq!(context.serving_vnode_bitmap.as_ref(), Some(&old_vnodes));
1469 }
1470
1471 #[tokio::test]
1472 async fn test_cache_refill_prunes_whole_ssts_before_meta_load() {
1473 let streaming_table = TableId::from(1);
1474 let serving_table = TableId::from(2);
1475 let disabled_table = TableId::from(3);
1476 let internal_table = TableId::from(4);
1477 let fallback_table = TableId::from(5);
1478 let serving_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
1479 let sstable_store = mock_sstable_store().await;
1480 let sst_info = |table_ids: Vec<TableId>| {
1481 SstableInfo::from(SstableInfoInner {
1482 table_ids,
1483 ..Default::default()
1484 })
1485 };
1486 let capture_pruned_table_ids = |role,
1487 default_policy,
1488 policies: HashMap<TableId, CacheRefillPolicy>,
1489 streaming_table_vnodes: HashMap<TableId, Bitmap>,
1490 serving_table_vnodes: HashMap<TableId, Bitmap>,
1491 delta| {
1492 let captured_deltas = Arc::new(Mutex::new(None::<Vec<SstDeltaInfo>>));
1493 let captured_deltas_clone = captured_deltas.clone();
1494 let spawn_refill_task: SpawnRefillTask = Arc::new(move |deltas, _, _, _| {
1495 *captured_deltas_clone.lock() = Some(deltas);
1496 tokio::spawn(async {})
1497 });
1498 let mut refiller = CacheRefiller::new(
1499 role,
1500 test_refill_config(default_policy),
1501 sstable_store.clone(),
1502 spawn_refill_task,
1503 );
1504 refiller.replace_table_cache_refill_policies(policies);
1505 for (table_id, vnodes) in streaming_table_vnodes {
1506 refiller.update_streaming_table_vnodes(table_id, Some(vnodes));
1507 }
1508 refiller.replace_serving_table_vnode_mapping(serving_table_vnodes);
1509 refiller.start_cache_refill(
1510 vec![delta],
1511 pinned_version_for_test(),
1512 pinned_version_for_test(),
1513 );
1514 captured_deltas
1515 .lock()
1516 .take()
1517 .unwrap()
1518 .pop()
1519 .unwrap()
1520 .insert_sst_infos
1521 .into_iter()
1522 .map(|sst| sst.table_ids.clone())
1523 .collect::<Vec<_>>()
1524 };
1525
1526 let normal_delta = |insert_sst_infos| SstDeltaInfo {
1527 insert_sst_infos,
1528 delete_sst_object_ids: vec![1.into()],
1529 insert_sst_level: 1,
1530 };
1531 let insert_only_delta = |insert_sst_infos| SstDeltaInfo {
1532 insert_sst_infos,
1533 delete_sst_object_ids: vec![],
1534 insert_sst_level: 0,
1535 };
1536
1537 assert_eq!(
1538 capture_pruned_table_ids(
1539 Role::Both,
1540 CacheRefillPolicy::Disabled,
1541 HashMap::from([
1542 (disabled_table, CacheRefillPolicy::Disabled),
1543 (streaming_table, CacheRefillPolicy::Enabled),
1544 ]),
1545 HashMap::new(),
1546 HashMap::new(),
1547 normal_delta(vec![
1548 sst_info(vec![disabled_table]),
1549 sst_info(vec![streaming_table]),
1550 ]),
1551 ),
1552 vec![vec![streaming_table]],
1553 );
1554
1555 assert_eq!(
1556 capture_pruned_table_ids(
1557 Role::Both,
1558 CacheRefillPolicy::Disabled,
1559 HashMap::from([
1560 (streaming_table, CacheRefillPolicy::Streaming),
1561 (internal_table, CacheRefillPolicy::Serving),
1562 ]),
1563 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1564 HashMap::new(),
1565 normal_delta(vec![
1566 sst_info(vec![streaming_table]),
1567 sst_info(vec![internal_table]),
1568 ]),
1569 ),
1570 vec![vec![streaming_table]],
1571 );
1572
1573 assert_eq!(
1574 capture_pruned_table_ids(
1575 Role::Both,
1576 CacheRefillPolicy::Disabled,
1577 HashMap::from([
1578 (streaming_table, CacheRefillPolicy::Streaming),
1579 (serving_table, CacheRefillPolicy::Serving),
1580 (internal_table, CacheRefillPolicy::Serving),
1581 ]),
1582 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1583 HashMap::from([(serving_table, serving_vnodes.clone())]),
1584 insert_only_delta(vec![
1585 sst_info(vec![streaming_table]),
1586 sst_info(vec![serving_table]),
1587 sst_info(vec![internal_table]),
1588 ]),
1589 ),
1590 vec![vec![serving_table]],
1591 );
1592
1593 assert_eq!(
1594 capture_pruned_table_ids(
1595 Role::Serving,
1596 CacheRefillPolicy::Disabled,
1597 HashMap::from([
1598 (streaming_table, CacheRefillPolicy::Streaming),
1599 (serving_table, CacheRefillPolicy::Serving),
1600 ]),
1601 HashMap::new(),
1602 HashMap::from([(serving_table, serving_vnodes.clone())]),
1603 normal_delta(vec![
1604 sst_info(vec![streaming_table]),
1605 sst_info(vec![serving_table]),
1606 ]),
1607 ),
1608 vec![vec![serving_table]],
1609 );
1610
1611 assert_eq!(
1612 capture_pruned_table_ids(
1613 Role::Serving,
1614 CacheRefillPolicy::Disabled,
1615 HashMap::from([
1616 (streaming_table, CacheRefillPolicy::Enabled),
1617 (serving_table, CacheRefillPolicy::Enabled),
1618 ]),
1619 HashMap::new(),
1620 HashMap::from([(serving_table, serving_vnodes.clone())]),
1621 normal_delta(vec![
1622 sst_info(vec![streaming_table]),
1623 sst_info(vec![serving_table]),
1624 sst_info(vec![streaming_table, serving_table]),
1625 ]),
1626 ),
1627 vec![
1628 vec![streaming_table],
1629 vec![serving_table],
1630 vec![streaming_table, serving_table],
1631 ],
1632 );
1633
1634 assert_eq!(
1635 capture_pruned_table_ids(
1636 Role::Both,
1637 CacheRefillPolicy::Disabled,
1638 HashMap::from([
1639 (streaming_table, CacheRefillPolicy::Both),
1640 (serving_table, CacheRefillPolicy::Both),
1641 ]),
1642 HashMap::new(),
1643 HashMap::new(),
1644 normal_delta(vec![
1645 sst_info(vec![streaming_table]),
1646 sst_info(vec![serving_table]),
1647 ]),
1648 ),
1649 Vec::<Vec<TableId>>::new(),
1650 );
1651
1652 assert_eq!(
1653 capture_pruned_table_ids(
1654 Role::Both,
1655 CacheRefillPolicy::Disabled,
1656 HashMap::from([
1657 (streaming_table, CacheRefillPolicy::Both),
1658 (serving_table, CacheRefillPolicy::Both),
1659 ]),
1660 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1661 HashMap::new(),
1662 normal_delta(vec![
1663 sst_info(vec![streaming_table]),
1664 sst_info(vec![serving_table]),
1665 ]),
1666 ),
1667 vec![vec![streaming_table]],
1668 );
1669
1670 assert_eq!(
1671 capture_pruned_table_ids(
1672 Role::Both,
1673 CacheRefillPolicy::Disabled,
1674 HashMap::from([
1675 (streaming_table, CacheRefillPolicy::Both),
1676 (serving_table, CacheRefillPolicy::Both),
1677 ]),
1678 HashMap::new(),
1679 HashMap::from([(serving_table, serving_vnodes.clone())]),
1680 normal_delta(vec![
1681 sst_info(vec![streaming_table]),
1682 sst_info(vec![serving_table]),
1683 ]),
1684 ),
1685 vec![vec![serving_table]],
1686 );
1687
1688 assert_eq!(
1689 capture_pruned_table_ids(
1690 Role::Streaming,
1691 CacheRefillPolicy::Disabled,
1692 HashMap::from([
1693 (streaming_table, CacheRefillPolicy::Streaming),
1694 (serving_table, CacheRefillPolicy::Serving),
1695 ]),
1696 HashMap::new(),
1697 HashMap::new(),
1698 normal_delta(vec![
1699 sst_info(vec![streaming_table]),
1700 sst_info(vec![serving_table]),
1701 ]),
1702 ),
1703 Vec::<Vec<TableId>>::new(),
1704 );
1705
1706 assert_eq!(
1707 capture_pruned_table_ids(
1708 Role::Streaming,
1709 CacheRefillPolicy::Disabled,
1710 HashMap::from([
1711 (streaming_table, CacheRefillPolicy::Streaming),
1712 (serving_table, CacheRefillPolicy::Serving),
1713 ]),
1714 HashMap::new(),
1715 HashMap::new(),
1716 insert_only_delta(vec![
1717 sst_info(vec![streaming_table]),
1718 sst_info(vec![serving_table]),
1719 ]),
1720 ),
1721 Vec::<Vec<TableId>>::new(),
1722 );
1723
1724 assert_eq!(
1725 capture_pruned_table_ids(
1726 Role::Both,
1727 CacheRefillPolicy::Enabled,
1728 HashMap::from([(disabled_table, CacheRefillPolicy::Disabled)]),
1729 HashMap::new(),
1730 HashMap::new(),
1731 normal_delta(vec![
1732 sst_info(vec![disabled_table]),
1733 sst_info(vec![fallback_table]),
1734 sst_info(vec![disabled_table, fallback_table]),
1735 ]),
1736 ),
1737 vec![vec![fallback_table], vec![disabled_table, fallback_table]],
1738 );
1739 }
1740
1741 #[tokio::test]
1742 async fn test_normal_refill_applies_policy_and_vnode_ownership() {
1743 let fixture = DataRefillGeneratorTestFixture::new(None).await;
1744 let delta = fixture.normal_l0_delta();
1745 let owned = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [0]);
1746 let unowned = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1]);
1747 let cases = vec![
1748 ("Enabled", CacheRefillPolicy::Enabled, None, None, true),
1749 (
1750 "Disabled",
1751 CacheRefillPolicy::Disabled,
1752 Some(owned.clone()),
1753 Some(owned.clone()),
1754 false,
1755 ),
1756 (
1757 "Streaming match",
1758 CacheRefillPolicy::Streaming,
1759 Some(owned.clone()),
1760 None,
1761 true,
1762 ),
1763 (
1764 "Streaming miss",
1765 CacheRefillPolicy::Streaming,
1766 Some(unowned.clone()),
1767 None,
1768 false,
1769 ),
1770 (
1771 "Streaming ownership missing",
1772 CacheRefillPolicy::Streaming,
1773 None,
1774 None,
1775 false,
1776 ),
1777 (
1778 "Serving match",
1779 CacheRefillPolicy::Serving,
1780 None,
1781 Some(owned.clone()),
1782 true,
1783 ),
1784 (
1785 "Serving miss",
1786 CacheRefillPolicy::Serving,
1787 None,
1788 Some(unowned.clone()),
1789 false,
1790 ),
1791 (
1792 "Serving ownership missing",
1793 CacheRefillPolicy::Serving,
1794 None,
1795 None,
1796 false,
1797 ),
1798 (
1799 "Both streaming match",
1800 CacheRefillPolicy::Both,
1801 Some(owned.clone()),
1802 Some(unowned.clone()),
1803 true,
1804 ),
1805 (
1806 "Both serving match",
1807 CacheRefillPolicy::Both,
1808 Some(unowned.clone()),
1809 Some(owned),
1810 true,
1811 ),
1812 (
1813 "Both misses",
1814 CacheRefillPolicy::Both,
1815 Some(unowned.clone()),
1816 Some(unowned),
1817 false,
1818 ),
1819 ];
1820
1821 for (name, policy, streaming_vnodes, serving_vnodes, should_refill) in cases {
1822 let context = fixture.context(policy, streaming_vnodes, serving_vnodes, |_| {});
1823 assert_eq!(
1824 !fixture.generate(&context, &delta).await.is_empty(),
1825 should_refill,
1826 "{name}"
1827 );
1828 }
1829 }
1830
1831 #[tokio::test]
1832 async fn test_normal_refill_applies_recent_and_inheritance_filters() {
1833 let recent_filter = SimpleRecentFilter::new(3, Duration::from_secs(60));
1834 let fixture =
1835 DataRefillGeneratorTestFixture::new(Some(Arc::new(recent_filter.clone().into()))).await;
1836 let delta = fixture.normal_l0_delta();
1837
1838 let serving_context = fixture.context(
1839 CacheRefillPolicy::Serving,
1840 None,
1841 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1842 |config| {
1843 config.skip_recent_filter = false;
1844 },
1845 );
1846 assert!(
1847 fixture.generate(&serving_context, &delta).await.is_empty(),
1848 "explicit Serving policy is not an implicit skip_recent_filter"
1849 );
1850
1851 recent_filter.insert((fixture.deleted_sst_object_id, usize::MAX));
1852 assert!(
1853 !fixture.generate(&serving_context, &delta).await.is_empty(),
1854 "explicit Serving policy should produce tasks after recent admission hits"
1855 );
1856
1857 let (_, parent_sst_info) =
1858 gen_test_sst_with_object_id(fixture.table_id, fixture.sstable_store.clone(), 2).await;
1859 let non_l0_delta = fixture.normal_delta(1, parent_sst_info.object_id);
1860 let non_l0_context = fixture.context(CacheRefillPolicy::Enabled, None, None, |config| {
1861 config.data_refill_levels.insert(1);
1862 config.skip_recent_filter = false;
1863 config.skip_inheritance_filter = false;
1864 });
1865
1866 recent_filter.insert((parent_sst_info.object_id, usize::MAX));
1867 let generator = DataCacheRefillTaskGenerator {
1868 context: &non_l0_context,
1869 delta: &non_l0_delta,
1870 ssts: std::slice::from_ref(&fixture.sst),
1871 };
1872 let unfiltered_tasks = generator.generate_unfiltered_tasks();
1873 assert_eq!(
1874 unfiltered_tasks
1875 .iter()
1876 .map(|task| task.blks.len())
1877 .sum::<usize>(),
1878 fixture.sst.block_count(),
1879 "recent-admitted blocks should reach the inheritance stage"
1880 );
1881 assert!(
1882 generator
1883 .filter_by_inheritance_if_needed(unfiltered_tasks)
1884 .await
1885 .is_empty(),
1886 "after recent admission, parent block recent miss should filter non-L0 normal refill"
1887 );
1888
1889 recent_filter.insert((parent_sst_info.object_id, 0));
1890 let tasks = fixture.generate(&non_l0_context, &non_l0_delta).await;
1891 assert_eq!(tasks.len(), 1);
1892 assert_eq!(tasks[0].sst.id, fixture.sst.id);
1893 assert_eq!(tasks[0].blks, 0..1);
1894 }
1895
1896 #[tokio::test]
1897 async fn test_l0_insert_only_refill_policy_uses_serving_ownership() {
1898 let fixture = DataRefillGeneratorTestFixture::new(None).await;
1899 let delta = fixture.l0_insert_only_delta();
1900 let cases = [
1901 (
1902 "Enabled + serving overlap",
1903 CacheRefillPolicy::Enabled,
1904 None,
1905 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1906 true,
1907 ),
1908 (
1909 "Enabled without serving ownership",
1910 CacheRefillPolicy::Enabled,
1911 None,
1912 None,
1913 false,
1914 ),
1915 (
1916 "Serving + serving overlap",
1917 CacheRefillPolicy::Serving,
1918 None,
1919 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1920 true,
1921 ),
1922 (
1923 "Streaming + streaming overlap",
1924 CacheRefillPolicy::Streaming,
1925 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1926 None,
1927 false,
1928 ),
1929 (
1930 "Both + streaming overlap + serving non-overlap",
1931 CacheRefillPolicy::Both,
1932 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1933 Some(Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1])),
1934 false,
1935 ),
1936 (
1937 "Both + serving overlap",
1938 CacheRefillPolicy::Both,
1939 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1940 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1941 true,
1942 ),
1943 (
1944 "Disabled + serving overlap",
1945 CacheRefillPolicy::Disabled,
1946 None,
1947 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1948 false,
1949 ),
1950 ];
1951
1952 for (name, policy, streaming_vnodes, serving_vnodes, should_refill) in cases {
1953 let context = fixture.context(policy, streaming_vnodes, serving_vnodes, |config| {
1954 config.skip_recent_filter = false;
1955 config.skip_inheritance_filter = false;
1956 });
1957 assert_eq!(
1958 !fixture.generate(&context, &delta).await.is_empty(),
1959 should_refill,
1960 "{name}"
1961 );
1962 }
1963 }
1964
1965 #[tokio::test]
1966 async fn test_refill_units_do_not_cross_table_projection_boundaries() {
1967 let table_a = TableId::from(233);
1968 let table_b = TableId::from(234);
1969 let sstable_store = mock_sstable_store().await;
1970 let (sst, sst_info) = gen_test_sstable_with_table_ids(
1971 default_builder_opt_for_test(),
1972 1,
1973 [table_a, table_b].into_iter().map(|table_id| {
1974 (
1975 FullKey {
1976 user_key: UserKey::for_test(table_id, iterator_test_table_key_of(0)),
1977 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
1978 },
1979 HummockValue::put(b"value".to_vec()),
1980 )
1981 }),
1982 sstable_store.clone(),
1983 vec![table_a.as_raw_id(), table_b.as_raw_id()],
1984 )
1985 .await;
1986 assert_eq!(sst.block_count(), 2, "table switch must form a new block");
1987
1988 let mut next_sst_id = 100.into();
1989 let (table_a_projection, table_b_projection) =
1990 split_sst_with_table_ids(&sst_info, &mut next_sst_id, 1, 1, vec![table_b]);
1991 assert_eq!(table_a_projection.object_id, sst_info.object_id);
1992 assert_eq!(table_b_projection.object_id, sst_info.object_id);
1993 assert_ne!(table_a_projection.sst_id, table_b_projection.sst_id);
1994 assert_eq!(table_a_projection.table_ids, vec![table_a]);
1995 assert_eq!(table_b_projection.table_ids, vec![table_b]);
1996
1997 let deltas = [table_a_projection, table_b_projection].map(|projection| SstDeltaInfo {
1998 insert_sst_infos: vec![projection],
1999 delete_sst_object_ids: vec![],
2000 insert_sst_level: 0,
2001 });
2002 let normal_deltas = deltas.clone().map(|mut delta| {
2003 delta.delete_sst_object_ids = vec![999.into()];
2006 delta
2007 });
2008 let serving_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
2009 let table_cache_refill_context_map = Arc::new(
2010 [table_a, table_b]
2011 .into_iter()
2012 .map(|table_id| {
2013 (
2014 table_id,
2015 super::TableCacheRefillContext {
2016 streaming_vnode_bitmap: None,
2017 serving_vnode_bitmap: Some(serving_vnodes.clone()),
2018 policy: CacheRefillPolicy::Serving,
2019 },
2020 )
2021 })
2022 .collect::<super::TableCacheRefillContextMap>(),
2023 );
2024 let make_context = |unit| {
2025 let mut config = test_refill_config(CacheRefillPolicy::Disabled);
2026 config.data_refill_levels.insert(0);
2027 config.unit = unit;
2028 CacheRefillContext {
2029 config: Arc::new(config),
2030 meta_refill_concurrency: None,
2031 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
2032 sstable_store: sstable_store.clone(),
2033 table_cache_refill_context_map: table_cache_refill_context_map.clone(),
2034 }
2035 };
2036 let generated_tasks = |context: &CacheRefillContext| {
2037 deltas
2038 .iter()
2039 .map(|delta| {
2040 DataCacheRefillTaskGenerator {
2041 context,
2042 delta,
2043 ssts: std::slice::from_ref(&sst),
2044 }
2045 .generate_unfiltered_tasks()
2046 })
2047 .collect::<Vec<_>>()
2048 };
2049 let generated_ranges = |context: &CacheRefillContext| {
2050 generated_tasks(context)
2051 .into_iter()
2052 .map(|tasks| tasks.into_iter().map(|task| task.blks).collect::<Vec<_>>())
2053 .collect::<Vec<_>>()
2054 };
2055
2056 assert_eq!(
2057 generated_ranges(&make_context(1)),
2058 vec![vec![0..1], vec![1..2]],
2059 "each logical projection must select only its own block"
2060 );
2061
2062 let wide_unit_context = make_context(2);
2063 assert_eq!(
2064 generated_ranges(&wide_unit_context),
2065 vec![vec![0..1], vec![1..2]],
2066 "units are clipped at table boundaries even when unit is larger than a table run"
2067 );
2068
2069 let normal_ranges = normal_deltas
2070 .iter()
2071 .map(|delta| {
2072 DataCacheRefillTaskGenerator {
2073 context: &wide_unit_context,
2074 delta,
2075 ssts: std::slice::from_ref(&sst),
2076 }
2077 .generate_unfiltered_tasks()
2078 .into_iter()
2079 .map(|task| task.blks)
2080 .collect::<Vec<_>>()
2081 })
2082 .collect::<Vec<_>>();
2083 assert_eq!(
2084 normal_ranges,
2085 vec![vec![0..1], vec![1..2]],
2086 "normal refill uses the same table-boundary geometry"
2087 );
2088
2089 for task in generated_tasks(&wide_unit_context).into_iter().flatten() {
2090 assert!(task.blks.len() <= wide_unit_context.config.unit);
2091 assert_eq!(
2092 task.sst.meta.block_metas[task.blks.start].table_id(),
2093 task.sst.meta.block_metas[task.blks.end - 1].table_id(),
2094 "a refill unit must not cross a table boundary"
2095 );
2096 }
2097 }
2098
2099 #[tokio::test]
2100 async fn test_scoped_refill_handles_multi_table_vnode_boundary() {
2101 let table_a = TableId::from(233);
2102 let table_b = TableId::from(234);
2103 let vnode_a = VirtualNode::COUNT_FOR_TEST - 1;
2104 let sstable_store = mock_sstable_store().await;
2105 let (sst, sst_info) = gen_test_sstable_with_table_ids(
2106 default_builder_opt_for_test(),
2107 1,
2108 [
2109 (
2110 FullKey {
2111 user_key: UserKey::for_test(
2112 table_a,
2113 prefix_slice_with_vnode(VirtualNode::from_index(vnode_a), b"table_a"),
2114 ),
2115 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2116 },
2117 HummockValue::put(Bytes::from_static(b"a")),
2118 ),
2119 (
2120 FullKey {
2121 user_key: UserKey::for_test(
2122 table_b,
2123 prefix_slice_with_vnode(VirtualNode::ZERO, b"table_b"),
2124 ),
2125 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2126 },
2127 HummockValue::put(Bytes::from_static(b"b")),
2128 ),
2129 ]
2130 .into_iter(),
2131 sstable_store.clone(),
2132 vec![table_a.as_raw_id(), table_b.as_raw_id()],
2133 )
2134 .await;
2135 assert_eq!(sst.block_count(), 2, "table switch must form a new block");
2136
2137 let generate = |streaming_vnodes| {
2138 let sstable_store = sstable_store.clone();
2139 let sst = sst.clone();
2140 let sst_info = sst_info.clone();
2141 let mut config = test_refill_config(CacheRefillPolicy::Streaming);
2142 config.data_refill_levels.insert(0);
2143 let context = CacheRefillContext {
2144 config: Arc::new(config),
2145 meta_refill_concurrency: None,
2146 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
2147 sstable_store,
2148 table_cache_refill_context_map: Arc::new(HashMap::from([(
2149 table_a,
2150 super::TableCacheRefillContext {
2151 streaming_vnode_bitmap: Some(streaming_vnodes),
2152 serving_vnode_bitmap: None,
2153 policy: CacheRefillPolicy::Streaming,
2154 },
2155 )])),
2156 };
2157 async move {
2158 let generator = DataCacheRefillTaskGenerator {
2159 context: &context,
2160 delta: &SstDeltaInfo {
2161 insert_sst_infos: vec![sst_info.clone()],
2162 delete_sst_object_ids: vec![2330.into()],
2163 insert_sst_level: 0,
2164 },
2165 ssts: std::slice::from_ref(&sst),
2166 };
2167 let tasks = generator.generate_unfiltered_tasks();
2168 generator.filter_by_inheritance_if_needed(tasks).await
2169 }
2170 };
2171
2172 let matching_tasks =
2173 generate(Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [vnode_a])).await;
2174 assert_eq!(matching_tasks.len(), 1);
2175 assert_eq!(matching_tasks[0].blks, 0..1);
2176
2177 let non_matching_tasks = generate(Bitmap::from_indices(
2178 VirtualNode::COUNT_FOR_TEST,
2179 [VirtualNode::ZERO.to_index()],
2180 ))
2181 .await;
2182 assert!(non_matching_tasks.is_empty());
2183 }
2184
2185 #[tokio::test]
2186 async fn test_block_vnode_range_handles_vnode_only_block_boundaries() {
2187 let table_id = TableId::from(233);
2188 let vnode = VirtualNode::ZERO;
2189 let sstable_store = mock_sstable_store().await;
2190 let mut builder_options = default_builder_opt_for_test();
2191 builder_options.block_capacity = 1;
2192 let (sst, _) = gen_test_sstable_with_table_ids(
2193 builder_options,
2194 1,
2195 [234, 233].into_iter().map(|epoch| {
2196 (
2197 FullKey {
2198 user_key: UserKey::for_test(table_id, prefix_slice_with_vnode(vnode, b"")),
2199 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(epoch)),
2200 },
2201 HummockValue::put(Bytes::from_static(b"value")),
2202 )
2203 }),
2204 sstable_store.clone(),
2205 vec![table_id.as_raw_id()],
2206 )
2207 .await;
2208 assert_eq!(sst.block_count(), 2);
2209 let expected = (vnode.to_index(), vnode.to_index() + 1);
2210 assert_eq!(block_vnode_range(&sst, 0), expected);
2211 assert_eq!(block_vnode_range(&sst, 1), expected);
2212 }
2213
2214 #[tokio::test]
2215 async fn test_block_vnode_range_fails_open_for_shortened_meta_keys() {
2216 let table_id = TableId::from(233);
2217 let sstable_store = mock_sstable_store().await;
2218 let mut builder_options = default_builder_opt_for_test();
2219 builder_options.block_capacity = 1;
2220 builder_options.shorten_block_meta_key_threshold = Some(0);
2221 let (sst, _) = gen_test_sstable_with_table_ids(
2222 builder_options,
2223 1,
2224 [255, 256].into_iter().map(|vnode| {
2225 (
2226 FullKey {
2227 user_key: UserKey::for_test(
2228 table_id,
2229 prefix_slice_with_vnode(VirtualNode::from_index(vnode), b"long-key"),
2230 ),
2231 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2232 },
2233 HummockValue::put(Bytes::from_static(b"value")),
2234 )
2235 }),
2236 sstable_store,
2237 vec![table_id.as_raw_id()],
2238 )
2239 .await;
2240 assert_eq!(sst.block_count(), 2);
2241 assert!(
2242 FullKey::decode(&sst.meta.block_metas[1].smallest_key)
2243 .user_key
2244 .table_key
2245 .as_ref()
2246 .len()
2247 < VirtualNode::SIZE
2248 );
2249 let full_range = (0, VirtualNode::MAX_REPRESENTABLE.to_index() + 1);
2250 assert_eq!(block_vnode_range(&sst, 0), full_range);
2251 assert_eq!(block_vnode_range(&sst, 1), full_range);
2252 }
2253
2254 #[test]
2255 fn test_vnode_range_overlaps_bitmap_uses_right_exclusive_end() {
2256 let right_exclusive = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [12]);
2257 assert!(!vnode_range_overlaps_bitmap((10, 12), &right_exclusive));
2258
2259 let inside_range = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [11]);
2260 assert!(vnode_range_overlaps_bitmap((10, 12), &inside_range));
2261
2262 let last_vnode = Bitmap::from_indices(
2263 VirtualNode::COUNT_FOR_TEST,
2264 [VirtualNode::COUNT_FOR_TEST - 1],
2265 );
2266 assert!(vnode_range_overlaps_bitmap(
2267 (VirtualNode::COUNT_FOR_TEST - 1, VirtualNode::COUNT_FOR_TEST),
2268 &last_vnode
2269 ));
2270 assert!(!vnode_range_overlaps_bitmap(
2271 (VirtualNode::COUNT_FOR_TEST, VirtualNode::COUNT_FOR_TEST + 1),
2272 &last_vnode
2273 ));
2274 }
2275}