Skip to main content

metric_engine/engine/
bulk_insert.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
15use std::collections::HashSet;
16
17use api::v1::{ArrowIpc, SemanticType};
18use bytes::Bytes;
19use common_error::ext::BoxedError;
20use common_grpc::flight::{FlightEncoder, FlightMessage};
21use datatypes::arrow::record_batch::RecordBatch;
22use mito2::request::check_bulk_insert_batch;
23use snafu::{OptionExt, ResultExt, ensure};
24use store_api::codec::PrimaryKeyEncoding;
25use store_api::metadata::RegionMetadataRef;
26use store_api::region_request::{AffectedRows, RegionBulkInsertsRequest, RegionRequest};
27use store_api::storage::RegionId;
28
29use crate::batch_modifier::{TagColumnInfo, modify_batch_sparse};
30use crate::engine::MetricEngineInner;
31use crate::error;
32use crate::error::Result;
33use crate::metrics::MITO_OPERATION_ELAPSED;
34
35impl MetricEngineInner {
36    /// Bulk-inserts rows into a metric region.
37    ///
38    /// **Logical region path:** The request payload is a logical `RecordBatch`
39    /// (timestamp, value and tag columns). It is transformed to physical format
40    /// via `modify_batch_sparse`, encoded to Arrow IPC, and forwarded as a
41    /// `BulkInserts` request to the data region.
42    ///
43    /// **Physical region path:** The request payload is already in physical format
44    /// (produced by the batcher's `flush_batch_physical`). It is forwarded directly
45    /// to the data region with no transformation.
46    ///
47    /// Returns the number of affected rows, or `0` if the input batch is empty.
48    pub async fn bulk_insert_region(
49        &self,
50        region_id: RegionId,
51        request: RegionBulkInsertsRequest,
52    ) -> Result<AffectedRows> {
53        if request.payload.num_rows() == 0 {
54            return Ok(0);
55        }
56        if self.is_physical_region(region_id) {
57            let _timer = MITO_OPERATION_ELAPSED
58                .with_label_values(&["bulk_insert_physical"])
59                .start_timer();
60            return self.bulk_insert_physical_region(region_id, request).await;
61        }
62
63        let _timer = MITO_OPERATION_ELAPSED
64            .with_label_values(&["bulk_insert_logical"])
65            .start_timer();
66        self.bulk_insert_logical_region(region_id, request).await
67    }
68
69    /// Passthrough for bulk inserts targeting a physical data region.
70    ///
71    /// The batch is already in physical format (with `__primary_key`, timestamp,
72    /// value columns), so no logical-to-physical transformation is needed.
73    async fn bulk_insert_physical_region(
74        &self,
75        region_id: RegionId,
76        mut request: RegionBulkInsertsRequest,
77    ) -> Result<AffectedRows> {
78        // Other logical tables can add fields to the shared physical schema.
79        // Let Mito fill fields absent from this batch before writing it.
80        request.aligned_schema_version = None;
81        self.data_region
82            .write_data(region_id, RegionRequest::BulkInserts(request))
83            .await
84    }
85
86    /// Bulk-inserts logical rows, transforming them to physical format first.
87    async fn bulk_insert_logical_region(
88        &self,
89        region_id: RegionId,
90        request: RegionBulkInsertsRequest,
91    ) -> Result<AffectedRows> {
92        let (physical_region_id, data_region_id, primary_key_encoding) =
93            self.find_data_region_meta(region_id)?;
94
95        if primary_key_encoding != PrimaryKeyEncoding::Sparse {
96            return error::UnsupportedRegionRequestSnafu {
97                request: RegionRequest::BulkInserts(request),
98            }
99            .fail();
100        }
101
102        let batch = request.payload;
103        if batch.num_rows() == 0 {
104            return Ok(0);
105        }
106
107        let logical_metadata = self
108            .logical_region_metadata(physical_region_id, region_id)
109            .await?;
110        let (tag_columns, non_tag_indices) = self.resolve_tag_columns_from_metadata(
111            region_id,
112            data_region_id,
113            &batch,
114            &logical_metadata,
115        )?;
116        // The rewrite below copies columns without checking them, and would encode a
117        // duplicated tag into the primary key twice.
118        check_bulk_insert_batch(&logical_metadata, &batch)
119            .map_err(BoxedError::new)
120            .context(error::MitoWriteOperationSnafu)?;
121        let modified_batch = modify_batch_sparse(
122            batch.clone(),
123            region_id.table_id(),
124            &tag_columns,
125            &non_tag_indices,
126        )?;
127        let (schema, data_header, payload) = record_batch_to_ipc(&modified_batch)?;
128
129        let partition_expr_version = request.partition_expr_version;
130
131        let request = RegionBulkInsertsRequest {
132            skip_wal: request.skip_wal,
133            region_id: data_region_id,
134            payload: modified_batch,
135            raw_data: ArrowIpc {
136                schema,
137                data_header,
138                payload,
139            },
140            partition_expr_version,
141            aligned_schema_version: None,
142        };
143        self.data_region
144            .write_data(data_region_id, RegionRequest::BulkInserts(request))
145            .await
146    }
147
148    fn resolve_tag_columns_from_metadata(
149        &self,
150        logical_region_id: RegionId,
151        data_region_id: RegionId,
152        batch: &RecordBatch,
153        logical_metadata: &RegionMetadataRef,
154    ) -> Result<(Vec<TagColumnInfo>, Vec<usize>)> {
155        let tag_names: HashSet<&str> = logical_metadata
156            .column_metadatas
157            .iter()
158            .filter_map(|column| {
159                if column.semantic_type == SemanticType::Tag {
160                    Some(column.column_schema.name.as_str())
161                } else {
162                    None
163                }
164            })
165            .collect();
166
167        let mut tag_columns = Vec::new();
168        let mut non_tag_indices = Vec::new();
169        {
170            let state = self.state.read().unwrap();
171            let physical_columns = state
172                .physical_region_states()
173                .get(&data_region_id)
174                .context(error::PhysicalRegionNotFoundSnafu {
175                    region_id: data_region_id,
176                })?
177                .physical_columns();
178
179            for (index, field) in batch.schema().fields().iter().enumerate() {
180                let name = field.name();
181                let column_id = physical_columns
182                    .get(name)
183                    .map(|info| info.column_id)
184                    .with_context(|| error::ColumnNotFoundSnafu {
185                        name: name.clone(),
186                        region_id: logical_region_id,
187                    })?;
188                if tag_names.contains(name.as_str()) {
189                    tag_columns.push(TagColumnInfo {
190                        name: name.clone(),
191                        index,
192                        column_id,
193                    });
194                } else {
195                    non_tag_indices.push(index);
196                }
197            }
198        }
199
200        tag_columns.sort_by(|a, b| a.name.cmp(&b.name));
201        Ok((tag_columns, non_tag_indices))
202    }
203}
204
205fn record_batch_to_ipc(record_batch: &RecordBatch) -> Result<(Bytes, Bytes, Bytes)> {
206    let mut encoder = FlightEncoder::default();
207    let schema = encoder.encode_schema(record_batch.schema().as_ref());
208    let mut iter = encoder
209        .encode(FlightMessage::RecordBatch(record_batch.clone()))
210        .into_iter();
211
212    let Some(flight_data) = iter.next() else {
213        return error::UnexpectedRequestSnafu {
214            reason: "Failed to encode empty flight data",
215        }
216        .fail();
217    };
218    ensure!(
219        iter.next().is_none(),
220        error::UnexpectedRequestSnafu {
221            reason: "Bulk insert RecordBatch with dictionary arrays is unsupported".to_string(),
222        }
223    );
224
225    Ok((
226        schema.data_header,
227        flight_data.data_header,
228        flight_data.data_body,
229    ))
230}
231
232#[cfg(test)]
233mod tests {
234    use std::assert_matches;
235    use std::sync::Arc;
236
237    use api::v1::ArrowIpc;
238    use common_error::ext::ErrorExt;
239    use common_query::prelude::{greptime_timestamp, greptime_value};
240    use common_recordbatch::RecordBatches;
241    use datafusion::parquet::basic::Encoding;
242    use datatypes::arrow::array::{Float64Array, StringArray, TimestampMillisecondArray};
243    use datatypes::arrow::datatypes::{DataType, Field, Schema as ArrowSchema, TimeUnit};
244    use datatypes::arrow::record_batch::RecordBatch;
245    use mito2::config::MitoConfig;
246    use mito2::sst::parquet::metadata::MetadataLoader;
247    use mito2::sst::parquet::reader::MetadataCacheMetrics;
248    use store_api::metric_engine_consts::{
249        DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
250        PRIMARY_KEY_ENCODING,
251    };
252    use store_api::mito_engine_options::EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING;
253    use store_api::path_utils::table_dir;
254    use store_api::region_engine::RegionEngine;
255    use store_api::region_request::{
256        PathType, RegionBulkInsertsRequest, RegionCloseRequest, RegionFlushRequest,
257        RegionOpenRequest, RegionPutRequest, RegionRequest,
258    };
259    use store_api::storage::{RegionId, ScanRequest};
260
261    use super::record_batch_to_ipc;
262    use crate::batch_modifier::{TagColumnInfo, modify_batch_sparse};
263    use crate::engine::MetricEngine;
264    use crate::error::Error;
265    use crate::test_util::{self, TestEnv};
266
267    fn build_logical_batch(start: usize, rows: usize) -> RecordBatch {
268        let schema = Arc::new(ArrowSchema::new(vec![
269            Field::new(
270                greptime_timestamp(),
271                DataType::Timestamp(TimeUnit::Millisecond, None),
272                false,
273            ),
274            Field::new(greptime_value(), DataType::Float64, true),
275            Field::new("job", DataType::Utf8, true),
276        ]));
277
278        let mut ts = Vec::with_capacity(rows);
279        let mut values = Vec::with_capacity(rows);
280        let mut tags = Vec::with_capacity(rows);
281        for i in start..start + rows {
282            ts.push(i as i64);
283            values.push(i as f64);
284            tags.push("tag_0".to_string());
285        }
286
287        RecordBatch::try_new(
288            schema,
289            vec![
290                Arc::new(TimestampMillisecondArray::from(ts)),
291                Arc::new(Float64Array::from(values)),
292                Arc::new(StringArray::from(tags)),
293            ],
294        )
295        .unwrap()
296    }
297
298    fn build_bulk_request(
299        logical_region_id: RegionId,
300        batch: RecordBatch,
301        skip_wal: bool,
302    ) -> RegionRequest {
303        let (schema, data_header, payload) = record_batch_to_ipc(&batch).unwrap();
304        RegionRequest::BulkInserts(RegionBulkInsertsRequest {
305            skip_wal,
306            region_id: logical_region_id,
307            payload: batch,
308            raw_data: ArrowIpc {
309                schema,
310                data_header,
311                payload,
312            },
313            partition_expr_version: None,
314            aligned_schema_version: None,
315        })
316    }
317
318    #[tokio::test]
319    async fn test_bulk_insert_rejects_duplicate_tag() {
320        use common_error::status_code::StatusCode;
321
322        let env = TestEnv::new().await;
323        env.init_metric_region().await;
324        let logical_region_id = env.default_logical_region_id();
325
326        let batch = build_logical_batch(0, 2);
327        let mut fields = batch.schema().fields().to_vec();
328        let mut columns = batch.columns().to_vec();
329        fields.push(fields[2].clone());
330        columns.push(columns[2].clone());
331        let batch = RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).unwrap();
332        let err = env
333            .metric()
334            .handle_request(
335                logical_region_id,
336                build_bulk_request(logical_region_id, batch, false),
337            )
338            .await
339            .unwrap_err();
340        assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err:?}");
341    }
342
343    #[tokio::test]
344    async fn test_bulk_insert_physical_region_rejects_malformed_primary_key() {
345        use common_error::status_code::StatusCode;
346        use datatypes::arrow::array::{ArrayRef, BinaryArray, Int64Array};
347        use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
348
349        let env = TestEnv::new().await;
350        env.init_metric_region().await;
351        let physical_region_id = env.default_physical_region_id();
352        let logical_region_id = env.default_logical_region_id();
353        let tag_columns = vec![TagColumnInfo {
354            name: "job".to_string(),
355            index: 2,
356            column_id: 2,
357        }];
358        let batch = modify_batch_sparse(
359            build_logical_batch(0, 2),
360            logical_region_id.table_id(),
361            &tag_columns,
362            &[0, 1],
363        )
364        .unwrap();
365        let primary_key_index = batch.schema().index_of(PRIMARY_KEY_COLUMN_NAME).unwrap();
366        let with_primary_key = |primary_key: Option<ArrayRef>, extra: Option<ArrayRef>| {
367            let mut fields = batch.schema().fields().to_vec();
368            let mut columns = batch.columns().to_vec();
369            fields.remove(primary_key_index);
370            columns.remove(primary_key_index);
371            for array in [primary_key, extra].into_iter().flatten() {
372                fields.push(Arc::new(Field::new(
373                    PRIMARY_KEY_COLUMN_NAME,
374                    array.data_type().clone(),
375                    true,
376                )));
377                columns.push(array);
378            }
379            RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).unwrap()
380        };
381        let encoded = batch.column(primary_key_index).clone();
382        let rejected = [
383            with_primary_key(None, None),
384            with_primary_key(Some(Arc::new(Int64Array::from(vec![1, 2]))), None),
385            with_primary_key(
386                Some(Arc::new(BinaryArray::from_opt_vec(vec![Some(b"a"), None]))),
387                None,
388            ),
389            with_primary_key(Some(encoded.clone()), Some(encoded)),
390        ];
391        for batch in rejected {
392            let err = env
393                .metric()
394                .handle_request(
395                    physical_region_id,
396                    build_bulk_request(physical_region_id, batch, false),
397                )
398                .await
399                .unwrap_err();
400            assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err:?}");
401        }
402    }
403
404    async fn init_dense_metric_region(env: &TestEnv) -> RegionId {
405        let physical_region_id = env.default_physical_region_id();
406        env.create_physical_region(
407            physical_region_id,
408            &TestEnv::default_table_dir(),
409            vec![(PRIMARY_KEY_ENCODING.to_string(), "dense".to_string())],
410        )
411        .await;
412
413        let logical_region_id = env.default_logical_region_id();
414        let request = test_util::create_logical_region_request(
415            &["job"],
416            physical_region_id,
417            &table_dir("test", logical_region_id.table_id()),
418        );
419        env.metric()
420            .handle_request(logical_region_id, RegionRequest::Create(request))
421            .await
422            .unwrap();
423        logical_region_id
424    }
425
426    #[tokio::test]
427    async fn test_bulk_insert_empty_batch_returns_zero() {
428        let env = TestEnv::new().await;
429        env.init_metric_region().await;
430        let logical_region_id = env.default_logical_region_id();
431
432        let batch = build_logical_batch(0, 0);
433        let request = RegionRequest::BulkInserts(RegionBulkInsertsRequest {
434            skip_wal: false,
435            region_id: logical_region_id,
436            payload: batch,
437            raw_data: ArrowIpc::default(),
438            partition_expr_version: None,
439            aligned_schema_version: None,
440        });
441        let response = env
442            .metric()
443            .handle_request(logical_region_id, request)
444            .await
445            .unwrap();
446        assert_eq!(response.affected_rows, 0);
447    }
448
449    #[tokio::test]
450    async fn test_bulk_insert_physical_region_passthrough() {
451        check_bulk_insert_physical_region_passthrough(false, false, false).await;
452        check_bulk_insert_physical_region_passthrough(true, false, false).await;
453    }
454
455    #[tokio::test]
456    async fn test_bulk_insert_physical_region_close_recovery() {
457        check_bulk_insert_physical_region_passthrough(false, true, false).await;
458        check_bulk_insert_physical_region_passthrough(true, true, false).await;
459    }
460
461    #[tokio::test]
462    async fn test_physical_bulk_partition_columns_preserve_stored_rows() {
463        for skip_wal in [false, true] {
464            let stripped =
465                check_bulk_insert_physical_region_passthrough(skip_wal, true, false).await;
466            let retained =
467                check_bulk_insert_physical_region_passthrough(skip_wal, true, true).await;
468            assert_eq!(retained, stripped, "skip_wal={skip_wal}");
469        }
470    }
471
472    async fn check_bulk_insert_physical_region_passthrough(
473        skip_wal: bool,
474        close: bool,
475        retain_partition_columns: bool,
476    ) -> String {
477        // Use flat format so that BulkMemtable is used (supports write_bulk).
478        let mito_config = MitoConfig {
479            default_flat_format: true,
480            ..Default::default()
481        };
482        let mut env = TestEnv::with_mito_config("", mito_config, Default::default()).await;
483        env.init_metric_region().await;
484        env.metric().inner.flush_task.stop().await.unwrap();
485        let physical_region_id = env.default_physical_region_id();
486        let logical_region_id = env.default_logical_region_id();
487
488        // First, do a normal logical bulk insert so we can compare results.
489        let logical_batch = build_logical_batch(0, 3);
490        let logical_request = build_bulk_request(logical_region_id, logical_batch, skip_wal);
491        let response = env
492            .metric()
493            .handle_request(logical_region_id, logical_request)
494            .await
495            .unwrap();
496        assert_eq!(response.affected_rows, 3);
497
498        // Now build a physical-format batch using modify_batch_sparse (simulating
499        // what the batcher's flush_batch_physical does) and send it directly to
500        // the physical region.
501        let tag_columns = vec![TagColumnInfo {
502            name: "job".to_string(),
503            index: 2,
504            column_id: 2, // column_id for "job" in the physical table
505        }];
506        let non_tag_indices = if retain_partition_columns {
507            vec![0, 1, 2] // timestamp, value, and the job partition column
508        } else {
509            vec![0, 1] // timestamp, value
510        };
511        let second_batch = build_logical_batch(3, 3);
512        let physical_batch = modify_batch_sparse(
513            second_batch,
514            logical_region_id.table_id(),
515            &tag_columns,
516            &non_tag_indices,
517        )
518        .unwrap();
519        assert_eq!(
520            physical_batch.column_by_name("job").is_some(),
521            retain_partition_columns
522        );
523        let physical_batch = if retain_partition_columns {
524            // The batcher retains identity for routing; sparse storage still uses the
525            // identity encoded in __primary_key, including after WAL recovery.
526            let mut fields = physical_batch.schema().fields().to_vec();
527            fields.push(Arc::new(Field::new(
528                DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
529                DataType::UInt32,
530                false,
531            )));
532            let mut columns = physical_batch.columns().to_vec();
533            columns.push(Arc::new(datatypes::arrow::array::UInt32Array::from(vec![
534                logical_region_id.table_id(); physical_batch.num_rows()
535            ])));
536            RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).unwrap()
537        } else {
538            physical_batch
539        };
540        let request = build_bulk_request(physical_region_id, physical_batch, skip_wal);
541        let response = env
542            .metric()
543            .handle_request(physical_region_id, request)
544            .await
545            .unwrap();
546        assert_eq!(response.affected_rows, 3);
547
548        // Verify all 6 rows are readable from the logical region.
549        let stream = env
550            .metric()
551            .scan_to_stream(logical_region_id, ScanRequest::default())
552            .await
553            .unwrap();
554        let batches = RecordBatches::try_collect(stream).await.unwrap();
555        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 6);
556
557        let stat = env.mito().region_statistic(physical_region_id).unwrap();
558        assert_eq!(stat.sst_num, 0);
559        let reopened = if close {
560            env.metric()
561                .handle_request(
562                    physical_region_id,
563                    RegionRequest::Close(RegionCloseRequest::default()),
564                )
565                .await
566                .unwrap();
567            // Recreating the wrapper prevents its metadata cache from hiding data loss.
568            MetricEngine::try_new(env.mito(), Default::default()).unwrap()
569        } else {
570            // Stopping workers without Close exercises recovery from WAL alone.
571            env.reopen_engine(Default::default()).await;
572            env.metric()
573        };
574        reopened.inner.flush_task.stop().await.unwrap();
575        reopened
576            .handle_request(
577                physical_region_id,
578                RegionRequest::Open(RegionOpenRequest {
579                    engine: METRIC_ENGINE_NAME.to_string(),
580                    table_dir: TestEnv::default_table_dir(),
581                    path_type: PathType::Bare,
582                    options: [(PHYSICAL_TABLE_METADATA_KEY.to_string(), String::new())]
583                        .into_iter()
584                        .collect(),
585                    skip_wal_replay: false,
586                    checkpoint: None,
587                    requirements: Default::default(),
588                }),
589            )
590            .await
591            .unwrap();
592        let stat = env
593            .mito()
594            .region_statistic(crate::utils::to_data_region_id(physical_region_id))
595            .unwrap();
596        assert_eq!(stat.sst_num > 0, skip_wal && close);
597        let stream = reopened
598            .scan_to_stream(logical_region_id, ScanRequest::default())
599            .await
600            .unwrap();
601        let batches = RecordBatches::try_collect(stream).await.unwrap();
602        assert_eq!(
603            batches.iter().map(|b| b.num_rows()).sum::<usize>(),
604            if skip_wal && !close { 0 } else { 6 },
605        );
606        batches.pretty_print().unwrap()
607    }
608
609    #[tokio::test]
610    async fn test_bulk_insert_physical_region_empty_batch() {
611        // Use flat format so that BulkMemtable is used (supports write_bulk).
612        let mito_config = MitoConfig {
613            default_flat_format: true,
614            ..Default::default()
615        };
616        let env = TestEnv::with_mito_config("", mito_config, Default::default()).await;
617        env.init_metric_region().await;
618        let physical_region_id = env.default_physical_region_id();
619
620        let batch = build_logical_batch(0, 0);
621        let request = build_bulk_request(physical_region_id, batch, false);
622        let response = env
623            .metric()
624            .handle_request(physical_region_id, request)
625            .await
626            .unwrap();
627        assert_eq!(response.affected_rows, 0);
628    }
629
630    #[tokio::test]
631    async fn test_bulk_insert_unknown_column_errors() {
632        let env = TestEnv::new().await;
633        env.init_metric_region().await;
634        let logical_region_id = env.default_logical_region_id();
635
636        let schema = Arc::new(ArrowSchema::new(vec![
637            Field::new(
638                greptime_timestamp(),
639                DataType::Timestamp(TimeUnit::Millisecond, None),
640                false,
641            ),
642            Field::new(greptime_value(), DataType::Float64, true),
643            Field::new("nonexistent_column", DataType::Utf8, true),
644        ]));
645        let batch = RecordBatch::try_new(
646            schema,
647            vec![
648                Arc::new(TimestampMillisecondArray::from(vec![0i64])),
649                Arc::new(Float64Array::from(vec![1.0])),
650                Arc::new(StringArray::from(vec!["val"])),
651            ],
652        )
653        .unwrap();
654
655        let request = build_bulk_request(logical_region_id, batch, false);
656        let err = env
657            .metric()
658            .handle_request(logical_region_id, request)
659            .await
660            .unwrap_err();
661        let Some(err) = err.as_any().downcast_ref::<Error>() else {
662            panic!("unexpected error type");
663        };
664        assert_matches!(err, Error::ColumnNotFound { .. });
665    }
666
667    #[tokio::test]
668    async fn test_bulk_insert_multiple_tag_columns() {
669        let env = TestEnv::new().await;
670        let physical_region_id = env.default_physical_region_id();
671        env.create_physical_region(physical_region_id, &TestEnv::default_table_dir(), vec![])
672            .await;
673        let logical_region_id = env.default_logical_region_id();
674        let request = test_util::create_logical_region_request(
675            &["host", "region"],
676            physical_region_id,
677            &table_dir("test", logical_region_id.table_id()),
678        );
679        env.metric()
680            .handle_request(logical_region_id, RegionRequest::Create(request))
681            .await
682            .unwrap();
683
684        let schema = Arc::new(ArrowSchema::new(vec![
685            Field::new(
686                greptime_timestamp(),
687                DataType::Timestamp(TimeUnit::Millisecond, None),
688                false,
689            ),
690            Field::new(greptime_value(), DataType::Float64, true),
691            Field::new("host", DataType::Utf8, true),
692            Field::new("region", DataType::Utf8, true),
693        ]));
694        let batch = RecordBatch::try_new(
695            schema,
696            vec![
697                Arc::new(TimestampMillisecondArray::from(vec![0i64, 1, 2])),
698                Arc::new(Float64Array::from(vec![10.0, 20.0, 30.0])),
699                Arc::new(StringArray::from(vec!["h1", "h2", "h1"])),
700                Arc::new(StringArray::from(vec!["us-east", "us-west", "eu-west"])),
701            ],
702        )
703        .unwrap();
704
705        let request = build_bulk_request(logical_region_id, batch, false);
706        let response = env
707            .metric()
708            .handle_request(logical_region_id, request)
709            .await
710            .unwrap();
711        assert_eq!(response.affected_rows, 3);
712
713        let stream = env
714            .metric()
715            .scan_to_stream(logical_region_id, ScanRequest::default())
716            .await
717            .unwrap();
718        let batches = RecordBatches::try_collect(stream).await.unwrap();
719        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
720    }
721
722    #[tokio::test]
723    async fn test_bulk_insert_accumulates_rows() {
724        let env = TestEnv::new().await;
725        env.init_metric_region().await;
726        let logical_region_id = env.default_logical_region_id();
727
728        let request = build_bulk_request(logical_region_id, build_logical_batch(0, 3), false);
729        let response = env
730            .metric()
731            .handle_request(logical_region_id, request)
732            .await
733            .unwrap();
734        assert_eq!(response.affected_rows, 3);
735
736        let request = build_bulk_request(logical_region_id, build_logical_batch(3, 5), false);
737        let response = env
738            .metric()
739            .handle_request(logical_region_id, request)
740            .await
741            .unwrap();
742        assert_eq!(response.affected_rows, 5);
743
744        let stream = env
745            .metric()
746            .scan_to_stream(logical_region_id, ScanRequest::default())
747            .await
748            .unwrap();
749        let batches = RecordBatches::try_collect(stream).await.unwrap();
750        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 8);
751    }
752
753    #[tokio::test]
754    async fn test_bulk_insert_sparse_encoding() {
755        let env = TestEnv::new().await;
756        let physical_region_id = env.default_physical_region_id();
757        env.create_physical_region(
758            physical_region_id,
759            &TestEnv::default_table_dir(),
760            vec![(
761                EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING.to_string(),
762                "byte_stream_split".to_string(),
763            )],
764        )
765        .await;
766        let logical_region_id = env.default_logical_region_id();
767        env.create_logical_region(physical_region_id, logical_region_id)
768            .await;
769
770        let rows = 4;
771        let request = build_bulk_request(logical_region_id, build_logical_batch(0, rows), false);
772        let response = env
773            .metric()
774            .handle_request(logical_region_id, request)
775            .await
776            .unwrap();
777        assert_eq!(response.affected_rows, rows);
778
779        let data_region_id = crate::utils::to_data_region_id(physical_region_id);
780        env.mito()
781            .handle_request(
782                data_region_id,
783                RegionRequest::Flush(RegionFlushRequest::default()),
784            )
785            .await
786            .unwrap();
787
788        let region = env.mito().find_region(data_region_id).unwrap();
789        let entry = env
790            .mito()
791            .all_ssts_from_manifest()
792            .await
793            .into_iter()
794            .find(|entry| {
795                entry.region_id == data_region_id
796                    && entry.visible
797                    && entry.file_path.ends_with(".parquet")
798            })
799            .unwrap();
800        let mut cache_metrics = MetadataCacheMetrics::default();
801        let footer = MetadataLoader::new(
802            region.access_layer().object_store().clone(),
803            &entry.file_path,
804            entry.file_size,
805        )
806        .load(&mut cache_metrics)
807        .await
808        .unwrap();
809        let field_column_index = footer
810            .file_metadata()
811            .schema_descr()
812            .columns()
813            .iter()
814            .position(|column| column.name() == greptime_value())
815            .unwrap();
816        assert!(!footer.row_groups().is_empty());
817        assert!(footer.row_groups().iter().all(|row_group| {
818            row_group
819                .column(field_column_index)
820                .encodings()
821                .any(|encoding| encoding == Encoding::BYTE_STREAM_SPLIT)
822        }));
823
824        let stream = env
825            .metric()
826            .scan_to_stream(logical_region_id, ScanRequest::default())
827            .await
828            .unwrap();
829        let batches = RecordBatches::try_collect(stream).await.unwrap();
830        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), rows);
831    }
832
833    #[tokio::test]
834    async fn test_bulk_insert_dense_encoding_rejected() {
835        let env = TestEnv::new().await;
836        let logical_region_id = init_dense_metric_region(&env).await;
837
838        let request = build_bulk_request(logical_region_id, build_logical_batch(0, 2), false);
839        let err = env
840            .metric()
841            .handle_request(logical_region_id, request)
842            .await
843            .unwrap_err();
844        let Some(err) = err.as_any().downcast_ref::<Error>() else {
845            panic!("unexpected error type");
846        };
847        assert_matches!(err, Error::UnsupportedRegionRequest { .. });
848    }
849
850    #[tokio::test]
851    async fn test_bulk_insert_matches_put() {
852        let env_put = TestEnv::new().await;
853        env_put.init_metric_region().await;
854        let logical_region_id = env_put.default_logical_region_id();
855        let schema = test_util::row_schema_with_tags(&["job"]);
856        let rows = test_util::build_rows(1, 5);
857        env_put
858            .metric()
859            .handle_request(
860                logical_region_id,
861                RegionRequest::Put(RegionPutRequest {
862                    skip_wal: false,
863                    rows: api::v1::Rows { schema, rows },
864                    hint: None,
865                    partition_expr_version: None,
866                }),
867            )
868            .await
869            .unwrap();
870        let put_stream = env_put
871            .metric()
872            .scan_to_stream(logical_region_id, ScanRequest::default())
873            .await
874            .unwrap();
875        let put_batches = RecordBatches::try_collect(put_stream).await.unwrap();
876        let put_output = put_batches.pretty_print().unwrap();
877
878        let env_bulk = TestEnv::new().await;
879        env_bulk.init_metric_region().await;
880        let request = build_bulk_request(logical_region_id, build_logical_batch(0, 5), false);
881        env_bulk
882            .metric()
883            .handle_request(logical_region_id, request)
884            .await
885            .unwrap();
886        let bulk_stream = env_bulk
887            .metric()
888            .scan_to_stream(logical_region_id, ScanRequest::default())
889            .await
890            .unwrap();
891        let bulk_batches = RecordBatches::try_collect(bulk_stream).await.unwrap();
892        let bulk_output = bulk_batches.pretty_print().unwrap();
893
894        assert_eq!(put_output, bulk_output);
895    }
896}