Skip to main content

mito2/
memtable.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Memtables are write buffers for regions.
16
17use std::collections::{BTreeMap, HashMap};
18use std::fmt;
19use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
20use std::sync::{Arc, Mutex};
21use std::time::Duration;
22
23pub use bulk::part::EncodedBulkPart;
24use bytes::Bytes;
25use common_time::Timestamp;
26use datatypes::arrow::datatypes::SchemaRef;
27use datatypes::arrow::record_batch::RecordBatch;
28use mito_codec::key_values::KeyValue;
29pub use mito_codec::key_values::KeyValues;
30use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
31use snafu::ensure;
32use store_api::codec::PrimaryKeyEncoding;
33use store_api::metadata::{RegionMetadata, RegionMetadataRef};
34use store_api::storage::{ColumnId, RegionId, SequenceNumber, SequenceRange};
35
36use crate::config::MitoConfig;
37use crate::error::{InvalidRegionOptionsSnafu, Result, UnsupportedOperationSnafu};
38use crate::flush::WriteBufferManagerRef;
39use crate::memtable::bulk::{BulkMemtableBuilder, BulkMemtableConfig, CompactDispatcher};
40use crate::memtable::time_series::TimeSeriesMemtableBuilder;
41use crate::metrics::WRITE_BUFFER_BYTES;
42use crate::read::Batch;
43use crate::read::batch_adapter::BatchToRecordBatchAdapter;
44use crate::read::prune::PruneTimeIterator;
45use crate::read::scan_region::PredicateGroup;
46use crate::region::options::{MemtableOptions, MergeMode, RegionOptions};
47use crate::sst::FormatType;
48use crate::sst::file::FileTimeRange;
49use crate::sst::parquet::SstInfo;
50use crate::sst::parquet::file_range::PreFilterMode;
51
52mod builder;
53pub mod bulk;
54pub mod simple_bulk_memtable;
55mod stats;
56pub mod time_partition;
57pub mod time_series;
58pub(crate) mod version;
59
60pub use bulk::part::{
61    BulkPart, BulkPartEncoder, BulkPartMeta, UnorderedPart, record_batch_estimated_size,
62    sort_primary_key_record_batch,
63};
64#[cfg(any(test, feature = "test"))]
65pub use time_partition::filter_record_batch;
66
67/// Groups sequence intervals into ordered, disjoint components. A component must
68/// not be split during a partial merge: an excluded interval could contain an
69/// intermediate row version. Bounds may conservatively include removed rows.
70pub(crate) fn group_by_sequence<T>(
71    mut parts: Vec<T>,
72    bounds: impl Fn(&T) -> (SequenceNumber, SequenceNumber),
73) -> Vec<Vec<T>> {
74    parts.sort_by_key(&bounds);
75    let mut groups: Vec<Vec<T>> = Vec::new();
76    let mut group_max = 0;
77    for part in parts {
78        let (min, max) = bounds(&part);
79        match groups.last_mut() {
80            Some(group) if min <= group_max => {
81                group.push(part);
82                group_max = group_max.max(max);
83            }
84            _ => {
85                groups.push(vec![part]);
86                group_max = max;
87            }
88        }
89    }
90    groups
91}
92
93/// Id for memtables.
94///
95/// Should be unique under the same region.
96pub type MemtableId = u32;
97
98/// Options for querying ranges from a memtable.
99#[derive(Clone)]
100pub struct RangesOptions {
101    /// Whether the ranges are being queried for flush.
102    pub for_flush: bool,
103    /// Mode to pre-filter columns in ranges.
104    pub pre_filter_mode: PreFilterMode,
105    /// Predicate to filter the data.
106    pub predicate: PredicateGroup,
107    /// Sequence range to filter the data.
108    pub sequence: Option<SequenceRange>,
109    /// Maximum number of rows readers should produce in one batch.
110    pub batch_size: usize,
111}
112
113impl Default for RangesOptions {
114    fn default() -> Self {
115        Self {
116            for_flush: false,
117            pre_filter_mode: PreFilterMode::All,
118            predicate: PredicateGroup::default(),
119            sequence: None,
120            batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
121        }
122    }
123}
124
125impl RangesOptions {
126    /// Creates a new [RangesOptions] for flushing.
127    pub fn for_flush() -> Self {
128        Self {
129            for_flush: true,
130            pre_filter_mode: PreFilterMode::All,
131            predicate: PredicateGroup::default(),
132            sequence: None,
133            batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
134        }
135    }
136
137    /// Sets the pre-filter mode.
138    #[must_use]
139    pub fn with_pre_filter_mode(mut self, pre_filter_mode: PreFilterMode) -> Self {
140        self.pre_filter_mode = pre_filter_mode;
141        self
142    }
143
144    /// Sets the predicate.
145    #[must_use]
146    pub fn with_predicate(mut self, predicate: PredicateGroup) -> Self {
147        self.predicate = predicate;
148        self
149    }
150
151    /// Sets the sequence range.
152    #[must_use]
153    pub fn with_sequence(mut self, sequence: Option<SequenceRange>) -> Self {
154        self.sequence = sequence;
155        self
156    }
157
158    /// Sets the maximum number of rows readers should produce in one batch.
159    #[must_use]
160    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
161        self.batch_size = batch_size.clamp(1, crate::sst::parquet::DEFAULT_READ_BATCH_SIZE);
162        self
163    }
164}
165
166#[derive(Debug, Default, Clone)]
167pub struct MemtableStats {
168    /// The estimated bytes allocated by this memtable from heap.
169    pub estimated_bytes: usize,
170    /// Estimated bytes of the rows once decoded, for sizing reads and counting written data.
171    /// `None` means `estimated_bytes`, as the memtable keeps its rows decoded. A memtable that
172    /// encodes rows in memory reports the bytes written into it, including rows deduplicated
173    /// later.
174    pub decoded_bytes: Option<usize>,
175    /// The inclusive time range that this memtable contains. It is None if
176    /// and only if the memtable is empty.
177    pub time_range: Option<(Timestamp, Timestamp)>,
178    /// Total rows in memtable
179    pub num_rows: usize,
180    /// Total number of ranges in the memtable.
181    pub num_ranges: usize,
182    /// The maximum sequence number in the memtable.
183    pub max_sequence: SequenceNumber,
184    /// Lower bound of the row sequences written to this memtable or range.
185    /// May remain below the actual minimum after deduplication. Zero is conservative
186    /// when a range does not track its minimum; the value is unused for empty memtables.
187    pub min_sequence: SequenceNumber,
188    /// Number of estimated timeseries in memtable.
189    pub series_count: usize,
190}
191
192impl MemtableStats {
193    /// Attaches the time range to the stats.
194    #[cfg(any(test, feature = "test"))]
195    pub fn with_time_range(mut self, time_range: Option<(Timestamp, Timestamp)>) -> Self {
196        self.time_range = time_range;
197        self
198    }
199
200    #[cfg(feature = "test")]
201    pub fn with_max_sequence(mut self, max_sequence: SequenceNumber) -> Self {
202        self.max_sequence = max_sequence;
203        self
204    }
205
206    /// Returns the estimated bytes allocated by this memtable.
207    pub fn bytes_allocated(&self) -> usize {
208        self.estimated_bytes
209    }
210
211    /// Returns the estimated bytes of the rows once decoded.
212    pub fn decoded_bytes(&self) -> usize {
213        self.decoded_bytes.unwrap_or(self.estimated_bytes)
214    }
215
216    /// Returns the time range of the memtable.
217    pub fn time_range(&self) -> Option<(Timestamp, Timestamp)> {
218        self.time_range
219    }
220
221    /// Returns the num of total rows in memtable.
222    pub fn num_rows(&self) -> usize {
223        self.num_rows
224    }
225
226    /// Returns the number of ranges in the memtable.
227    pub fn num_ranges(&self) -> usize {
228        self.num_ranges
229    }
230
231    /// Returns the maximum sequence number in the memtable.
232    pub fn max_sequence(&self) -> SequenceNumber {
233        self.max_sequence
234    }
235
236    /// Series count in memtable.
237    pub fn series_count(&self) -> usize {
238        self.series_count
239    }
240}
241
242pub type BoxedBatchIterator = Box<dyn Iterator<Item = Result<Batch>> + Send>;
243
244pub type BoxedRecordBatchIterator = Box<dyn Iterator<Item = Result<RecordBatch>> + Send>;
245
246/// Ranges in a memtable.
247#[derive(Default)]
248pub struct MemtableRanges {
249    /// Range IDs and ranges.
250    pub ranges: BTreeMap<usize, MemtableRange>,
251}
252
253impl MemtableRanges {
254    /// Returns the total number of rows across all ranges.
255    pub fn num_rows(&self) -> usize {
256        self.ranges.values().map(|r| r.stats().num_rows()).sum()
257    }
258
259    /// Returns the total series count across all ranges.
260    pub fn series_count(&self) -> usize {
261        self.ranges.values().map(|r| r.stats().series_count()).sum()
262    }
263
264    /// Returns the maximum sequence number across all ranges.
265    pub fn max_sequence(&self) -> SequenceNumber {
266        self.ranges
267            .values()
268            .map(|r| r.stats().max_sequence())
269            .max()
270            .unwrap_or(0)
271    }
272}
273
274impl IterBuilder for MemtableRanges {
275    fn build(&self, _metrics: Option<MemScanMetrics>) -> Result<BoxedBatchIterator> {
276        ensure!(
277            self.ranges.len() == 1,
278            UnsupportedOperationSnafu {
279                err_msg: format!(
280                    "Building an iterator from MemtableRanges expects 1 range, but got {}",
281                    self.ranges.len()
282                ),
283            }
284        );
285
286        self.ranges.values().next().unwrap().build_iter()
287    }
288
289    fn is_record_batch(&self) -> bool {
290        self.ranges.values().all(|range| range.is_record_batch())
291    }
292}
293
294/// In memory write buffer.
295pub trait Memtable: Send + Sync + fmt::Debug {
296    /// Returns the id of this memtable.
297    fn id(&self) -> MemtableId;
298
299    /// Writes key values into the memtable.
300    fn write(&self, kvs: &KeyValues) -> Result<()>;
301
302    /// Writes one key value pair into the memtable.
303    fn write_one(&self, key_value: KeyValue) -> Result<()>;
304
305    /// Writes an encoded batch of into memtable.
306    fn write_bulk(&self, part: crate::memtable::bulk::part::BulkPart) -> Result<()>;
307
308    /// Returns the ranges in the memtable.
309    ///
310    /// The returned map contains the range id and the range after applying the predicate.
311    fn ranges(
312        &self,
313        projection: Option<&[ColumnId]>,
314        options: RangesOptions,
315    ) -> Result<MemtableRanges>;
316
317    /// Returns true if the memtable is empty.
318    fn is_empty(&self) -> bool;
319
320    /// Turns a mutable memtable into an immutable memtable.
321    fn freeze(&self) -> Result<()>;
322
323    /// Returns the [MemtableStats] info of Memtable.
324    fn stats(&self) -> MemtableStats;
325
326    /// Returns a conservative row-sequence lower bound without computing full statistics.
327    /// Returns zero when write statistics are unavailable. Callers must ignore
328    /// empty memtables when using this bound to constrain compaction.
329    fn min_sequence(&self) -> SequenceNumber;
330
331    /// Forks this (immutable) memtable and returns a new mutable memtable with specific memtable `id`.
332    ///
333    /// A region must freeze the memtable before invoking this method.
334    fn fork(&self, id: MemtableId, metadata: &RegionMetadataRef) -> MemtableRef;
335
336    /// Compacts the memtable.
337    ///
338    /// The `for_flush` is true when the flush job calls this method.
339    fn compact(&self, for_flush: bool) -> Result<()> {
340        let _ = for_flush;
341        Ok(())
342    }
343}
344
345pub type MemtableRef = Arc<dyn Memtable>;
346
347/// Builder to build a new [Memtable].
348pub trait MemtableBuilder: Send + Sync + fmt::Debug {
349    /// Builds a new memtable instance.
350    fn build(&self, id: MemtableId, metadata: &RegionMetadataRef) -> MemtableRef;
351
352    /// Returns true if the memtable supports bulk insert and benefits from it.
353    fn use_bulk_insert(&self, metadata: &RegionMetadataRef) -> bool {
354        let _metadata = metadata;
355        false
356    }
357}
358
359pub type MemtableBuilderRef = Arc<dyn MemtableBuilder>;
360
361/// Memtable memory allocation tracker.
362#[derive(Default)]
363pub struct AllocTracker {
364    write_buffer_manager: Option<WriteBufferManagerRef>,
365    /// Bytes allocated by the tracker.
366    bytes_allocated: AtomicUsize,
367    /// Whether allocating is done.
368    is_done_allocating: AtomicBool,
369    /// Serializes [Self::done_allocating] with charging and releasing, which all decide how
370    /// much of the allocated memory counts as mutable memory of the write buffer.
371    release: std::sync::Mutex<()>,
372}
373
374impl fmt::Debug for AllocTracker {
375    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376        f.debug_struct("AllocTracker")
377            .field("bytes_allocated", &self.bytes_allocated)
378            .field("is_done_allocating", &self.is_done_allocating)
379            .finish()
380    }
381}
382
383impl AllocTracker {
384    /// Returns a new [AllocTracker].
385    pub fn new(write_buffer_manager: Option<WriteBufferManagerRef>) -> AllocTracker {
386        AllocTracker {
387            write_buffer_manager,
388            bytes_allocated: AtomicUsize::new(0),
389            is_done_allocating: AtomicBool::new(false),
390            release: std::sync::Mutex::new(()),
391        }
392    }
393
394    /// Tracks `bytes` memory is allocated.
395    pub(crate) fn on_allocation(&self, bytes: usize) {
396        self.bytes_allocated.fetch_add(bytes, Ordering::Relaxed);
397        WRITE_BUFFER_BYTES.add(bytes as i64);
398        if let Some(write_buffer_manager) = &self.write_buffer_manager {
399            write_buffer_manager.reserve_mem(bytes);
400        }
401    }
402
403    /// Marks we have finished allocating memory so we can free it from
404    /// the write buffer's limit.
405    ///
406    /// The region MUST ensure that it calls this method inside the region writer's write lock.
407    pub(crate) fn done_allocating(&self) {
408        let _release = self.release.lock().unwrap();
409        if let Some(write_buffer_manager) = &self.write_buffer_manager
410            && self
411                .is_done_allocating
412                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
413                .is_ok()
414        {
415            write_buffer_manager.schedule_free_mem(self.bytes_allocated.load(Ordering::Relaxed));
416        }
417    }
418
419    /// Charges `bytes` to this tracker until the returned charge drops.
420    ///
421    /// Memtables that replace their data, or hand it to readers, keep a charge with the data so
422    /// the write buffer stays charged until the last holder releases it.
423    pub(crate) fn charge(self: &Arc<Self>, bytes: usize) -> MemoryCharge {
424        let _release = self.release.lock().unwrap();
425        self.bytes_allocated.fetch_add(bytes, Ordering::Relaxed);
426        WRITE_BUFFER_BYTES.add(bytes as i64);
427        if let Some(write_buffer_manager) = &self.write_buffer_manager {
428            write_buffer_manager.reserve_mem(bytes);
429            // Frozen memory no longer counts as mutable memory.
430            if self.is_done_allocating.load(Ordering::Relaxed) {
431                write_buffer_manager.schedule_free_mem(bytes);
432            }
433        }
434        MemoryCharge {
435            tracker: self.clone(),
436            bytes,
437        }
438    }
439
440    fn release(&self, bytes: usize) {
441        let _release = self.release.lock().unwrap();
442        self.bytes_allocated.fetch_sub(bytes, Ordering::Relaxed);
443        WRITE_BUFFER_BYTES.sub(bytes as i64);
444        if let Some(write_buffer_manager) = &self.write_buffer_manager {
445            // Freezing already removed the frozen bytes from the mutable memory.
446            if !self.is_done_allocating.load(Ordering::Relaxed) {
447                write_buffer_manager.schedule_free_mem(bytes);
448            }
449            write_buffer_manager.release_mem(bytes);
450        }
451    }
452
453    /// Returns bytes allocated.
454    pub(crate) fn bytes_allocated(&self) -> usize {
455        self.bytes_allocated.load(Ordering::Relaxed)
456    }
457
458    /// Returns the write buffer manager.
459    pub(crate) fn write_buffer_manager(&self) -> Option<WriteBufferManagerRef> {
460        self.write_buffer_manager.clone()
461    }
462}
463
464impl Drop for AllocTracker {
465    fn drop(&mut self) {
466        if !self.is_done_allocating.load(Ordering::Relaxed) {
467            self.done_allocating();
468        }
469
470        let bytes_allocated = self.bytes_allocated.load(Ordering::Relaxed);
471        WRITE_BUFFER_BYTES.sub(bytes_allocated as i64);
472
473        // Memory tracked by this tracker is freed.
474        if let Some(write_buffer_manager) = &self.write_buffer_manager {
475            write_buffer_manager.free_mem(bytes_allocated);
476        }
477    }
478}
479
480/// Memory charged to an [AllocTracker] until this charge drops.
481///
482/// The charge keeps its tracker alive, so data still held by readers stays charged after its
483/// memtable is dropped. Ranges, and the iterators and encoded data built from them, hold the
484/// charge; batches that an iterator passes on without copying are not covered once it drops.
485pub(crate) struct MemoryCharge {
486    tracker: Arc<AllocTracker>,
487    bytes: usize,
488}
489
490impl MemoryCharge {
491    pub(crate) fn bytes(&self) -> usize {
492        self.bytes
493    }
494}
495
496impl fmt::Debug for MemoryCharge {
497    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498        f.debug_struct("MemoryCharge")
499            .field("bytes", &self.bytes)
500            .finish()
501    }
502}
503
504impl Drop for MemoryCharge {
505    fn drop(&mut self) {
506        self.tracker.release(self.bytes);
507    }
508}
509
510/// Provider of memtable builders for regions.
511#[derive(Clone)]
512pub(crate) struct MemtableBuilderProvider {
513    write_buffer_manager: Option<WriteBufferManagerRef>,
514    config: Arc<MitoConfig>,
515    default_bulk_memtable_config: BulkMemtableConfig,
516    compact_dispatcher: Arc<CompactDispatcher>,
517}
518
519/// Ensures JSON2 columns use flat SST output after resolving the SST format.
520pub(crate) fn ensure_json2_uses_flat_format(
521    metadata: &RegionMetadata,
522    options: &RegionOptions,
523) -> Result<()> {
524    if metadata
525        .column_metadatas
526        .iter()
527        .any(|x| x.column_schema.data_type.is_json2())
528    {
529        // Bulk memtables alone do not ensure the SST writer supports JSON2.
530        ensure!(
531            options.sst_format == Some(FormatType::Flat),
532            InvalidRegionOptionsSnafu {
533                reason: "JSON2 columns require sst_format=flat",
534            }
535        );
536    }
537    Ok(())
538}
539
540impl MemtableBuilderProvider {
541    pub(crate) fn new(
542        write_buffer_manager: Option<WriteBufferManagerRef>,
543        config: Arc<MitoConfig>,
544        compact_dispatcher: Arc<CompactDispatcher>,
545    ) -> Self {
546        let default_bulk_memtable_config = BulkMemtableConfig::default_for_write_buffer_size(
547            config.global_write_buffer_size.as_bytes() as usize,
548        );
549
550        Self {
551            write_buffer_manager,
552            config,
553            default_bulk_memtable_config,
554            compact_dispatcher,
555        }
556    }
557
558    /// Parses region options with this provider's default bulk memtable config.
559    pub(crate) fn parse_options(
560        &self,
561        region_id: RegionId,
562        options: &HashMap<String, String>,
563    ) -> Result<RegionOptions> {
564        RegionOptions::try_from_options_with_bulk_config(
565            region_id,
566            options,
567            &self.default_bulk_memtable_config,
568        )
569    }
570
571    pub(crate) fn builder_for_options(&self, options: &RegionOptions) -> MemtableBuilderRef {
572        let dedup = options.need_dedup();
573        let merge_mode = options.merge_mode();
574        let primary_key_encoding = options.primary_key_encoding();
575        let flat_format = options
576            .sst_format
577            .map(|format| format == FormatType::Flat)
578            .unwrap_or(self.config.default_flat_format);
579        if flat_format {
580            if options.memtable.is_some()
581                && !matches!(&options.memtable, Some(MemtableOptions::Bulk(_)))
582            {
583                common_telemetry::info!(
584                    "Overriding memtable config, use BulkMemtable under flat format"
585                );
586            }
587
588            return Arc::new(self.bulk_memtable_builder(dedup, merge_mode, options));
589        }
590
591        if primary_key_encoding == PrimaryKeyEncoding::Sparse {
592            if options.memtable.is_some()
593                && !matches!(&options.memtable, Some(MemtableOptions::Bulk(_)))
594            {
595                common_telemetry::info!(
596                    "Overriding memtable config, use BulkMemtable for sparse primary key encoding"
597                );
598            }
599            return Arc::new(self.bulk_memtable_builder(dedup, merge_mode, options));
600        }
601
602        // The format is not flat.
603        match &options.memtable {
604            Some(MemtableOptions::Bulk(config)) => Arc::new(
605                BulkMemtableBuilder::new(self.write_buffer_manager.clone(), !dedup, merge_mode)
606                    .with_config(config.clone())
607                    .with_row_group_size(options.row_group_size())
608                    .with_float_field_encoding(options.float_field_encoding)
609                    .with_narthex_format(
610                        options.sst_format == Some(crate::sst::FormatType::Narthex),
611                    )
612                    .with_compact_dispatcher(self.compact_dispatcher.clone()),
613            ),
614            Some(MemtableOptions::TimeSeries) => Arc::new(TimeSeriesMemtableBuilder::new(
615                self.write_buffer_manager.clone(),
616                dedup,
617                merge_mode,
618            )),
619            None => self.default_primary_key_memtable_builder(dedup, merge_mode),
620        }
621    }
622
623    fn bulk_memtable_builder(
624        &self,
625        dedup: bool,
626        merge_mode: MergeMode,
627        options: &RegionOptions,
628    ) -> BulkMemtableBuilder {
629        let mut builder = BulkMemtableBuilder::new(
630            self.write_buffer_manager.clone(),
631            !dedup, // append_mode: true if not dedup, false if dedup
632            merge_mode,
633        )
634        .with_config(self.default_bulk_memtable_config.clone())
635        .with_row_group_size(options.row_group_size())
636        .with_float_field_encoding(options.float_field_encoding)
637        .with_narthex_format(options.sst_format == Some(crate::sst::FormatType::Narthex))
638        .with_compact_dispatcher(self.compact_dispatcher.clone());
639
640        if let Some(MemtableOptions::Bulk(config)) = &options.memtable {
641            builder = builder.with_config(config.clone());
642        }
643
644        builder
645    }
646
647    fn default_primary_key_memtable_builder(
648        &self,
649        dedup: bool,
650        merge_mode: MergeMode,
651    ) -> MemtableBuilderRef {
652        Arc::new(TimeSeriesMemtableBuilder::new(
653            self.write_buffer_manager.clone(),
654            dedup,
655            merge_mode,
656        ))
657    }
658}
659
660/// Metrics for scanning a memtable.
661#[derive(Clone, Default)]
662pub struct MemScanMetrics(Arc<Mutex<MemScanMetricsData>>);
663
664impl MemScanMetrics {
665    /// Merges the metrics.
666    pub(crate) fn merge_inner(&self, inner: &MemScanMetricsData) {
667        let mut metrics = self.0.lock().unwrap();
668        metrics.total_series += inner.total_series;
669        metrics.num_rows += inner.num_rows;
670        metrics.num_batches += inner.num_batches;
671        metrics.scan_cost += inner.scan_cost;
672        metrics.prefilter_cost += inner.prefilter_cost;
673        metrics.prefilter_rows_filtered += inner.prefilter_rows_filtered;
674    }
675
676    /// Gets the metrics data.
677    pub(crate) fn data(&self) -> MemScanMetricsData {
678        self.0.lock().unwrap().clone()
679    }
680}
681
682#[derive(Clone, Default)]
683pub(crate) struct MemScanMetricsData {
684    /// Total series in the memtable.
685    pub(crate) total_series: usize,
686    /// Number of rows read.
687    pub(crate) num_rows: usize,
688    /// Number of batch read.
689    pub(crate) num_batches: usize,
690    /// Duration to scan the memtable.
691    pub(crate) scan_cost: Duration,
692    /// Duration of prefilter in memtable scan.
693    pub(crate) prefilter_cost: Duration,
694    /// Number of rows filtered by prefilter in memtable scan.
695    pub(crate) prefilter_rows_filtered: usize,
696}
697
698/// Encoded range in the memtable.
699pub struct EncodedRange {
700    /// Encoded file data.
701    pub data: Bytes,
702    /// Metadata of the encoded range.
703    pub sst_info: SstInfo,
704    /// Keeps the write buffer charged for `data`.
705    pub(crate) _charges: Vec<Arc<MemoryCharge>>,
706}
707
708/// Conservative exact-key discovery without decoding sample columns.
709pub type BoxedPrimaryKeyIterator = Box<dyn Iterator<Item = Bytes> + Send>;
710
711/// Builder to build an iterator to read the range.
712/// The builder should know the projection and the predicate to build the iterator.
713pub trait IterBuilder: Send + Sync {
714    /// Returns the iterator to read the range.
715    fn build(&self, metrics: Option<MemScanMetrics>) -> Result<BoxedBatchIterator>;
716
717    /// Returns exact keys directly when the range has a separate key representation.
718    /// Keys may repeat and may include rows excluded by query visibility.
719    fn primary_keys(&self) -> Option<BoxedPrimaryKeyIterator> {
720        None
721    }
722
723    /// Returns whether the iterator is a record batch iterator.
724    fn is_record_batch(&self) -> bool {
725        false
726    }
727
728    /// Returns the record batch iterator to read the range.
729    /// ## Note
730    /// Implementations should ensure the iterator yields data within given time range.
731    fn build_record_batch(
732        &self,
733        time_range: Option<(Timestamp, Timestamp)>,
734        metrics: Option<MemScanMetrics>,
735    ) -> Result<BoxedRecordBatchIterator> {
736        let _metrics = metrics;
737        let _ = time_range;
738        UnsupportedOperationSnafu {
739            err_msg: "Record batch iterator is not supported by this memtable",
740        }
741        .fail()
742    }
743
744    /// Returns a cheap schema hint for record batches yielded by this builder.
745    fn record_batch_schema_hint(&self) -> Option<SchemaRef> {
746        None
747    }
748
749    /// Returns the [EncodedRange] if the range is already encoded into SST.
750    fn encoded_range(&self) -> Option<EncodedRange> {
751        None
752    }
753}
754
755pub type BoxedIterBuilder = Box<dyn IterBuilder>;
756
757/// Computes the column IDs to read based on the projection.
758///
759/// If `projection` is `Some`, returns those column IDs. If `None`, returns all column IDs
760/// from the metadata.
761pub fn read_column_ids_from_projection(
762    metadata: &RegionMetadataRef,
763    projection: Option<&[ColumnId]>,
764) -> Vec<ColumnId> {
765    if let Some(projection) = projection {
766        projection.to_vec()
767    } else {
768        metadata
769            .column_metadatas
770            .iter()
771            .map(|c| c.column_id)
772            .collect()
773    }
774}
775
776/// Context to adapt batch iterators to record batch iterators for flat scan.
777pub struct BatchToRecordBatchContext {
778    metadata: RegionMetadataRef,
779    codec: Arc<dyn PrimaryKeyCodec>,
780    read_column_ids: Vec<ColumnId>,
781}
782
783impl BatchToRecordBatchContext {
784    /// Creates a new context for adapting batch iterators.
785    pub fn new(metadata: RegionMetadataRef, mut read_column_ids: Vec<ColumnId>) -> Self {
786        if read_column_ids.is_empty() {
787            read_column_ids.push(metadata.time_index_column().column_id);
788        }
789
790        let codec = build_primary_key_codec(&metadata);
791        Self {
792            metadata,
793            codec,
794            read_column_ids,
795        }
796    }
797
798    fn adapt_iter(&self, iter: BoxedBatchIterator) -> BoxedRecordBatchIterator {
799        Box::new(BatchToRecordBatchAdapter::new(
800            iter,
801            self.metadata.clone(),
802            self.codec.clone(),
803            &self.read_column_ids,
804        ))
805    }
806}
807
808/// Context shared by ranges of the same memtable.
809pub struct MemtableRangeContext {
810    /// Id of the memtable.
811    id: MemtableId,
812    /// Iterator builder.
813    builder: BoxedIterBuilder,
814    /// All filters.
815    predicate: PredicateGroup,
816    /// Optional context to adapt batch iterators for flat scans.
817    batch_to_record_batch: Option<Arc<BatchToRecordBatchContext>>,
818}
819
820pub type MemtableRangeContextRef = Arc<MemtableRangeContext>;
821
822impl MemtableRangeContext {
823    /// Creates a new [MemtableRangeContext].
824    pub fn new(id: MemtableId, builder: BoxedIterBuilder, predicate: PredicateGroup) -> Self {
825        Self::new_with_batch_to_record_batch(id, builder, predicate, None)
826    }
827
828    /// Creates a new [MemtableRangeContext] with optional adapter context.
829    pub fn new_with_batch_to_record_batch(
830        id: MemtableId,
831        builder: BoxedIterBuilder,
832        predicate: PredicateGroup,
833        batch_to_record_batch: Option<Arc<BatchToRecordBatchContext>>,
834    ) -> Self {
835        Self {
836            id,
837            builder,
838            predicate,
839            batch_to_record_batch,
840        }
841    }
842}
843
844/// A range in the memtable.
845#[derive(Clone)]
846pub struct MemtableRange {
847    /// Shared context.
848    context: MemtableRangeContextRef,
849    /// Statistics for this memtable range.
850    stats: MemtableStats,
851}
852
853impl MemtableRange {
854    /// Creates a new range from context and stats.
855    pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self {
856        Self { context, stats }
857    }
858
859    /// Returns the statistics for this range.
860    pub fn stats(&self) -> &MemtableStats {
861        &self.stats
862    }
863
864    /// Returns the id of the memtable to read.
865    pub fn id(&self) -> MemtableId {
866        self.context.id
867    }
868
869    /// Builds an iterator to read the range.
870    /// Filters the result by the specific time range, this ensures memtable won't return
871    /// rows out of the time range when new rows are inserted.
872    pub fn build_prune_iter(
873        &self,
874        time_range: FileTimeRange,
875        metrics: Option<MemScanMetrics>,
876    ) -> Result<BoxedBatchIterator> {
877        let iter = self.context.builder.build(metrics)?;
878        let time_filters = self.context.predicate.time_filters();
879        Ok(Box::new(PruneTimeIterator::new(
880            iter,
881            time_range,
882            time_filters,
883        )))
884    }
885
886    pub(crate) fn primary_keys(&self) -> Option<BoxedPrimaryKeyIterator> {
887        self.context.builder.primary_keys()
888    }
889
890    /// Builds an iterator to read all rows in range.
891    pub fn build_iter(&self) -> Result<BoxedBatchIterator> {
892        self.context.builder.build(None)
893    }
894
895    /// Builds a record batch iterator to read rows in range.
896    ///
897    /// For mutable memtables (adapter path), applies time-range pruning to ensure rows
898    /// outside the time range are filtered, matching the behavior of `build_prune_iter`.
899    pub fn build_record_batch_iter(
900        &self,
901        time_range: Option<FileTimeRange>,
902        metrics: Option<MemScanMetrics>,
903    ) -> Result<BoxedRecordBatchIterator> {
904        if self.context.builder.is_record_batch() {
905            return self.context.builder.build_record_batch(time_range, metrics);
906        }
907
908        if let Some(context) = self.context.batch_to_record_batch.as_ref() {
909            let iter = self.context.builder.build(metrics)?;
910            let iter: BoxedBatchIterator = if let Some(time_range) = time_range {
911                let time_filters = self.context.predicate.time_filters();
912                Box::new(PruneTimeIterator::new(iter, time_range, time_filters))
913            } else {
914                iter
915            };
916            return Ok(context.adapt_iter(iter));
917        }
918
919        UnsupportedOperationSnafu {
920            err_msg: "Record batch iterator is not supported by this memtable",
921        }
922        .fail()
923    }
924
925    /// Returns a cheap schema hint for record batches yielded by this range.
926    pub fn record_batch_schema_hint(&self) -> Option<SchemaRef> {
927        self.context.builder.record_batch_schema_hint()
928    }
929
930    /// Returns whether the iterator is a record batch iterator.
931    pub fn is_record_batch(&self) -> bool {
932        self.context.builder.is_record_batch()
933    }
934
935    pub fn num_rows(&self) -> usize {
936        self.stats.num_rows
937    }
938
939    /// Returns the encoded range if available.
940    pub fn encoded(&self) -> Option<EncodedRange> {
941        self.context.builder.encoded_range()
942    }
943}
944
945#[cfg(test)]
946mod tests {
947    use std::collections::HashMap;
948    use std::sync::Arc;
949
950    use common_base::readable_size::ReadableSize;
951    use common_error::ext::WhateverResult;
952    use datatypes::prelude::ConcreteDataType;
953    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
954    use store_api::metadata::RegionMetadataBuilder;
955    use store_api::storage::RegionId;
956
957    use super::*;
958    use crate::flush::{WriteBufferManager, WriteBufferManagerImpl};
959    use crate::memtable::bulk::BulkMemtableConfig;
960    use crate::test_util::sst_util::sst_region_metadata;
961
962    #[test]
963    fn test_alloc_tracker_without_manager() {
964        let tracker = AllocTracker::new(None);
965        assert_eq!(0, tracker.bytes_allocated());
966        tracker.on_allocation(100);
967        assert_eq!(100, tracker.bytes_allocated());
968        tracker.on_allocation(200);
969        assert_eq!(300, tracker.bytes_allocated());
970
971        tracker.done_allocating();
972        assert_eq!(300, tracker.bytes_allocated());
973    }
974
975    #[test]
976    fn test_alloc_tracker_with_manager() {
977        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
978        {
979            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
980
981            tracker.on_allocation(100);
982            assert_eq!(100, tracker.bytes_allocated());
983            assert_eq!(100, manager.memory_usage());
984            assert_eq!(100, manager.mutable_usage());
985
986            for _ in 0..2 {
987                // Done allocating won't free the same memory multiple times.
988                tracker.done_allocating();
989                assert_eq!(100, manager.memory_usage());
990                assert_eq!(0, manager.mutable_usage());
991            }
992        }
993
994        assert_eq!(0, manager.memory_usage());
995        assert_eq!(0, manager.mutable_usage());
996    }
997
998    #[test]
999    fn test_memory_charge_before_and_after_freezing() {
1000        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1001        let tracker = Arc::new(AllocTracker::new(Some(
1002            manager.clone() as WriteBufferManagerRef
1003        )));
1004        let mutable = tracker.charge(100);
1005        let released_after_freeze = tracker.charge(60);
1006        assert_eq!(160, manager.memory_usage());
1007        assert_eq!(160, manager.mutable_usage());
1008        // Releasing a mutable charge frees both its total and its mutable usage.
1009        drop(mutable);
1010        assert_eq!(60, manager.mutable_usage());
1011
1012        tracker.done_allocating();
1013        assert_eq!(0, manager.mutable_usage());
1014        // Charges taken or released after freezing only change the total usage.
1015        let frozen = tracker.charge(30);
1016        drop(released_after_freeze);
1017        assert_eq!(30, tracker.bytes_allocated());
1018        assert_eq!(30, manager.memory_usage());
1019        assert_eq!(0, manager.mutable_usage());
1020
1021        // A charge outlives the tracker's owner and keeps the memory charged.
1022        drop(tracker);
1023        assert_eq!(30, manager.memory_usage());
1024        drop(frozen);
1025        assert_eq!(0, manager.memory_usage());
1026        assert_eq!(0, manager.mutable_usage());
1027    }
1028
1029    #[test]
1030    fn test_alloc_tracker_without_done_allocating() {
1031        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1032        {
1033            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
1034
1035            tracker.on_allocation(100);
1036            assert_eq!(100, tracker.bytes_allocated());
1037            assert_eq!(100, manager.memory_usage());
1038            assert_eq!(100, manager.mutable_usage());
1039        }
1040
1041        assert_eq!(0, manager.memory_usage());
1042        assert_eq!(0, manager.mutable_usage());
1043    }
1044
1045    #[test]
1046    fn test_forced_bulk_memtable_preserves_bulk_config() {
1047        let provider = MemtableBuilderProvider::new(
1048            None,
1049            Arc::new(MitoConfig::default()),
1050            Arc::new(CompactDispatcher::new(1)),
1051        );
1052        let config = BulkMemtableConfig {
1053            merge_threshold: 7,
1054            encode_row_threshold: 11,
1055            encode_bytes_threshold: 13,
1056            max_merge_groups: 17,
1057        };
1058        let options = RegionOptions {
1059            memtable: Some(MemtableOptions::Bulk(config.clone())),
1060            primary_key_encoding: Some(PrimaryKeyEncoding::Sparse),
1061            ..Default::default()
1062        };
1063
1064        let builder =
1065            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1066
1067        assert_eq!(&config, builder.config());
1068    }
1069
1070    #[test]
1071    fn test_provider_uses_adaptive_config_for_implicit_bulk_builder() {
1072        let config = MitoConfig {
1073            global_write_buffer_size: ReadableSize::gb(8),
1074            ..Default::default()
1075        };
1076        let provider = MemtableBuilderProvider::new(
1077            None,
1078            Arc::new(config),
1079            Arc::new(CompactDispatcher::new(1)),
1080        );
1081        let options = RegionOptions::default();
1082
1083        let builder =
1084            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1085
1086        assert_eq!(256 * 1024 * 1024, builder.config().encode_bytes_threshold);
1087    }
1088
1089    #[test]
1090    fn test_provider_parses_bulk_memtable_with_adaptive_config() {
1091        let config = MitoConfig {
1092            global_write_buffer_size: ReadableSize::gb(8),
1093            ..Default::default()
1094        };
1095        let provider = MemtableBuilderProvider::new(
1096            None,
1097            Arc::new(config),
1098            Arc::new(CompactDispatcher::new(1)),
1099        );
1100        let options = HashMap::from([("memtable.type".to_string(), "bulk".to_string())]);
1101
1102        let options = provider
1103            .parse_options(RegionId::new(0, 0), &options)
1104            .unwrap();
1105
1106        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1107            panic!("expected bulk memtable options");
1108        };
1109        assert_eq!(256 * 1024 * 1024, config.encode_bytes_threshold);
1110    }
1111
1112    #[test]
1113    fn test_provider_preserves_explicit_bulk_encode_bytes_threshold() {
1114        let config = MitoConfig {
1115            global_write_buffer_size: ReadableSize::gb(8),
1116            ..Default::default()
1117        };
1118        let provider = MemtableBuilderProvider::new(
1119            None,
1120            Arc::new(config),
1121            Arc::new(CompactDispatcher::new(1)),
1122        );
1123        let options = HashMap::from([
1124            ("memtable.type".to_string(), "bulk".to_string()),
1125            (
1126                "memtable.bulk.encode_bytes_threshold".to_string(),
1127                "13".to_string(),
1128            ),
1129        ]);
1130
1131        let options = provider
1132            .parse_options(RegionId::new(0, 0), &options)
1133            .unwrap();
1134
1135        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1136            panic!("expected bulk memtable options");
1137        };
1138        assert_eq!(13, config.encode_bytes_threshold);
1139    }
1140
1141    #[test]
1142    fn test_json2_requires_flat_format() -> WhateverResult<()> {
1143        let mut metadata = sst_region_metadata();
1144        metadata.column_metadatas[2].column_schema.data_type =
1145            ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
1146        let metadata = RegionMetadataBuilder::from_existing(metadata).build()?;
1147        let mut options = RegionOptions {
1148            sst_format: Some(FormatType::PrimaryKey),
1149            memtable: Some(MemtableOptions::TimeSeries),
1150            ..Default::default()
1151        };
1152
1153        let err = ensure_json2_uses_flat_format(&metadata, &options).unwrap_err();
1154        assert!(
1155            err.to_string()
1156                .contains("JSON2 columns require sst_format=flat")
1157        );
1158
1159        options.memtable = None;
1160        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1161
1162        options.memtable = Some(MemtableOptions::Bulk(BulkMemtableConfig::default()));
1163        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1164
1165        options.memtable = Some(MemtableOptions::TimeSeries);
1166        options.sst_format = Some(FormatType::Flat);
1167        ensure_json2_uses_flat_format(&metadata, &options)?;
1168
1169        options.sst_format = Some(FormatType::PrimaryKey);
1170        options.primary_key_encoding = Some(PrimaryKeyEncoding::Sparse);
1171        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1172
1173        options.sst_format = Some(FormatType::Flat);
1174        ensure_json2_uses_flat_format(&metadata, &options)?;
1175        Ok(())
1176    }
1177}