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 if res.is_ok() {
968 GLOBAL_CACHE_REFILL_METRICS
969 .meta_refill_success_duration
970 .observe(now.elapsed().as_secs_f64());
971 }
972 drop(permit);
973
974 res
975 })
976 .collect_vec();
977 let holders = try_join_all(tasks).await?;
978 Ok(holders)
979 }
980
981 async fn data_cache_refill(context: &CacheRefillContext, tasks: Vec<DataCacheRefillTask>) {
982 let mut futures = Vec::with_capacity(tasks.len());
983 for task in tasks {
984 context
986 .sstable_store
987 .recent_filter()
988 .insert((task.sst.id, usize::MAX));
989
990 let blocks = task.blks.len();
991 let mut contexts = Vec::with_capacity(blocks);
992 let mut admits = 0;
993
994 let (range_first, _) = task.sst.calculate_block_info(task.blks.start);
995 let (range_last, _) = task.sst.calculate_block_info(task.blks.end - 1);
996 let range = range_first.start..range_last.end;
997
998 let size = range.size().unwrap();
999
1000 GLOBAL_CACHE_REFILL_METRICS
1001 .data_refill_ideal_bytes
1002 .inc_by(size as _);
1003
1004 for blk in task.blks {
1005 let (range, uncompressed_capacity) = task.sst.calculate_block_info(blk);
1006 let key = SstableBlockIndex {
1007 sst_id: task.sst.id,
1008 block_idx: blk as u64,
1009 };
1010
1011 let mut writer = context.sstable_store.block_cache().storage_writer(key);
1012
1013 if writer.filter(size).is_admitted() {
1014 admits += 1;
1015 }
1016
1017 contexts.push((writer, range, uncompressed_capacity))
1018 }
1019
1020 if admits as f64 / contexts.len() as f64 >= context.config.threshold {
1021 let sstable_store = context.sstable_store.clone();
1022 let context = context.clone();
1023 let future = async move {
1024 GLOBAL_CACHE_REFILL_METRICS.data_refill_attempts_total.inc();
1025
1026 let permit = context.concurrency.acquire().await.unwrap();
1027
1028 GLOBAL_CACHE_REFILL_METRICS.data_refill_started_total.inc();
1029
1030 let now = Instant::now();
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 GLOBAL_CACHE_REFILL_METRICS
1061 .data_refill_success_duration
1062 .observe(now.elapsed().as_secs_f64());
1063 drop(permit);
1064
1065 Ok::<_, HummockError>(())
1066 };
1067 futures.push(future);
1068 }
1069 }
1070
1071 let futures = futures.into_iter().map(|future| async move {
1072 if let Err(e) = future.await {
1073 tracing::error!(error = %e.as_report(), "data cache refill task error");
1074 }
1075 });
1076
1077 join_all(futures).await;
1078 }
1079}
1080
1081#[derive(Debug)]
1082pub struct SstableBlock {
1083 pub sst_obj_id: HummockSstableObjectId,
1084 pub blk_idx: usize,
1085}
1086
1087#[derive(Debug, Hash, PartialEq, Eq)]
1088pub struct SstableUnit {
1089 pub sst_obj_id: HummockSstableObjectId,
1090 pub blks: Range<usize>,
1091}
1092
1093impl Ord for SstableUnit {
1094 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1095 match self.sst_obj_id.cmp(&other.sst_obj_id) {
1096 std::cmp::Ordering::Equal => {}
1097 ord => return ord,
1098 }
1099 match self.blks.start.cmp(&other.blks.start) {
1100 std::cmp::Ordering::Equal => {}
1101 ord => return ord,
1102 }
1103 self.blks.end.cmp(&other.blks.end)
1104 }
1105}
1106
1107impl PartialOrd for SstableUnit {
1108 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1109 Some(self.cmp(other))
1110 }
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115 use std::collections::{HashMap, HashSet};
1116 use std::sync::Arc;
1117 use std::time::Duration;
1118
1119 use bytes::Bytes;
1120 use parking_lot::Mutex;
1121 use risingwave_common::bitmap::Bitmap;
1122 use risingwave_common::config::Role;
1123 use risingwave_common::config::streaming::CacheRefillPolicy;
1124 use risingwave_common::hash::VirtualNode;
1125 use risingwave_common::util::epoch::test_epoch;
1126 use risingwave_hummock_sdk::compaction_group::group_split::split_sst_with_table_ids;
1127 use risingwave_hummock_sdk::key::{FullKey, UserKey, prefix_slice_with_vnode};
1128 use risingwave_hummock_sdk::sstable_info::{SstableInfo, SstableInfoInner};
1129 use risingwave_hummock_sdk::version::HummockVersion;
1130 use risingwave_hummock_sdk::{EpochWithGap, HummockSstableObjectId};
1131 use risingwave_pb::hummock::PbHummockVersion;
1132 use risingwave_pb::id::TableId;
1133 use tokio::sync::mpsc::unbounded_channel;
1134
1135 use super::{
1136 CacheRefillConfig, CacheRefillContext, CacheRefiller, DataCacheRefillTaskGenerator,
1137 SpawnRefillTask, SstDeltaInfo, block_vnode_range, vnode_range_overlaps_bitmap,
1138 };
1139 use crate::hummock::iterator::test_utils::{
1140 iterator_test_table_key_of, mock_sstable_store, mock_sstable_store_with_recent_filter,
1141 };
1142 use crate::hummock::local_version::pinned_version::PinnedVersion;
1143 use crate::hummock::recent_filter::simple::SimpleRecentFilter;
1144 use crate::hummock::test_utils::{
1145 default_builder_opt_for_test, gen_test_sstable_with_table_ids,
1146 };
1147 use crate::hummock::value::HummockValue;
1148 use crate::hummock::{RecentFilter, RecentFilterTrait, SstableStoreRef, TableHolder};
1149
1150 fn test_refill_config(default_policy: CacheRefillPolicy) -> CacheRefillConfig {
1151 CacheRefillConfig {
1152 timeout: Duration::from_secs(1),
1153 data_refill_levels: HashSet::new(),
1154 meta_refill_concurrency: 1,
1155 concurrency: 1,
1156 unit: 1,
1157 threshold: 0.0,
1158 skip_recent_filter: true,
1159 skip_inheritance_filter: true,
1160 table_cache_refill_default_policy: default_policy,
1161 }
1162 }
1163
1164 fn pinned_version_for_test() -> PinnedVersion {
1165 PinnedVersion::new(
1166 HummockVersion::from(PbHummockVersion::default()),
1167 unbounded_channel().0,
1168 )
1169 }
1170
1171 async fn gen_test_sst_with_object_id(
1172 table_id: TableId,
1173 sstable_store: SstableStoreRef,
1174 object_id: u64,
1175 ) -> (TableHolder, SstableInfo) {
1176 gen_test_sstable_with_table_ids(
1177 default_builder_opt_for_test(),
1178 object_id,
1179 (0..2).map(|idx| {
1180 (
1181 FullKey {
1182 user_key: risingwave_hummock_sdk::key::UserKey::for_test(
1183 table_id,
1184 iterator_test_table_key_of(idx),
1185 ),
1186 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
1187 },
1188 HummockValue::put(vec![idx as u8]),
1189 )
1190 }),
1191 sstable_store,
1192 vec![table_id.as_raw_id()],
1193 )
1194 .await
1195 }
1196
1197 struct DataRefillGeneratorTestFixture {
1198 table_id: TableId,
1199 sstable_store: SstableStoreRef,
1200 sst: TableHolder,
1201 sst_info: SstableInfo,
1202 deleted_sst_object_id: HummockSstableObjectId,
1203 }
1204
1205 impl DataRefillGeneratorTestFixture {
1206 async fn new(
1207 recent_filter: Option<Arc<RecentFilter<(HummockSstableObjectId, usize)>>>,
1208 ) -> Self {
1209 let table_id = TableId::from(233);
1210 let sstable_store = match recent_filter {
1211 Some(recent_filter) => mock_sstable_store_with_recent_filter(recent_filter).await,
1212 None => mock_sstable_store().await,
1213 };
1214 let (sst, sst_info) =
1215 gen_test_sst_with_object_id(table_id, sstable_store.clone(), 1).await;
1216 Self {
1217 table_id,
1218 sstable_store,
1219 sst,
1220 sst_info,
1221 deleted_sst_object_id: 2330.into(),
1222 }
1223 }
1224
1225 fn context(
1226 &self,
1227 policy: CacheRefillPolicy,
1228 streaming_vnode_bitmap: Option<Bitmap>,
1229 serving_vnode_bitmap: Option<Bitmap>,
1230 configure: impl FnOnce(&mut CacheRefillConfig),
1231 ) -> CacheRefillContext {
1232 let mut config = test_refill_config(CacheRefillPolicy::Enabled);
1233 config.data_refill_levels.insert(0);
1234 configure(&mut config);
1235 CacheRefillContext {
1236 config: Arc::new(config),
1237 meta_refill_concurrency: None,
1238 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
1239 sstable_store: self.sstable_store.clone(),
1240 table_cache_refill_context_map: Arc::new(HashMap::from([(
1241 self.table_id,
1242 super::TableCacheRefillContext {
1243 streaming_vnode_bitmap,
1244 serving_vnode_bitmap,
1245 policy,
1246 },
1247 )])),
1248 }
1249 }
1250
1251 fn normal_delta(
1252 &self,
1253 insert_sst_level: u32,
1254 deleted_sst_object_id: HummockSstableObjectId,
1255 ) -> SstDeltaInfo {
1256 SstDeltaInfo {
1257 insert_sst_infos: vec![self.sst_info.clone()],
1258 delete_sst_object_ids: vec![deleted_sst_object_id],
1259 insert_sst_level,
1260 }
1261 }
1262
1263 fn normal_l0_delta(&self) -> SstDeltaInfo {
1264 self.normal_delta(0, self.deleted_sst_object_id)
1265 }
1266
1267 fn l0_insert_only_delta(&self) -> SstDeltaInfo {
1268 SstDeltaInfo {
1269 insert_sst_infos: vec![self.sst_info.clone()],
1270 delete_sst_object_ids: vec![],
1271 insert_sst_level: 0,
1272 }
1273 }
1274
1275 async fn generate(
1276 &self,
1277 context: &CacheRefillContext,
1278 delta: &SstDeltaInfo,
1279 ) -> Vec<super::DataCacheRefillTask> {
1280 let generator = DataCacheRefillTaskGenerator {
1281 context,
1282 delta,
1283 ssts: std::slice::from_ref(&self.sst),
1284 };
1285 let tasks = generator.generate_unfiltered_tasks();
1286 generator.filter_by_inheritance_if_needed(tasks).await
1287 }
1288 }
1289
1290 #[tokio::test]
1291 async fn test_table_cache_refill_contexts_by_role_and_policy() {
1292 struct Case {
1293 name: &'static str,
1294 role: Role,
1295 default_policy: CacheRefillPolicy,
1296 policy: Option<CacheRefillPolicy>,
1297 has_streaming_vnodes: bool,
1298 has_serving_vnodes: bool,
1299 expected: Option<(CacheRefillPolicy, bool, bool)>,
1300 }
1301
1302 let cases = [
1303 Case {
1304 name: "streaming role uses streaming side of Both",
1305 role: Role::Streaming,
1306 default_policy: CacheRefillPolicy::Disabled,
1307 policy: Some(CacheRefillPolicy::Both),
1308 has_streaming_vnodes: true,
1309 has_serving_vnodes: true,
1310 expected: Some((CacheRefillPolicy::Both, true, false)),
1311 },
1312 Case {
1313 name: "serving role uses serving side of Both",
1314 role: Role::Serving,
1315 default_policy: CacheRefillPolicy::Disabled,
1316 policy: Some(CacheRefillPolicy::Both),
1317 has_streaming_vnodes: true,
1318 has_serving_vnodes: true,
1319 expected: Some((CacheRefillPolicy::Both, false, true)),
1320 },
1321 Case {
1322 name: "both role keeps both sides",
1323 role: Role::Both,
1324 default_policy: CacheRefillPolicy::Disabled,
1325 policy: Some(CacheRefillPolicy::Both),
1326 has_streaming_vnodes: true,
1327 has_serving_vnodes: true,
1328 expected: Some((CacheRefillPolicy::Both, true, true)),
1329 },
1330 Case {
1331 name: "both role keeps streaming-only ownership",
1332 role: Role::Both,
1333 default_policy: CacheRefillPolicy::Disabled,
1334 policy: Some(CacheRefillPolicy::Both),
1335 has_streaming_vnodes: true,
1336 has_serving_vnodes: false,
1337 expected: Some((CacheRefillPolicy::Both, true, false)),
1338 },
1339 Case {
1340 name: "streaming scope without ownership has no usable bitmap",
1341 role: Role::Streaming,
1342 default_policy: CacheRefillPolicy::Disabled,
1343 policy: Some(CacheRefillPolicy::Streaming),
1344 has_streaming_vnodes: false,
1345 has_serving_vnodes: false,
1346 expected: Some((CacheRefillPolicy::Streaming, false, false)),
1347 },
1348 Case {
1349 name: "pure serving worker excludes unmapped table",
1350 role: Role::Serving,
1351 default_policy: CacheRefillPolicy::Disabled,
1352 policy: Some(CacheRefillPolicy::Serving),
1353 has_streaming_vnodes: true,
1354 has_serving_vnodes: false,
1355 expected: None,
1356 },
1357 Case {
1358 name: "default Enabled retains serving ownership",
1359 role: Role::Serving,
1360 default_policy: CacheRefillPolicy::Enabled,
1361 policy: None,
1362 has_streaming_vnodes: false,
1363 has_serving_vnodes: true,
1364 expected: Some((CacheRefillPolicy::Enabled, false, true)),
1365 },
1366 Case {
1367 name: "explicit policy overrides default",
1368 role: Role::Serving,
1369 default_policy: CacheRefillPolicy::Enabled,
1370 policy: Some(CacheRefillPolicy::Disabled),
1371 has_streaming_vnodes: false,
1372 has_serving_vnodes: true,
1373 expected: Some((CacheRefillPolicy::Disabled, false, false)),
1374 },
1375 ];
1376
1377 let table_id = TableId::from(233);
1378 let streaming_vnodes = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1, 3]);
1379 let serving_vnodes = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [2, 4]);
1380 let sstable_store = mock_sstable_store().await;
1381 for case in cases {
1382 let mut refiller = CacheRefiller::new(
1383 case.role,
1384 test_refill_config(case.default_policy),
1385 sstable_store.clone(),
1386 CacheRefiller::default_spawn_refill_task(),
1387 );
1388 if let Some(policy) = case.policy {
1389 refiller.replace_table_cache_refill_policies(HashMap::from([(table_id, policy)]));
1390 }
1391 if case.has_streaming_vnodes {
1392 refiller.update_streaming_table_vnodes(table_id, Some(streaming_vnodes.clone()));
1393 }
1394 if case.has_serving_vnodes {
1395 refiller.replace_serving_table_vnode_mapping(HashMap::from([(
1396 table_id,
1397 serving_vnodes.clone(),
1398 )]));
1399 }
1400
1401 let contexts = refiller.table_cache_refill_contexts([table_id]);
1402 let actual = contexts.get(&table_id).map(|context| {
1403 (
1404 context.policy,
1405 context.streaming_vnode_bitmap.as_ref(),
1406 context.serving_vnode_bitmap.as_ref(),
1407 )
1408 });
1409 let expected = case.expected.map(|(policy, streaming, serving)| {
1410 (
1411 policy,
1412 streaming.then_some(&streaming_vnodes),
1413 serving.then_some(&serving_vnodes),
1414 )
1415 });
1416 assert_eq!(actual, expected, "{}", case.name);
1417 }
1418 }
1419
1420 #[tokio::test]
1421 async fn test_refill_task_captures_runtime_context_snapshot() {
1422 let table_id = TableId::from(233);
1423 let old_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
1424 let new_vnodes = Bitmap::from_range(VirtualNode::COUNT_FOR_TEST, 0..8);
1425 let captured_context = Arc::new(Mutex::new(None::<CacheRefillContext>));
1426 let captured_context_clone = captured_context.clone();
1427 let spawn_refill_task: SpawnRefillTask = Arc::new(move |_, context, _, _| {
1428 *captured_context_clone.lock() = Some(context);
1429 tokio::spawn(async {})
1430 });
1431 let mut refiller = CacheRefiller::new(
1432 Role::Serving,
1433 test_refill_config(CacheRefillPolicy::Enabled),
1434 mock_sstable_store().await,
1435 spawn_refill_task,
1436 );
1437
1438 refiller.replace_table_cache_refill_policies(HashMap::from([(
1439 table_id,
1440 CacheRefillPolicy::Serving,
1441 )]));
1442 refiller
1443 .replace_serving_table_vnode_mapping(HashMap::from([(table_id, old_vnodes.clone())]));
1444
1445 refiller.start_cache_refill(
1446 vec![SstDeltaInfo {
1447 insert_sst_infos: vec![SstableInfo::from(SstableInfoInner {
1448 table_ids: vec![table_id],
1449 ..Default::default()
1450 })],
1451 ..Default::default()
1452 }],
1453 pinned_version_for_test(),
1454 pinned_version_for_test(),
1455 );
1456 refiller.replace_table_cache_refill_policies(HashMap::from([(
1457 table_id,
1458 CacheRefillPolicy::Disabled,
1459 )]));
1460 refiller.replace_serving_table_vnode_mapping(HashMap::from([(table_id, new_vnodes)]));
1461
1462 let captured_context = captured_context.lock();
1463 let context = captured_context
1464 .as_ref()
1465 .unwrap()
1466 .table_cache_refill_context_map
1467 .get(&table_id)
1468 .unwrap();
1469 assert_eq!(context.policy, CacheRefillPolicy::Serving);
1470 assert_eq!(context.serving_vnode_bitmap.as_ref(), Some(&old_vnodes));
1471 }
1472
1473 #[tokio::test]
1474 async fn test_cache_refill_prunes_whole_ssts_before_meta_load() {
1475 let streaming_table = TableId::from(1);
1476 let serving_table = TableId::from(2);
1477 let disabled_table = TableId::from(3);
1478 let internal_table = TableId::from(4);
1479 let fallback_table = TableId::from(5);
1480 let serving_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
1481 let sstable_store = mock_sstable_store().await;
1482 let sst_info = |table_ids: Vec<TableId>| {
1483 SstableInfo::from(SstableInfoInner {
1484 table_ids,
1485 ..Default::default()
1486 })
1487 };
1488 let capture_pruned_table_ids = |role,
1489 default_policy,
1490 policies: HashMap<TableId, CacheRefillPolicy>,
1491 streaming_table_vnodes: HashMap<TableId, Bitmap>,
1492 serving_table_vnodes: HashMap<TableId, Bitmap>,
1493 delta| {
1494 let captured_deltas = Arc::new(Mutex::new(None::<Vec<SstDeltaInfo>>));
1495 let captured_deltas_clone = captured_deltas.clone();
1496 let spawn_refill_task: SpawnRefillTask = Arc::new(move |deltas, _, _, _| {
1497 *captured_deltas_clone.lock() = Some(deltas);
1498 tokio::spawn(async {})
1499 });
1500 let mut refiller = CacheRefiller::new(
1501 role,
1502 test_refill_config(default_policy),
1503 sstable_store.clone(),
1504 spawn_refill_task,
1505 );
1506 refiller.replace_table_cache_refill_policies(policies);
1507 for (table_id, vnodes) in streaming_table_vnodes {
1508 refiller.update_streaming_table_vnodes(table_id, Some(vnodes));
1509 }
1510 refiller.replace_serving_table_vnode_mapping(serving_table_vnodes);
1511 refiller.start_cache_refill(
1512 vec![delta],
1513 pinned_version_for_test(),
1514 pinned_version_for_test(),
1515 );
1516 captured_deltas
1517 .lock()
1518 .take()
1519 .unwrap()
1520 .pop()
1521 .unwrap()
1522 .insert_sst_infos
1523 .into_iter()
1524 .map(|sst| sst.table_ids.clone())
1525 .collect::<Vec<_>>()
1526 };
1527
1528 let normal_delta = |insert_sst_infos| SstDeltaInfo {
1529 insert_sst_infos,
1530 delete_sst_object_ids: vec![1.into()],
1531 insert_sst_level: 1,
1532 };
1533 let insert_only_delta = |insert_sst_infos| SstDeltaInfo {
1534 insert_sst_infos,
1535 delete_sst_object_ids: vec![],
1536 insert_sst_level: 0,
1537 };
1538
1539 assert_eq!(
1540 capture_pruned_table_ids(
1541 Role::Both,
1542 CacheRefillPolicy::Disabled,
1543 HashMap::from([
1544 (disabled_table, CacheRefillPolicy::Disabled),
1545 (streaming_table, CacheRefillPolicy::Enabled),
1546 ]),
1547 HashMap::new(),
1548 HashMap::new(),
1549 normal_delta(vec![
1550 sst_info(vec![disabled_table]),
1551 sst_info(vec![streaming_table]),
1552 ]),
1553 ),
1554 vec![vec![streaming_table]],
1555 );
1556
1557 assert_eq!(
1558 capture_pruned_table_ids(
1559 Role::Both,
1560 CacheRefillPolicy::Disabled,
1561 HashMap::from([
1562 (streaming_table, CacheRefillPolicy::Streaming),
1563 (internal_table, CacheRefillPolicy::Serving),
1564 ]),
1565 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1566 HashMap::new(),
1567 normal_delta(vec![
1568 sst_info(vec![streaming_table]),
1569 sst_info(vec![internal_table]),
1570 ]),
1571 ),
1572 vec![vec![streaming_table]],
1573 );
1574
1575 assert_eq!(
1576 capture_pruned_table_ids(
1577 Role::Both,
1578 CacheRefillPolicy::Disabled,
1579 HashMap::from([
1580 (streaming_table, CacheRefillPolicy::Streaming),
1581 (serving_table, CacheRefillPolicy::Serving),
1582 (internal_table, CacheRefillPolicy::Serving),
1583 ]),
1584 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1585 HashMap::from([(serving_table, serving_vnodes.clone())]),
1586 insert_only_delta(vec![
1587 sst_info(vec![streaming_table]),
1588 sst_info(vec![serving_table]),
1589 sst_info(vec![internal_table]),
1590 ]),
1591 ),
1592 vec![vec![serving_table]],
1593 );
1594
1595 assert_eq!(
1596 capture_pruned_table_ids(
1597 Role::Serving,
1598 CacheRefillPolicy::Disabled,
1599 HashMap::from([
1600 (streaming_table, CacheRefillPolicy::Streaming),
1601 (serving_table, CacheRefillPolicy::Serving),
1602 ]),
1603 HashMap::new(),
1604 HashMap::from([(serving_table, serving_vnodes.clone())]),
1605 normal_delta(vec![
1606 sst_info(vec![streaming_table]),
1607 sst_info(vec![serving_table]),
1608 ]),
1609 ),
1610 vec![vec![serving_table]],
1611 );
1612
1613 assert_eq!(
1614 capture_pruned_table_ids(
1615 Role::Serving,
1616 CacheRefillPolicy::Disabled,
1617 HashMap::from([
1618 (streaming_table, CacheRefillPolicy::Enabled),
1619 (serving_table, CacheRefillPolicy::Enabled),
1620 ]),
1621 HashMap::new(),
1622 HashMap::from([(serving_table, serving_vnodes.clone())]),
1623 normal_delta(vec![
1624 sst_info(vec![streaming_table]),
1625 sst_info(vec![serving_table]),
1626 sst_info(vec![streaming_table, serving_table]),
1627 ]),
1628 ),
1629 vec![
1630 vec![streaming_table],
1631 vec![serving_table],
1632 vec![streaming_table, serving_table],
1633 ],
1634 );
1635
1636 assert_eq!(
1637 capture_pruned_table_ids(
1638 Role::Both,
1639 CacheRefillPolicy::Disabled,
1640 HashMap::from([
1641 (streaming_table, CacheRefillPolicy::Both),
1642 (serving_table, CacheRefillPolicy::Both),
1643 ]),
1644 HashMap::new(),
1645 HashMap::new(),
1646 normal_delta(vec![
1647 sst_info(vec![streaming_table]),
1648 sst_info(vec![serving_table]),
1649 ]),
1650 ),
1651 Vec::<Vec<TableId>>::new(),
1652 );
1653
1654 assert_eq!(
1655 capture_pruned_table_ids(
1656 Role::Both,
1657 CacheRefillPolicy::Disabled,
1658 HashMap::from([
1659 (streaming_table, CacheRefillPolicy::Both),
1660 (serving_table, CacheRefillPolicy::Both),
1661 ]),
1662 HashMap::from([(streaming_table, serving_vnodes.clone())]),
1663 HashMap::new(),
1664 normal_delta(vec![
1665 sst_info(vec![streaming_table]),
1666 sst_info(vec![serving_table]),
1667 ]),
1668 ),
1669 vec![vec![streaming_table]],
1670 );
1671
1672 assert_eq!(
1673 capture_pruned_table_ids(
1674 Role::Both,
1675 CacheRefillPolicy::Disabled,
1676 HashMap::from([
1677 (streaming_table, CacheRefillPolicy::Both),
1678 (serving_table, CacheRefillPolicy::Both),
1679 ]),
1680 HashMap::new(),
1681 HashMap::from([(serving_table, serving_vnodes.clone())]),
1682 normal_delta(vec![
1683 sst_info(vec![streaming_table]),
1684 sst_info(vec![serving_table]),
1685 ]),
1686 ),
1687 vec![vec![serving_table]],
1688 );
1689
1690 assert_eq!(
1691 capture_pruned_table_ids(
1692 Role::Streaming,
1693 CacheRefillPolicy::Disabled,
1694 HashMap::from([
1695 (streaming_table, CacheRefillPolicy::Streaming),
1696 (serving_table, CacheRefillPolicy::Serving),
1697 ]),
1698 HashMap::new(),
1699 HashMap::new(),
1700 normal_delta(vec![
1701 sst_info(vec![streaming_table]),
1702 sst_info(vec![serving_table]),
1703 ]),
1704 ),
1705 Vec::<Vec<TableId>>::new(),
1706 );
1707
1708 assert_eq!(
1709 capture_pruned_table_ids(
1710 Role::Streaming,
1711 CacheRefillPolicy::Disabled,
1712 HashMap::from([
1713 (streaming_table, CacheRefillPolicy::Streaming),
1714 (serving_table, CacheRefillPolicy::Serving),
1715 ]),
1716 HashMap::new(),
1717 HashMap::new(),
1718 insert_only_delta(vec![
1719 sst_info(vec![streaming_table]),
1720 sst_info(vec![serving_table]),
1721 ]),
1722 ),
1723 Vec::<Vec<TableId>>::new(),
1724 );
1725
1726 assert_eq!(
1727 capture_pruned_table_ids(
1728 Role::Both,
1729 CacheRefillPolicy::Enabled,
1730 HashMap::from([(disabled_table, CacheRefillPolicy::Disabled)]),
1731 HashMap::new(),
1732 HashMap::new(),
1733 normal_delta(vec![
1734 sst_info(vec![disabled_table]),
1735 sst_info(vec![fallback_table]),
1736 sst_info(vec![disabled_table, fallback_table]),
1737 ]),
1738 ),
1739 vec![vec![fallback_table], vec![disabled_table, fallback_table]],
1740 );
1741 }
1742
1743 #[tokio::test]
1744 async fn test_normal_refill_applies_policy_and_vnode_ownership() {
1745 let fixture = DataRefillGeneratorTestFixture::new(None).await;
1746 let delta = fixture.normal_l0_delta();
1747 let owned = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [0]);
1748 let unowned = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1]);
1749 let cases = vec![
1750 ("Enabled", CacheRefillPolicy::Enabled, None, None, true),
1751 (
1752 "Disabled",
1753 CacheRefillPolicy::Disabled,
1754 Some(owned.clone()),
1755 Some(owned.clone()),
1756 false,
1757 ),
1758 (
1759 "Streaming match",
1760 CacheRefillPolicy::Streaming,
1761 Some(owned.clone()),
1762 None,
1763 true,
1764 ),
1765 (
1766 "Streaming miss",
1767 CacheRefillPolicy::Streaming,
1768 Some(unowned.clone()),
1769 None,
1770 false,
1771 ),
1772 (
1773 "Streaming ownership missing",
1774 CacheRefillPolicy::Streaming,
1775 None,
1776 None,
1777 false,
1778 ),
1779 (
1780 "Serving match",
1781 CacheRefillPolicy::Serving,
1782 None,
1783 Some(owned.clone()),
1784 true,
1785 ),
1786 (
1787 "Serving miss",
1788 CacheRefillPolicy::Serving,
1789 None,
1790 Some(unowned.clone()),
1791 false,
1792 ),
1793 (
1794 "Serving ownership missing",
1795 CacheRefillPolicy::Serving,
1796 None,
1797 None,
1798 false,
1799 ),
1800 (
1801 "Both streaming match",
1802 CacheRefillPolicy::Both,
1803 Some(owned.clone()),
1804 Some(unowned.clone()),
1805 true,
1806 ),
1807 (
1808 "Both serving match",
1809 CacheRefillPolicy::Both,
1810 Some(unowned.clone()),
1811 Some(owned),
1812 true,
1813 ),
1814 (
1815 "Both misses",
1816 CacheRefillPolicy::Both,
1817 Some(unowned.clone()),
1818 Some(unowned),
1819 false,
1820 ),
1821 ];
1822
1823 for (name, policy, streaming_vnodes, serving_vnodes, should_refill) in cases {
1824 let context = fixture.context(policy, streaming_vnodes, serving_vnodes, |_| {});
1825 assert_eq!(
1826 !fixture.generate(&context, &delta).await.is_empty(),
1827 should_refill,
1828 "{name}"
1829 );
1830 }
1831 }
1832
1833 #[tokio::test]
1834 async fn test_normal_refill_applies_recent_and_inheritance_filters() {
1835 let recent_filter = SimpleRecentFilter::new(3, Duration::from_secs(60));
1836 let fixture =
1837 DataRefillGeneratorTestFixture::new(Some(Arc::new(recent_filter.clone().into()))).await;
1838 let delta = fixture.normal_l0_delta();
1839
1840 let serving_context = fixture.context(
1841 CacheRefillPolicy::Serving,
1842 None,
1843 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1844 |config| {
1845 config.skip_recent_filter = false;
1846 },
1847 );
1848 assert!(
1849 fixture.generate(&serving_context, &delta).await.is_empty(),
1850 "explicit Serving policy is not an implicit skip_recent_filter"
1851 );
1852
1853 recent_filter.insert((fixture.deleted_sst_object_id, usize::MAX));
1854 assert!(
1855 !fixture.generate(&serving_context, &delta).await.is_empty(),
1856 "explicit Serving policy should produce tasks after recent admission hits"
1857 );
1858
1859 let (_, parent_sst_info) =
1860 gen_test_sst_with_object_id(fixture.table_id, fixture.sstable_store.clone(), 2).await;
1861 let non_l0_delta = fixture.normal_delta(1, parent_sst_info.object_id);
1862 let non_l0_context = fixture.context(CacheRefillPolicy::Enabled, None, None, |config| {
1863 config.data_refill_levels.insert(1);
1864 config.skip_recent_filter = false;
1865 config.skip_inheritance_filter = false;
1866 });
1867
1868 recent_filter.insert((parent_sst_info.object_id, usize::MAX));
1869 let generator = DataCacheRefillTaskGenerator {
1870 context: &non_l0_context,
1871 delta: &non_l0_delta,
1872 ssts: std::slice::from_ref(&fixture.sst),
1873 };
1874 let unfiltered_tasks = generator.generate_unfiltered_tasks();
1875 assert_eq!(
1876 unfiltered_tasks
1877 .iter()
1878 .map(|task| task.blks.len())
1879 .sum::<usize>(),
1880 fixture.sst.block_count(),
1881 "recent-admitted blocks should reach the inheritance stage"
1882 );
1883 assert!(
1884 generator
1885 .filter_by_inheritance_if_needed(unfiltered_tasks)
1886 .await
1887 .is_empty(),
1888 "after recent admission, parent block recent miss should filter non-L0 normal refill"
1889 );
1890
1891 recent_filter.insert((parent_sst_info.object_id, 0));
1892 let tasks = fixture.generate(&non_l0_context, &non_l0_delta).await;
1893 assert_eq!(tasks.len(), 1);
1894 assert_eq!(tasks[0].sst.id, fixture.sst.id);
1895 assert_eq!(tasks[0].blks, 0..1);
1896 }
1897
1898 #[tokio::test]
1899 async fn test_l0_insert_only_refill_policy_uses_serving_ownership() {
1900 let fixture = DataRefillGeneratorTestFixture::new(None).await;
1901 let delta = fixture.l0_insert_only_delta();
1902 let cases = [
1903 (
1904 "Enabled + serving overlap",
1905 CacheRefillPolicy::Enabled,
1906 None,
1907 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1908 true,
1909 ),
1910 (
1911 "Enabled without serving ownership",
1912 CacheRefillPolicy::Enabled,
1913 None,
1914 None,
1915 false,
1916 ),
1917 (
1918 "Serving + serving overlap",
1919 CacheRefillPolicy::Serving,
1920 None,
1921 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1922 true,
1923 ),
1924 (
1925 "Streaming + streaming overlap",
1926 CacheRefillPolicy::Streaming,
1927 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1928 None,
1929 false,
1930 ),
1931 (
1932 "Both + streaming overlap + serving non-overlap",
1933 CacheRefillPolicy::Both,
1934 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1935 Some(Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [1])),
1936 false,
1937 ),
1938 (
1939 "Both + serving overlap",
1940 CacheRefillPolicy::Both,
1941 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1942 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1943 true,
1944 ),
1945 (
1946 "Disabled + serving overlap",
1947 CacheRefillPolicy::Disabled,
1948 None,
1949 Some(Bitmap::ones(VirtualNode::COUNT_FOR_TEST)),
1950 false,
1951 ),
1952 ];
1953
1954 for (name, policy, streaming_vnodes, serving_vnodes, should_refill) in cases {
1955 let context = fixture.context(policy, streaming_vnodes, serving_vnodes, |config| {
1956 config.skip_recent_filter = false;
1957 config.skip_inheritance_filter = false;
1958 });
1959 assert_eq!(
1960 !fixture.generate(&context, &delta).await.is_empty(),
1961 should_refill,
1962 "{name}"
1963 );
1964 }
1965 }
1966
1967 #[tokio::test]
1968 async fn test_refill_units_do_not_cross_table_projection_boundaries() {
1969 let table_a = TableId::from(233);
1970 let table_b = TableId::from(234);
1971 let sstable_store = mock_sstable_store().await;
1972 let (sst, sst_info) = gen_test_sstable_with_table_ids(
1973 default_builder_opt_for_test(),
1974 1,
1975 [table_a, table_b].into_iter().map(|table_id| {
1976 (
1977 FullKey {
1978 user_key: UserKey::for_test(table_id, iterator_test_table_key_of(0)),
1979 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
1980 },
1981 HummockValue::put(b"value".to_vec()),
1982 )
1983 }),
1984 sstable_store.clone(),
1985 vec![table_a.as_raw_id(), table_b.as_raw_id()],
1986 )
1987 .await;
1988 assert_eq!(sst.block_count(), 2, "table switch must form a new block");
1989
1990 let mut next_sst_id = 100.into();
1991 let (table_a_projection, table_b_projection) =
1992 split_sst_with_table_ids(&sst_info, &mut next_sst_id, 1, 1, vec![table_b]);
1993 assert_eq!(table_a_projection.object_id, sst_info.object_id);
1994 assert_eq!(table_b_projection.object_id, sst_info.object_id);
1995 assert_ne!(table_a_projection.sst_id, table_b_projection.sst_id);
1996 assert_eq!(table_a_projection.table_ids, vec![table_a]);
1997 assert_eq!(table_b_projection.table_ids, vec![table_b]);
1998
1999 let deltas = [table_a_projection, table_b_projection].map(|projection| SstDeltaInfo {
2000 insert_sst_infos: vec![projection],
2001 delete_sst_object_ids: vec![],
2002 insert_sst_level: 0,
2003 });
2004 let normal_deltas = deltas.clone().map(|mut delta| {
2005 delta.delete_sst_object_ids = vec![999.into()];
2008 delta
2009 });
2010 let serving_vnodes = Bitmap::ones(VirtualNode::COUNT_FOR_TEST);
2011 let table_cache_refill_context_map = Arc::new(
2012 [table_a, table_b]
2013 .into_iter()
2014 .map(|table_id| {
2015 (
2016 table_id,
2017 super::TableCacheRefillContext {
2018 streaming_vnode_bitmap: None,
2019 serving_vnode_bitmap: Some(serving_vnodes.clone()),
2020 policy: CacheRefillPolicy::Serving,
2021 },
2022 )
2023 })
2024 .collect::<super::TableCacheRefillContextMap>(),
2025 );
2026 let make_context = |unit| {
2027 let mut config = test_refill_config(CacheRefillPolicy::Disabled);
2028 config.data_refill_levels.insert(0);
2029 config.unit = unit;
2030 CacheRefillContext {
2031 config: Arc::new(config),
2032 meta_refill_concurrency: None,
2033 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
2034 sstable_store: sstable_store.clone(),
2035 table_cache_refill_context_map: table_cache_refill_context_map.clone(),
2036 }
2037 };
2038 let generated_tasks = |context: &CacheRefillContext| {
2039 deltas
2040 .iter()
2041 .map(|delta| {
2042 DataCacheRefillTaskGenerator {
2043 context,
2044 delta,
2045 ssts: std::slice::from_ref(&sst),
2046 }
2047 .generate_unfiltered_tasks()
2048 })
2049 .collect::<Vec<_>>()
2050 };
2051 let generated_ranges = |context: &CacheRefillContext| {
2052 generated_tasks(context)
2053 .into_iter()
2054 .map(|tasks| tasks.into_iter().map(|task| task.blks).collect::<Vec<_>>())
2055 .collect::<Vec<_>>()
2056 };
2057
2058 assert_eq!(
2059 generated_ranges(&make_context(1)),
2060 vec![vec![0..1], vec![1..2]],
2061 "each logical projection must select only its own block"
2062 );
2063
2064 let wide_unit_context = make_context(2);
2065 assert_eq!(
2066 generated_ranges(&wide_unit_context),
2067 vec![vec![0..1], vec![1..2]],
2068 "units are clipped at table boundaries even when unit is larger than a table run"
2069 );
2070
2071 let normal_ranges = normal_deltas
2072 .iter()
2073 .map(|delta| {
2074 DataCacheRefillTaskGenerator {
2075 context: &wide_unit_context,
2076 delta,
2077 ssts: std::slice::from_ref(&sst),
2078 }
2079 .generate_unfiltered_tasks()
2080 .into_iter()
2081 .map(|task| task.blks)
2082 .collect::<Vec<_>>()
2083 })
2084 .collect::<Vec<_>>();
2085 assert_eq!(
2086 normal_ranges,
2087 vec![vec![0..1], vec![1..2]],
2088 "normal refill uses the same table-boundary geometry"
2089 );
2090
2091 for task in generated_tasks(&wide_unit_context).into_iter().flatten() {
2092 assert!(task.blks.len() <= wide_unit_context.config.unit);
2093 assert_eq!(
2094 task.sst.meta.block_metas[task.blks.start].table_id(),
2095 task.sst.meta.block_metas[task.blks.end - 1].table_id(),
2096 "a refill unit must not cross a table boundary"
2097 );
2098 }
2099 }
2100
2101 #[tokio::test]
2102 async fn test_scoped_refill_handles_multi_table_vnode_boundary() {
2103 let table_a = TableId::from(233);
2104 let table_b = TableId::from(234);
2105 let vnode_a = VirtualNode::COUNT_FOR_TEST - 1;
2106 let sstable_store = mock_sstable_store().await;
2107 let (sst, sst_info) = gen_test_sstable_with_table_ids(
2108 default_builder_opt_for_test(),
2109 1,
2110 [
2111 (
2112 FullKey {
2113 user_key: UserKey::for_test(
2114 table_a,
2115 prefix_slice_with_vnode(VirtualNode::from_index(vnode_a), b"table_a"),
2116 ),
2117 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2118 },
2119 HummockValue::put(Bytes::from_static(b"a")),
2120 ),
2121 (
2122 FullKey {
2123 user_key: UserKey::for_test(
2124 table_b,
2125 prefix_slice_with_vnode(VirtualNode::ZERO, b"table_b"),
2126 ),
2127 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2128 },
2129 HummockValue::put(Bytes::from_static(b"b")),
2130 ),
2131 ]
2132 .into_iter(),
2133 sstable_store.clone(),
2134 vec![table_a.as_raw_id(), table_b.as_raw_id()],
2135 )
2136 .await;
2137 assert_eq!(sst.block_count(), 2, "table switch must form a new block");
2138
2139 let generate = |streaming_vnodes| {
2140 let sstable_store = sstable_store.clone();
2141 let sst = sst.clone();
2142 let sst_info = sst_info.clone();
2143 let mut config = test_refill_config(CacheRefillPolicy::Streaming);
2144 config.data_refill_levels.insert(0);
2145 let context = CacheRefillContext {
2146 config: Arc::new(config),
2147 meta_refill_concurrency: None,
2148 concurrency: Arc::new(tokio::sync::Semaphore::new(1)),
2149 sstable_store,
2150 table_cache_refill_context_map: Arc::new(HashMap::from([(
2151 table_a,
2152 super::TableCacheRefillContext {
2153 streaming_vnode_bitmap: Some(streaming_vnodes),
2154 serving_vnode_bitmap: None,
2155 policy: CacheRefillPolicy::Streaming,
2156 },
2157 )])),
2158 };
2159 async move {
2160 let generator = DataCacheRefillTaskGenerator {
2161 context: &context,
2162 delta: &SstDeltaInfo {
2163 insert_sst_infos: vec![sst_info.clone()],
2164 delete_sst_object_ids: vec![2330.into()],
2165 insert_sst_level: 0,
2166 },
2167 ssts: std::slice::from_ref(&sst),
2168 };
2169 let tasks = generator.generate_unfiltered_tasks();
2170 generator.filter_by_inheritance_if_needed(tasks).await
2171 }
2172 };
2173
2174 let matching_tasks =
2175 generate(Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [vnode_a])).await;
2176 assert_eq!(matching_tasks.len(), 1);
2177 assert_eq!(matching_tasks[0].blks, 0..1);
2178
2179 let non_matching_tasks = generate(Bitmap::from_indices(
2180 VirtualNode::COUNT_FOR_TEST,
2181 [VirtualNode::ZERO.to_index()],
2182 ))
2183 .await;
2184 assert!(non_matching_tasks.is_empty());
2185 }
2186
2187 #[tokio::test]
2188 async fn test_block_vnode_range_handles_vnode_only_block_boundaries() {
2189 let table_id = TableId::from(233);
2190 let vnode = VirtualNode::ZERO;
2191 let sstable_store = mock_sstable_store().await;
2192 let mut builder_options = default_builder_opt_for_test();
2193 builder_options.block_capacity = 1;
2194 let (sst, _) = gen_test_sstable_with_table_ids(
2195 builder_options,
2196 1,
2197 [234, 233].into_iter().map(|epoch| {
2198 (
2199 FullKey {
2200 user_key: UserKey::for_test(table_id, prefix_slice_with_vnode(vnode, b"")),
2201 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(epoch)),
2202 },
2203 HummockValue::put(Bytes::from_static(b"value")),
2204 )
2205 }),
2206 sstable_store.clone(),
2207 vec![table_id.as_raw_id()],
2208 )
2209 .await;
2210 assert_eq!(sst.block_count(), 2);
2211 let expected = (vnode.to_index(), vnode.to_index() + 1);
2212 assert_eq!(block_vnode_range(&sst, 0), expected);
2213 assert_eq!(block_vnode_range(&sst, 1), expected);
2214 }
2215
2216 #[tokio::test]
2217 async fn test_block_vnode_range_fails_open_for_shortened_meta_keys() {
2218 let table_id = TableId::from(233);
2219 let sstable_store = mock_sstable_store().await;
2220 let mut builder_options = default_builder_opt_for_test();
2221 builder_options.block_capacity = 1;
2222 builder_options.shorten_block_meta_key_threshold = Some(0);
2223 let (sst, _) = gen_test_sstable_with_table_ids(
2224 builder_options,
2225 1,
2226 [255, 256].into_iter().map(|vnode| {
2227 (
2228 FullKey {
2229 user_key: UserKey::for_test(
2230 table_id,
2231 prefix_slice_with_vnode(VirtualNode::from_index(vnode), b"long-key"),
2232 ),
2233 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(233)),
2234 },
2235 HummockValue::put(Bytes::from_static(b"value")),
2236 )
2237 }),
2238 sstable_store,
2239 vec![table_id.as_raw_id()],
2240 )
2241 .await;
2242 assert_eq!(sst.block_count(), 2);
2243 assert!(
2244 FullKey::decode(&sst.meta.block_metas[1].smallest_key)
2245 .user_key
2246 .table_key
2247 .as_ref()
2248 .len()
2249 < VirtualNode::SIZE
2250 );
2251 let full_range = (0, VirtualNode::MAX_REPRESENTABLE.to_index() + 1);
2252 assert_eq!(block_vnode_range(&sst, 0), full_range);
2253 assert_eq!(block_vnode_range(&sst, 1), full_range);
2254 }
2255
2256 #[test]
2257 fn test_vnode_range_overlaps_bitmap_uses_right_exclusive_end() {
2258 let right_exclusive = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [12]);
2259 assert!(!vnode_range_overlaps_bitmap((10, 12), &right_exclusive));
2260
2261 let inside_range = Bitmap::from_indices(VirtualNode::COUNT_FOR_TEST, [11]);
2262 assert!(vnode_range_overlaps_bitmap((10, 12), &inside_range));
2263
2264 let last_vnode = Bitmap::from_indices(
2265 VirtualNode::COUNT_FOR_TEST,
2266 [VirtualNode::COUNT_FOR_TEST - 1],
2267 );
2268 assert!(vnode_range_overlaps_bitmap(
2269 (VirtualNode::COUNT_FOR_TEST - 1, VirtualNode::COUNT_FOR_TEST),
2270 &last_vnode
2271 ));
2272 assert!(!vnode_range_overlaps_bitmap(
2273 (VirtualNode::COUNT_FOR_TEST, VirtualNode::COUNT_FOR_TEST + 1),
2274 &last_vnode
2275 ));
2276 }
2277}