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    /// Inclusive time range of every row the range can yield, set only when
867    /// the range reads content captured when it was built.
868    captured_time_range: Option<(Timestamp, Timestamp)>,
869}
870
871impl MemtableRange {
872    /// Creates a new range from context and stats.
873    pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self {
874        Self {
875            context,
876            stats,
877            captured_time_range: None,
878        }
879    }
880
881    /// Marks the range as reading immutable content captured when it was
882    /// built, whose rows all lie in the inclusive `time_range`. Writes after
883    /// that never reach the range.
884    #[must_use]
885    pub(crate) fn with_captured_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self {
886        self.captured_time_range = Some(time_range);
887        self
888    }
889
890    /// Returns the statistics for this range.
891    pub fn stats(&self) -> &MemtableStats {
892        &self.stats
893    }
894
895    /// Returns the inclusive time range of the captured content, if the range
896    /// reads only content captured when it was built.
897    pub(crate) fn captured_time_range(&self) -> Option<(Timestamp, Timestamp)> {
898        self.captured_time_range
899    }
900
901    /// Returns the id of the memtable to read.
902    pub fn id(&self) -> MemtableId {
903        self.context.id
904    }
905
906    /// Builds an iterator to read the range.
907    /// Filters the result by the specific time range, this ensures memtable won't return
908    /// rows out of the time range when new rows are inserted.
909    pub fn build_prune_iter(
910        &self,
911        time_range: FileTimeRange,
912        metrics: Option<MemScanMetrics>,
913    ) -> Result<BoxedBatchIterator> {
914        let iter = self.context.builder.build(metrics)?;
915        let time_filters = self.context.predicate.time_filters();
916        Ok(Box::new(PruneTimeIterator::new(
917            iter,
918            time_range,
919            time_filters,
920        )))
921    }
922
923    pub(crate) fn primary_keys(&self) -> Option<BoxedPrimaryKeyIterator> {
924        self.context.builder.primary_keys()
925    }
926
927    /// Builds an iterator to read all rows in range.
928    pub fn build_iter(&self) -> Result<BoxedBatchIterator> {
929        self.context.builder.build(None)
930    }
931
932    /// Builds a record batch iterator to read rows in range.
933    ///
934    /// For mutable memtables (adapter path), applies time-range pruning to ensure rows
935    /// outside the time range are filtered, matching the behavior of `build_prune_iter`.
936    pub fn build_record_batch_iter(
937        &self,
938        time_range: Option<FileTimeRange>,
939        metrics: Option<MemScanMetrics>,
940    ) -> Result<BoxedRecordBatchIterator> {
941        if self.context.builder.is_record_batch() {
942            return self.context.builder.build_record_batch(time_range, metrics);
943        }
944
945        if let Some(context) = self.context.batch_to_record_batch.as_ref() {
946            let iter = self.context.builder.build(metrics)?;
947            let iter: BoxedBatchIterator = if let Some(time_range) = time_range {
948                let time_filters = self.context.predicate.time_filters();
949                Box::new(PruneTimeIterator::new(iter, time_range, time_filters))
950            } else {
951                iter
952            };
953            return Ok(context.adapt_iter(iter));
954        }
955
956        UnsupportedOperationSnafu {
957            err_msg: "Record batch iterator is not supported by this memtable",
958        }
959        .fail()
960    }
961
962    /// Returns a cheap schema hint for record batches yielded by this range.
963    pub fn record_batch_schema_hint(&self) -> Option<SchemaRef> {
964        self.context.builder.record_batch_schema_hint()
965    }
966
967    /// Returns whether the iterator is a record batch iterator.
968    pub fn is_record_batch(&self) -> bool {
969        self.context.builder.is_record_batch()
970    }
971
972    pub fn num_rows(&self) -> usize {
973        self.stats.num_rows
974    }
975
976    /// Returns the encoded range if available.
977    pub fn encoded(&self) -> Option<EncodedRange> {
978        self.context.builder.encoded_range()
979    }
980}
981
982#[cfg(test)]
983mod tests {
984    use std::collections::HashMap;
985    use std::sync::Arc;
986
987    use common_base::readable_size::ReadableSize;
988    use common_error::ext::WhateverResult;
989    use datatypes::prelude::ConcreteDataType;
990    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
991    use store_api::metadata::RegionMetadataBuilder;
992    use store_api::storage::RegionId;
993
994    use super::*;
995    use crate::flush::{WriteBufferManager, WriteBufferManagerImpl};
996    use crate::memtable::bulk::BulkMemtableConfig;
997    use crate::test_util::sst_util::sst_region_metadata;
998
999    #[test]
1000    fn test_alloc_tracker_without_manager() {
1001        let tracker = AllocTracker::new(None);
1002        assert_eq!(0, tracker.bytes_allocated());
1003        tracker.on_allocation(100);
1004        assert_eq!(100, tracker.bytes_allocated());
1005        tracker.on_allocation(200);
1006        assert_eq!(300, tracker.bytes_allocated());
1007
1008        tracker.done_allocating();
1009        assert_eq!(300, tracker.bytes_allocated());
1010    }
1011
1012    #[test]
1013    fn test_alloc_tracker_with_manager() {
1014        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1015        {
1016            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
1017
1018            tracker.on_allocation(100);
1019            assert_eq!(100, tracker.bytes_allocated());
1020            assert_eq!(100, manager.memory_usage());
1021            assert_eq!(100, manager.mutable_usage());
1022
1023            for _ in 0..2 {
1024                // Done allocating won't free the same memory multiple times.
1025                tracker.done_allocating();
1026                assert_eq!(100, manager.memory_usage());
1027                assert_eq!(0, manager.mutable_usage());
1028            }
1029        }
1030
1031        assert_eq!(0, manager.memory_usage());
1032        assert_eq!(0, manager.mutable_usage());
1033    }
1034
1035    #[test]
1036    fn test_memory_charge_before_and_after_freezing() {
1037        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1038        let tracker = Arc::new(AllocTracker::new(Some(
1039            manager.clone() as WriteBufferManagerRef
1040        )));
1041        let mutable = tracker.charge(100);
1042        let released_after_freeze = tracker.charge(60);
1043        assert_eq!(160, manager.memory_usage());
1044        assert_eq!(160, manager.mutable_usage());
1045        // Releasing a mutable charge frees both its total and its mutable usage.
1046        drop(mutable);
1047        assert_eq!(60, manager.mutable_usage());
1048
1049        tracker.done_allocating();
1050        assert_eq!(0, manager.mutable_usage());
1051        // Charges taken or released after freezing only change the total usage.
1052        let frozen = tracker.charge(30);
1053        drop(released_after_freeze);
1054        assert_eq!(30, tracker.bytes_allocated());
1055        assert_eq!(30, manager.memory_usage());
1056        assert_eq!(0, manager.mutable_usage());
1057
1058        // A charge outlives the tracker's owner and keeps the memory charged.
1059        drop(tracker);
1060        assert_eq!(30, manager.memory_usage());
1061        drop(frozen);
1062        assert_eq!(0, manager.memory_usage());
1063        assert_eq!(0, manager.mutable_usage());
1064    }
1065
1066    #[test]
1067    fn test_alloc_tracker_without_done_allocating() {
1068        let manager = Arc::new(WriteBufferManagerImpl::new(1000));
1069        {
1070            let tracker = AllocTracker::new(Some(manager.clone() as WriteBufferManagerRef));
1071
1072            tracker.on_allocation(100);
1073            assert_eq!(100, tracker.bytes_allocated());
1074            assert_eq!(100, manager.memory_usage());
1075            assert_eq!(100, manager.mutable_usage());
1076        }
1077
1078        assert_eq!(0, manager.memory_usage());
1079        assert_eq!(0, manager.mutable_usage());
1080    }
1081
1082    #[test]
1083    fn test_forced_bulk_memtable_preserves_bulk_config() {
1084        let provider = MemtableBuilderProvider::new(
1085            None,
1086            Arc::new(MitoConfig::default()),
1087            Arc::new(CompactDispatcher::new(1)),
1088        );
1089        let config = BulkMemtableConfig {
1090            merge_threshold: 7,
1091            encode_row_threshold: 11,
1092            encode_bytes_threshold: 13,
1093            max_merge_groups: 17,
1094        };
1095        let options = RegionOptions {
1096            memtable: Some(MemtableOptions::Bulk(config.clone())),
1097            primary_key_encoding: Some(PrimaryKeyEncoding::Sparse),
1098            ..Default::default()
1099        };
1100
1101        let builder =
1102            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1103
1104        assert_eq!(&config, builder.config());
1105    }
1106
1107    #[test]
1108    fn test_provider_uses_adaptive_config_for_implicit_bulk_builder() {
1109        let config = MitoConfig {
1110            global_write_buffer_size: ReadableSize::gb(8),
1111            ..Default::default()
1112        };
1113        let provider = MemtableBuilderProvider::new(
1114            None,
1115            Arc::new(config),
1116            Arc::new(CompactDispatcher::new(1)),
1117        );
1118        let options = RegionOptions::default();
1119
1120        let builder =
1121            provider.bulk_memtable_builder(options.need_dedup(), options.merge_mode(), &options);
1122
1123        assert_eq!(256 * 1024 * 1024, builder.config().encode_bytes_threshold);
1124    }
1125
1126    #[test]
1127    fn test_provider_parses_bulk_memtable_with_adaptive_config() {
1128        let config = MitoConfig {
1129            global_write_buffer_size: ReadableSize::gb(8),
1130            ..Default::default()
1131        };
1132        let provider = MemtableBuilderProvider::new(
1133            None,
1134            Arc::new(config),
1135            Arc::new(CompactDispatcher::new(1)),
1136        );
1137        let options = HashMap::from([("memtable.type".to_string(), "bulk".to_string())]);
1138
1139        let options = provider
1140            .parse_options(RegionId::new(0, 0), &options)
1141            .unwrap();
1142
1143        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1144            panic!("expected bulk memtable options");
1145        };
1146        assert_eq!(256 * 1024 * 1024, config.encode_bytes_threshold);
1147    }
1148
1149    #[test]
1150    fn test_provider_preserves_explicit_bulk_encode_bytes_threshold() {
1151        let config = MitoConfig {
1152            global_write_buffer_size: ReadableSize::gb(8),
1153            ..Default::default()
1154        };
1155        let provider = MemtableBuilderProvider::new(
1156            None,
1157            Arc::new(config),
1158            Arc::new(CompactDispatcher::new(1)),
1159        );
1160        let options = HashMap::from([
1161            ("memtable.type".to_string(), "bulk".to_string()),
1162            (
1163                "memtable.bulk.encode_bytes_threshold".to_string(),
1164                "13".to_string(),
1165            ),
1166        ]);
1167
1168        let options = provider
1169            .parse_options(RegionId::new(0, 0), &options)
1170            .unwrap();
1171
1172        let Some(MemtableOptions::Bulk(config)) = options.memtable else {
1173            panic!("expected bulk memtable options");
1174        };
1175        assert_eq!(13, config.encode_bytes_threshold);
1176    }
1177
1178    #[test]
1179    fn test_json2_requires_flat_format() -> WhateverResult<()> {
1180        let mut metadata = sst_region_metadata();
1181        metadata.column_metadatas[2].column_schema.data_type =
1182            ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
1183        let metadata = RegionMetadataBuilder::from_existing(metadata).build()?;
1184        let mut options = RegionOptions {
1185            sst_format: Some(FormatType::PrimaryKey),
1186            memtable: Some(MemtableOptions::TimeSeries),
1187            ..Default::default()
1188        };
1189
1190        let err = ensure_json2_uses_flat_format(&metadata, &options).unwrap_err();
1191        assert!(
1192            err.to_string()
1193                .contains("JSON2 columns require sst_format=flat")
1194        );
1195
1196        options.memtable = None;
1197        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1198
1199        options.memtable = Some(MemtableOptions::Bulk(BulkMemtableConfig::default()));
1200        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1201
1202        options.memtable = Some(MemtableOptions::TimeSeries);
1203        options.sst_format = Some(FormatType::Flat);
1204        ensure_json2_uses_flat_format(&metadata, &options)?;
1205
1206        options.sst_format = Some(FormatType::PrimaryKey);
1207        options.primary_key_encoding = Some(PrimaryKeyEncoding::Sparse);
1208        assert!(ensure_json2_uses_flat_format(&metadata, &options).is_err());
1209
1210        options.sst_format = Some(FormatType::Flat);
1211        ensure_json2_uses_flat_format(&metadata, &options)?;
1212        Ok(())
1213    }
1214}