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
698pub(crate) enum EncodedData {
699    Parquet(Bytes),
700    Narthex(crate::series_index::samples::bulk::NarthexBulkPart),
701}
702
703/// Encoded range in the memtable.
704pub struct EncodedRange {
705    /// Encoded file data.
706    pub(crate) data: EncodedData,
707    /// Metadata of the encoded range.
708    pub sst_info: SstInfo,
709    /// Keeps the write buffer charged for `data`.
710    pub(crate) _charges: Vec<Arc<MemoryCharge>>,
711}
712
713impl EncodedRange {
714    /// Returns the serialized bytes of a Parquet range.
715    pub fn parquet_data(&self) -> Option<&Bytes> {
716        match &self.data {
717            EncodedData::Parquet(bytes) => Some(bytes),
718            EncodedData::Narthex(_) => None,
719        }
720    }
721}
722
723/// Conservative exact-key discovery without decoding sample columns.
724pub type BoxedPrimaryKeyIterator = Box<dyn Iterator<Item = Bytes> + Send>;
725
726/// Builder to build an iterator to read the range.
727/// The builder should know the projection and the predicate to build the iterator.
728pub trait IterBuilder: Send + Sync {
729    /// Returns the iterator to read the range.
730    fn build(&self, metrics: Option<MemScanMetrics>) -> Result<BoxedBatchIterator>;
731
732    /// Returns exact keys directly when the range has a separate key representation.
733    /// Keys may repeat and may include rows excluded by query visibility.
734    fn primary_keys(&self) -> Option<BoxedPrimaryKeyIterator> {
735        None
736    }
737
738    /// Returns whether the iterator is a record batch iterator.
739    fn is_record_batch(&self) -> bool {
740        false
741    }
742
743    /// Returns the record batch iterator to read the range.
744    /// ## Note
745    /// Implementations should ensure the iterator yields data within given time range.
746    fn build_record_batch(
747        &self,
748        time_range: Option<(Timestamp, Timestamp)>,
749        metrics: Option<MemScanMetrics>,
750    ) -> Result<BoxedRecordBatchIterator> {
751        let _metrics = metrics;
752        let _ = time_range;
753        UnsupportedOperationSnafu {
754            err_msg: "Record batch iterator is not supported by this memtable",
755        }
756        .fail()
757    }
758
759    /// Returns a cheap schema hint for record batches yielded by this builder.
760    fn record_batch_schema_hint(&self) -> Option<SchemaRef> {
761        None
762    }
763
764    /// Returns the [EncodedRange] if the range is already encoded into SST.
765    fn encoded_range(&self) -> Option<EncodedRange> {
766        None
767    }
768}
769
770pub type BoxedIterBuilder = Box<dyn IterBuilder>;
771
772/// Computes the column IDs to read based on the projection.
773///
774/// If `projection` is `Some`, returns those column IDs. If `None`, returns all column IDs
775/// from the metadata.
776pub fn read_column_ids_from_projection(
777    metadata: &RegionMetadataRef,
778    projection: Option<&[ColumnId]>,
779) -> Vec<ColumnId> {
780    if let Some(projection) = projection {
781        projection.to_vec()
782    } else {
783        metadata
784            .column_metadatas
785            .iter()
786            .map(|c| c.column_id)
787            .collect()
788    }
789}
790
791/// Context to adapt batch iterators to record batch iterators for flat scan.
792pub struct BatchToRecordBatchContext {
793    metadata: RegionMetadataRef,
794    codec: Arc<dyn PrimaryKeyCodec>,
795    read_column_ids: Vec<ColumnId>,
796}
797
798impl BatchToRecordBatchContext {
799    /// Creates a new context for adapting batch iterators.
800    pub fn new(metadata: RegionMetadataRef, mut read_column_ids: Vec<ColumnId>) -> Self {
801        if read_column_ids.is_empty() {
802            read_column_ids.push(metadata.time_index_column().column_id);
803        }
804
805        let codec = build_primary_key_codec(&metadata);
806        Self {
807            metadata,
808            codec,
809            read_column_ids,
810        }
811    }
812
813    fn adapt_iter(&self, iter: BoxedBatchIterator) -> BoxedRecordBatchIterator {
814        Box::new(BatchToRecordBatchAdapter::new(
815            iter,
816            self.metadata.clone(),
817            self.codec.clone(),
818            &self.read_column_ids,
819        ))
820    }
821}
822
823/// Context shared by ranges of the same memtable.
824pub struct MemtableRangeContext {
825    /// Id of the memtable.
826    id: MemtableId,
827    /// Iterator builder.
828    builder: BoxedIterBuilder,
829    /// All filters.
830    predicate: PredicateGroup,
831    /// Optional context to adapt batch iterators for flat scans.
832    batch_to_record_batch: Option<Arc<BatchToRecordBatchContext>>,
833}
834
835pub type MemtableRangeContextRef = Arc<MemtableRangeContext>;
836
837impl MemtableRangeContext {
838    /// Creates a new [MemtableRangeContext].
839    pub fn new(id: MemtableId, builder: BoxedIterBuilder, predicate: PredicateGroup) -> Self {
840        Self::new_with_batch_to_record_batch(id, builder, predicate, None)
841    }
842
843    /// Creates a new [MemtableRangeContext] with optional adapter context.
844    pub fn new_with_batch_to_record_batch(
845        id: MemtableId,
846        builder: BoxedIterBuilder,
847        predicate: PredicateGroup,
848        batch_to_record_batch: Option<Arc<BatchToRecordBatchContext>>,
849    ) -> Self {
850        Self {
851            id,
852            builder,
853            predicate,
854            batch_to_record_batch,
855        }
856    }
857}
858
859/// A range in the memtable.
860#[derive(Clone)]
861pub struct MemtableRange {
862    /// Shared context.
863    context: MemtableRangeContextRef,
864    /// Statistics for this memtable range.
865    stats: MemtableStats,
866}
867
868impl MemtableRange {
869    /// Creates a new range from context and stats.
870    pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self {
871        Self { context, stats }
872    }
873
874    /// Returns the statistics for this range.
875    pub fn stats(&self) -> &MemtableStats {
876        &self.stats
877    }
878
879    /// Returns the id of the memtable to read.
880    pub fn id(&self) -> MemtableId {
881        self.context.id
882    }
883
884    /// Builds an iterator to read the range.
885    /// Filters the result by the specific time range, this ensures memtable won't return
886    /// rows out of the time range when new rows are inserted.
887    pub fn build_prune_iter(
888        &self,
889        time_range: FileTimeRange,
890        metrics: Option<MemScanMetrics>,
891    ) -> Result<BoxedBatchIterator> {
892        let iter = self.context.builder.build(metrics)?;
893        let time_filters = self.context.predicate.time_filters();
894        Ok(Box::new(PruneTimeIterator::new(
895            iter,
896            time_range,
897            time_filters,
898        )))
899    }
900
901    pub(crate) fn primary_keys(&self) -> Option<BoxedPrimaryKeyIterator> {
902        self.context.builder.primary_keys()
903    }
904
905    /// Builds an iterator to read all rows in range.
906    pub fn build_iter(&self) -> Result<BoxedBatchIterator> {
907        self.context.builder.build(None)
908    }
909
910    /// Builds a record batch iterator to read rows in range.
911    ///
912    /// For mutable memtables (adapter path), applies time-range pruning to ensure rows
913    /// outside the time range are filtered, matching the behavior of `build_prune_iter`.
914    pub fn build_record_batch_iter(
915        &self,
916        time_range: Option<FileTimeRange>,
917        metrics: Option<MemScanMetrics>,
918    ) -> Result<BoxedRecordBatchIterator> {
919        if self.context.builder.is_record_batch() {
920            return self.context.builder.build_record_batch(time_range, metrics);
921        }
922
923        if let Some(context) = self.context.batch_to_record_batch.as_ref() {
924            let iter = self.context.builder.build(metrics)?;
925            let iter: BoxedBatchIterator = if let Some(time_range) = time_range {
926                let time_filters = self.context.predicate.time_filters();
927                Box::new(PruneTimeIterator::new(iter, time_range, time_filters))
928            } else {
929                iter
930            };
931            return Ok(context.adapt_iter(iter));
932        }
933
934        UnsupportedOperationSnafu {
935            err_msg: "Record batch iterator is not supported by this memtable",
936        }
937        .fail()
938    }
939
940    /// Returns a cheap schema hint for record batches yielded by this range.
941    pub fn record_batch_schema_hint(&self) -> Option<SchemaRef> {
942        self.context.builder.record_batch_schema_hint()
943    }
944
945    /// Returns whether the iterator is a record batch iterator.
946    pub fn is_record_batch(&self) -> bool {
947        self.context.builder.is_record_batch()
948    }
949
950    pub fn num_rows(&self) -> usize {
951        self.stats.num_rows
952    }
953
954    /// Returns the encoded range if available.
955    pub fn encoded(&self) -> Option<EncodedRange> {
956        self.context.builder.encoded_range()
957    }
958}
959
960#[cfg(test)]
961mod tests {
962    use std::collections::HashMap;
963    use std::sync::Arc;
964
965    use common_base::readable_size::ReadableSize;
966    use common_error::ext::WhateverResult;
967    use datatypes::prelude::ConcreteDataType;
968    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
969    use store_api::metadata::RegionMetadataBuilder;
970    use store_api::storage::RegionId;
971
972    use super::*;
973    use crate::flush::{WriteBufferManager, WriteBufferManagerImpl};
974    use crate::memtable::bulk::BulkMemtableConfig;
975    use crate::test_util::sst_util::sst_region_metadata;
976
977    #[test]
978    fn test_alloc_tracker_without_manager() {
979        let tracker = AllocTracker::new(None);
980        assert_eq!(0, tracker.bytes_allocated());
981        tracker.on_allocation(100);
982        assert_eq!(100, tracker.bytes_allocated());
983        tracker.on_allocation(200);
984        assert_eq!(300, tracker.bytes_allocated());
985
986        tracker.done_allocating();
987        assert_eq!(300, tracker.bytes_allocated());
988    }
989
990    #[test]
991    fn test_alloc_tracker_with_manager() {
992        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
993        {
994            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
995
996            tracker.on_allocation(100);
997            assert_eq!(100, tracker.bytes_allocated());
998            assert_eq!(100, manager.memory_usage());
999            assert_eq!(100, manager.mutable_usage());
1000
1001            for _ in 0..2 {
1002                // Done allocating won't free the same memory multiple times.
1003                tracker.done_allocating();
1004                assert_eq!(100, manager.memory_usage());
1005                assert_eq!(0, manager.mutable_usage());
1006            }
1007        }
1008
1009        assert_eq!(0, manager.memory_usage());
1010        assert_eq!(0, manager.mutable_usage());
1011    }
1012
1013    #[test]
1014    fn test_memory_charge_before_and_after_freezing() {
1015        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1016        let tracker = Arc::new(AllocTracker::new(Some(
1017            manager.clone() as WriteBufferManagerRef
1018        )));
1019        let mutable = tracker.charge(100);
1020        let released_after_freeze = tracker.charge(60);
1021        assert_eq!(160, manager.memory_usage());
1022        assert_eq!(160, manager.mutable_usage());
1023        // Releasing a mutable charge frees both its total and its mutable usage.
1024        drop(mutable);
1025        assert_eq!(60, manager.mutable_usage());
1026
1027        tracker.done_allocating();
1028        assert_eq!(0, manager.mutable_usage());
1029        // Charges taken or released after freezing only change the total usage.
1030        let frozen = tracker.charge(30);
1031        drop(released_after_freeze);
1032        assert_eq!(30, tracker.bytes_allocated());
1033        assert_eq!(30, manager.memory_usage());
1034        assert_eq!(0, manager.mutable_usage());
1035
1036        // A charge outlives the tracker's owner and keeps the memory charged.
1037        drop(tracker);
1038        assert_eq!(30, manager.memory_usage());
1039        drop(frozen);
1040        assert_eq!(0, manager.memory_usage());
1041        assert_eq!(0, manager.mutable_usage());
1042    }
1043
1044    #[test]
1045    fn test_alloc_tracker_without_done_allocating() {
1046        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1047        {
1048            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
1049
1050            tracker.on_allocation(100);
1051            assert_eq!(100, tracker.bytes_allocated());
1052            assert_eq!(100, manager.memory_usage());
1053            assert_eq!(100, manager.mutable_usage());
1054        }
1055
1056        assert_eq!(0, manager.memory_usage());
1057        assert_eq!(0, manager.mutable_usage());
1058    }
1059
1060    #[test]
1061    fn test_forced_bulk_memtable_preserves_bulk_config() {
1062        let provider = MemtableBuilderProvider::new(
1063            None,
1064            Arc::new(MitoConfig::default()),
1065            Arc::new(CompactDispatcher::new(1)),
1066        );
1067        let config = BulkMemtableConfig {
1068            merge_threshold: 7,
1069            encode_row_threshold: 11,
1070            encode_bytes_threshold: 13,
1071            max_merge_groups: 17,
1072        };
1073        let options = RegionOptions {
1074            memtable: Some(MemtableOptions::Bulk(config.clone())),
1075            primary_key_encoding: Some(PrimaryKeyEncoding::Sparse),
1076            ..Default::default()
1077        };
1078
1079        let builder =
1080            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1081
1082        assert_eq!(&config, builder.config());
1083    }
1084
1085    #[test]
1086    fn test_provider_uses_adaptive_config_for_implicit_bulk_builder() {
1087        let config = MitoConfig {
1088            global_write_buffer_size: ReadableSize::gb(8),
1089            ..Default::default()
1090        };
1091        let provider = MemtableBuilderProvider::new(
1092            None,
1093            Arc::new(config),
1094            Arc::new(CompactDispatcher::new(1)),
1095        );
1096        let options = RegionOptions::default();
1097
1098        let builder =
1099            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1100
1101        assert_eq!(256 * 1024 * 1024, builder.config().encode_bytes_threshold);
1102    }
1103
1104    #[test]
1105    fn test_provider_parses_bulk_memtable_with_adaptive_config() {
1106        let config = MitoConfig {
1107            global_write_buffer_size: ReadableSize::gb(8),
1108            ..Default::default()
1109        };
1110        let provider = MemtableBuilderProvider::new(
1111            None,
1112            Arc::new(config),
1113            Arc::new(CompactDispatcher::new(1)),
1114        );
1115        let options = HashMap::from([("memtable.type".to_string(), "bulk".to_string())]);
1116
1117        let options = provider
1118            .parse_options(RegionId::new(0, 0), &options)
1119            .unwrap();
1120
1121        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1122            panic!("expected bulk memtable options");
1123        };
1124        assert_eq!(256 * 1024 * 1024, config.encode_bytes_threshold);
1125    }
1126
1127    #[test]
1128    fn test_provider_preserves_explicit_bulk_encode_bytes_threshold() {
1129        let config = MitoConfig {
1130            global_write_buffer_size: ReadableSize::gb(8),
1131            ..Default::default()
1132        };
1133        let provider = MemtableBuilderProvider::new(
1134            None,
1135            Arc::new(config),
1136            Arc::new(CompactDispatcher::new(1)),
1137        );
1138        let options = HashMap::from([
1139            ("memtable.type".to_string(), "bulk".to_string()),
1140            (
1141                "memtable.bulk.encode_bytes_threshold".to_string(),
1142                "13".to_string(),
1143            ),
1144        ]);
1145
1146        let options = provider
1147            .parse_options(RegionId::new(0, 0), &options)
1148            .unwrap();
1149
1150        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1151            panic!("expected bulk memtable options");
1152        };
1153        assert_eq!(13, config.encode_bytes_threshold);
1154    }
1155
1156    #[test]
1157    fn test_json2_requires_flat_format() -> WhateverResult<()> {
1158        let mut metadata = sst_region_metadata();
1159        metadata.column_metadatas[2].column_schema.data_type =
1160            ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
1161        let metadata = RegionMetadataBuilder::from_existing(metadata).build()?;
1162        let mut options = RegionOptions {
1163            sst_format: Some(FormatType::PrimaryKey),
1164            memtable: Some(MemtableOptions::TimeSeries),
1165            ..Default::default()
1166        };
1167
1168        let err = ensure_json2_uses_flat_format(&metadata, &options).unwrap_err();
1169        assert!(
1170            err.to_string()
1171                .contains("JSON2 columns require sst_format=flat")
1172        );
1173
1174        options.memtable = None;
1175        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1176
1177        options.memtable = Some(MemtableOptions::Bulk(BulkMemtableConfig::default()));
1178        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1179
1180        options.memtable = Some(MemtableOptions::TimeSeries);
1181        options.sst_format = Some(FormatType::Flat);
1182        ensure_json2_uses_flat_format(&metadata, &options)?;
1183
1184        options.sst_format = Some(FormatType::PrimaryKey);
1185        options.primary_key_encoding = Some(PrimaryKeyEncoding::Sparse);
1186        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1187
1188        options.sst_format = Some(FormatType::Flat);
1189        ensure_json2_uses_flat_format(&metadata, &options)?;
1190        Ok(())
1191    }
1192}