risingwave_storage/hummock/
mod.rs1use std::ops::Bound;
18use std::sync::Arc;
19
20use bytes::Bytes;
21use risingwave_hummock_sdk::key::{FullKey, TableKey, UserKeyRangeRef};
22use risingwave_hummock_sdk::sstable_info::SstableInfo;
23use risingwave_hummock_sdk::{HummockEpoch, *};
24
25pub mod block_cache;
26pub use block_cache::*;
27
28pub mod sstable;
29pub use sstable::*;
30
31pub mod compactor;
32mod error;
33pub mod hummock_meta_client;
34pub mod iterator;
35pub mod shared_buffer;
36pub mod sstable_store;
37#[cfg(any(test, feature = "test"))]
38pub mod test_utils;
39pub mod utils;
40pub use utils::MemoryLimiter;
41pub mod backup_reader;
42pub mod event_handler;
43pub mod local_version;
44pub mod observer_manager;
45#[allow(dead_code)]
47pub(crate) mod pin_cache;
48pub mod store;
49pub(crate) mod table_cache_metadata;
50pub use store::*;
51mod validator;
52pub mod value;
53pub mod write_limiter;
54
55pub mod recent_filter;
56pub use recent_filter::*;
57
58pub mod block_stream;
59mod time_travel_version_cache;
60
61pub(crate) mod vector;
62
63mod object_id_manager;
64pub use error::*;
65pub use object_id_manager::*;
66pub use risingwave_common::cache::{CacheableEntry, LookupResult, LruCache};
67pub use validator::*;
68use value::*;
69
70use self::iterator::HummockIterator;
71pub use self::sstable_store::*;
72use crate::mem_table::ImmutableMemtable;
73use crate::monitor::StoreLocalStatistic;
74use crate::store::ReadOptions;
75
76pub(in crate::hummock) struct IteratorStatsGuard<'a, TI: HummockIterator> {
77 iter: Option<TI>,
78 parent_stats: &'a mut StoreLocalStatistic,
79}
80
81impl<'a, TI: HummockIterator> IteratorStatsGuard<'a, TI> {
82 pub(in crate::hummock) fn new(iter: TI, parent_stats: &'a mut StoreLocalStatistic) -> Self {
83 Self {
84 iter: Some(iter),
85 parent_stats,
86 }
87 }
88
89 pub(in crate::hummock) fn iter(&self) -> &TI {
90 self.iter.as_ref().expect("iterator must be present")
91 }
92
93 pub(in crate::hummock) fn iter_mut(&mut self) -> &mut TI {
94 self.iter.as_mut().expect("iterator must be present")
95 }
96
97 fn collect(&mut self) {
98 if let Some(iter) = &self.iter {
99 iter.collect_local_statistic(self.parent_stats);
100 }
101 }
102
103 pub(in crate::hummock) fn handoff(mut self) -> TI {
104 self.iter.take().expect("iterator must be present")
105 }
106
107 pub(in crate::hummock) fn collect_and_take(mut self) -> TI {
108 self.collect();
109 self.iter.take().expect("iterator must be present")
110 }
111}
112
113impl<TI: HummockIterator> Drop for IteratorStatsGuard<'_, TI> {
114 fn drop(&mut self) {
115 self.collect();
116 }
117}
118
119pub async fn get_from_sstable_info(
120 sstable_store_ref: SstableStoreRef,
121 sstable_info: &SstableInfo,
122 full_key: FullKey<&[u8]>,
123 read_options: &ReadOptions,
124 dist_key_hash: Option<u64>,
125 local_stats: &mut StoreLocalStatistic,
126) -> HummockResult<Option<impl HummockIterator>> {
127 let sstable = sstable_store_ref.sstable(sstable_info, local_stats).await?;
128
129 if let Some(hash) = dist_key_hash
132 && !hit_sstable_filter(
133 &sstable,
134 &(
135 Bound::Included(full_key.user_key),
136 Bound::Included(full_key.user_key),
137 ),
138 hash,
139 local_stats,
140 )
141 {
142 return Ok(None);
143 }
144
145 let mut iterator_read_options = SstableIteratorReadOptions::from_read_options(read_options);
146 iterator_read_options.read_table_id = Some(full_key.user_key.table_id);
147
148 let mut iter = IteratorStatsGuard::new(
149 SstableIterator::create(
150 sstable,
151 sstable_store_ref.clone(),
152 Arc::new(iterator_read_options),
153 sstable_info,
154 ),
155 local_stats,
156 );
157 iter.iter_mut().seek(full_key).await?;
158 if !iter.iter().is_valid() {
160 return Ok(None);
161 }
162
163 let value = if iter.iter().key().user_key == full_key.user_key {
166 Some(iter.collect_and_take())
167 } else {
168 None
169 };
170
171 Ok(value)
172}
173
174pub fn hit_sstable_filter(
175 sstable_ref: &Sstable,
176 user_key_range: &UserKeyRangeRef<'_>,
177 prefix_hash: u64,
178 local_stats: &mut StoreLocalStatistic,
179) -> bool {
180 local_stats.bloom_filter_check_counts += 1;
181 let may_exist = sstable_ref.may_match_hash(user_key_range, prefix_hash);
182 if !may_exist {
183 local_stats.bloom_filter_true_negative_counts += 1;
184 }
185 may_exist
186}
187
188pub fn get_from_batch<'a>(
190 imm: &'a ImmutableMemtable,
191 table_key: TableKey<&[u8]>,
192 read_epoch: HummockEpoch,
193 read_options: &ReadOptions,
194 local_stats: &mut StoreLocalStatistic,
195) -> Option<(HummockValue<&'a Bytes>, EpochWithGap)> {
196 imm.get(table_key, read_epoch, read_options).inspect(|_| {
197 local_stats.get_shared_buffer_hit_counts += 1;
198 })
199}
200
201#[cfg(test)]
202mod tests {
203 use bytes::Bytes;
204 use risingwave_common::catalog::TableId;
205 use risingwave_common::hash::VirtualNode;
206 use risingwave_common::util::epoch::test_epoch;
207 use risingwave_hummock_sdk::EpochWithGap;
208 use risingwave_hummock_sdk::key::{FullKey, TableKey, UserKey};
209
210 use super::{CachePolicy, get_from_sstable_info};
211 use crate::hummock::iterator::test_utils::{iterator_test_key_of, mock_sstable_store};
212 use crate::hummock::test_utils::{
213 default_builder_opt_for_test, gen_test_sstable_info, gen_test_sstable_with_table_ids,
214 test_value_of,
215 };
216 use crate::hummock::value::HummockValue;
217 use crate::monitor::StoreLocalStatistic;
218 use crate::store::ReadOptions;
219
220 #[tokio::test]
221 async fn test_get_collects_stats_when_seek_passes_sst_end() {
222 let sstable_store = mock_sstable_store().await;
223 let sstable_info = gen_test_sstable_info(
224 default_builder_opt_for_test(),
225 1,
226 (0..10).map(|idx| {
227 (
228 iterator_test_key_of(idx),
229 HummockValue::put(format!("value_{idx}").into_bytes()),
230 )
231 }),
232 sstable_store.clone(),
233 )
234 .await;
235 let mut stats = StoreLocalStatistic::default();
236 let key = iterator_test_key_of(10);
237 let read_options = ReadOptions::default();
238
239 let result = get_from_sstable_info(
240 sstable_store,
241 &sstable_info,
242 key.to_ref(),
243 &read_options,
244 None,
245 &mut stats,
246 )
247 .await
248 .unwrap();
249
250 assert!(result.is_none());
251 drop(result);
252 assert_eq!(stats.cache_data_block_total, 1);
253 }
254
255 #[tokio::test]
256 async fn test_point_get_reads_only_requested_table_blocks() {
257 let sstable_store = mock_sstable_store().await;
258 let mut builder_options = default_builder_opt_for_test();
259 builder_options.block_capacity = 128;
260
261 let test_user_key = |table_id, key: &str| {
262 UserKey::new(
263 TableId::new(table_id),
264 TableKey(Bytes::from(
265 [VirtualNode::ZERO.to_be_bytes().as_slice(), key.as_bytes()].concat(),
266 )),
267 )
268 };
269 let test_key = |table_id, key: &str| FullKey {
270 user_key: test_user_key(table_id, key),
271 epoch_with_gap: EpochWithGap::new_from_epoch(test_epoch(1)),
272 };
273 let kv_pairs = (1..=2).flat_map(|table_id| {
274 (0..8).map(move |idx| {
275 (
276 test_key(table_id, &format!("key_{idx:05}")),
277 HummockValue::put(Bytes::from(test_value_of(idx))),
278 )
279 })
280 });
281 let (sstable, sstable_info) = gen_test_sstable_with_table_ids(
282 builder_options,
283 10,
284 kv_pairs,
285 sstable_store.clone(),
286 vec![1, 2],
287 )
288 .await;
289 let table_2_block_start = sstable
290 .meta
291 .block_metas
292 .partition_point(|block_meta| block_meta.table_id() < TableId::new(2));
293 assert!(table_2_block_start > 0);
294
295 let full_key = test_key(2, "key");
298 let mut local_stats = StoreLocalStatistic::default();
299 let read_options = ReadOptions {
300 cache_policy: CachePolicy::Disable,
301 ..Default::default()
302 };
303
304 {
305 let result = get_from_sstable_info(
306 sstable_store,
307 &sstable_info,
308 full_key.to_ref(),
309 &read_options,
310 None,
311 &mut local_stats,
312 )
313 .await
314 .unwrap();
315 assert!(result.is_none());
316 }
317 assert_eq!(local_stats.cache_data_block_total, 1);
318 }
319}