Skip to main content

servers/batcher/
logical_table.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
15mod batch;
16mod batch_convert;
17mod flow_notifier;
18mod pending_worker;
19mod region_write;
20mod tables;
21#[cfg(test)]
22pub(crate) mod test_util;
23
24use std::collections::{HashMap, HashSet};
25use std::future::{Future, ready};
26use std::num::NonZeroUsize;
27use std::sync::Arc;
28use std::time::Duration;
29
30use api::v1::RowInsertRequests;
31use catalog::CatalogManagerRef;
32use common_batcher::flush_limiter::FlushLimiter;
33use common_batcher::flush_policy::timing::TimingFlushPolicy;
34use common_batcher::request_limiter::RequestLimiter;
35use common_batcher::worker_registry::WorkerRegistry;
36use common_error::ext::BoxedError;
37use common_meta::cache::TableFlownodeSetCacheRef;
38use common_meta::node_manager::NodeManagerRef;
39use common_query::prelude::GREPTIME_PHYSICAL_TABLE;
40use common_query::{Output, WriteCompletion, WriteProgress};
41use common_time::timestamp::TimeUnit;
42use meter_core::data::MeterRecord;
43use meter_macros::write_meter;
44use operator::write_dispatcher::WriteDispatcherRef;
45use partition::manager::PartitionRuleManagerRef;
46use session::context::QueryContextRef;
47use snafu::ResultExt;
48use store_api::metric_engine_consts::{LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME};
49use tokio::sync::{Semaphore, broadcast, mpsc, oneshot};
50
51use crate::batcher::flow_notifier::{FlowNotifier, start_flow_notification_worker};
52pub use crate::batcher::logical_table::batch::flush_batch_physical;
53pub use crate::batcher::logical_table::batch_convert::{RecordBatchWithTsIdx, TableBatch};
54use crate::batcher::logical_table::pending_worker::{
55    PendingWorker, WorkerCommand, remove_worker_if_same_channel, start_worker,
56};
57pub use crate::batcher::logical_table::region_write::{
58    PhysicalFlushCatalogProvider, PhysicalFlushPartitionProvider, PhysicalFlushWriteDispatcher,
59    PhysicalTableMetadata,
60};
61pub use crate::batcher::logical_table::tables::{
62    PendingRowsSchemaAlterer, PendingRowsSchemaAltererRef,
63};
64use crate::batcher::pending_rows_batch_sync_enabled;
65use crate::error;
66use crate::error::{Error, Result};
67use crate::metrics::{
68    FLOW_NOTIFICATION_DROPPED, PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED, PENDING_WORKERS,
69};
70
71const PHYSICAL_TABLE_KEY: &str = "physical_table";
72
73const WORKER_IDLE_TIMEOUT_MULTIPLIER: u32 = 3;
74
75#[derive(Debug, Clone, Hash, Eq, PartialEq)]
76pub(crate) struct BatchKey {
77    pub(crate) catalog: String,
78    pub(crate) schema: String,
79    pub(crate) physical_table: String,
80    pub(crate) skip_wal: bool,
81}
82
83// Requests can share a batch only when their write target and WAL policy match.
84pub(crate) fn batch_key_from_ctx(ctx: &QueryContextRef) -> BatchKey {
85    let physical_table = ctx
86        .extension(PHYSICAL_TABLE_KEY)
87        .unwrap_or(GREPTIME_PHYSICAL_TABLE)
88        .to_string();
89    BatchKey {
90        catalog: ctx.current_catalog().to_string(),
91        schema: ctx.current_schema(),
92        physical_table,
93        skip_wal: ctx.skip_wal(),
94    }
95}
96
97/// Prometheus remote write pending rows batcher.
98pub struct LogicalTablePendingRowsBatcher {
99    workers: Arc<WorkerRegistry<BatchKey, WorkerCommand>>,
100    flush_interval: Duration,
101    flush_policy: TimingFlushPolicy,
102    partition_manager: PartitionRuleManagerRef,
103    write_dispatcher: WriteDispatcherRef,
104    catalog_manager: CatalogManagerRef,
105    flow_notification_tx: FlowNotifier,
106    flush_limiter: FlushLimiter,
107    request_limiter: RequestLimiter,
108    worker_channel_capacity: usize,
109    schema_alterer: PendingRowsSchemaAltererRef,
110    /// Time index unit the schema alterer uses when auto-creating a missing
111    /// physical metric table; keeps the batcher's logical-create alignment
112    /// consistent with the created physical table.
113    auto_create_physical_table_timestamp_unit: TimeUnit,
114    pending_rows_batch_sync: bool,
115    shutdown: broadcast::Sender<()>,
116}
117
118impl LogicalTablePendingRowsBatcher {
119    /// Creates the batcher when metric-engine batching is enabled.
120    #[allow(clippy::too_many_arguments)]
121    pub fn try_new(
122        partition_manager: PartitionRuleManagerRef,
123        node_manager: NodeManagerRef,
124        write_dispatcher: WriteDispatcherRef,
125        catalog_manager: CatalogManagerRef,
126        table_flownode_set_cache: TableFlownodeSetCacheRef,
127        schema_alterer: PendingRowsSchemaAltererRef,
128        auto_create_physical_table_timestamp_unit: TimeUnit,
129        flush_interval: Duration,
130        max_batch_rows: usize,
131        max_concurrent_flushes: usize,
132        worker_channel_capacity: usize,
133        max_inflight_requests: usize,
134        flow_notification_queue_capacity: NonZeroUsize,
135    ) -> Option<Arc<Self>> {
136        if worker_channel_capacity == 0 || worker_channel_capacity > Semaphore::MAX_PERMITS {
137            return None;
138        }
139
140        let flush_policy = TimingFlushPolicy::try_new(flush_interval, max_batch_rows)?;
141        let flush_limiter = FlushLimiter::try_new(max_concurrent_flushes)?;
142
143        let request_limiter = RequestLimiter::try_new(max_inflight_requests)?;
144        let (flow_notification_tx, flow_notification_rx) = FlowNotifier::try_new(
145            flow_notification_queue_capacity.get(),
146            FLOW_NOTIFICATION_DROPPED.clone(),
147        )?;
148
149        let (shutdown, _) = broadcast::channel(1);
150        let pending_rows_batch_sync = pending_rows_batch_sync_enabled();
151        let workers = Arc::new(WorkerRegistry::new());
152        PENDING_WORKERS.set(0);
153        start_flow_notification_worker(
154            flow_notification_rx,
155            table_flownode_set_cache,
156            node_manager.clone(),
157        );
158
159        Some(Arc::new(Self {
160            workers,
161            flush_interval,
162            flush_policy,
163            partition_manager,
164            write_dispatcher,
165            catalog_manager,
166            flow_notification_tx,
167            schema_alterer,
168            auto_create_physical_table_timestamp_unit,
169            flush_limiter,
170            request_limiter,
171            worker_channel_capacity,
172            pending_rows_batch_sync,
173            shutdown,
174        }))
175    }
176}
177
178impl LogicalTablePendingRowsBatcher {
179    pub(crate) fn is_synchronous(&self) -> bool {
180        self.pending_rows_batch_sync
181    }
182
183    pub async fn submit(&self, requests: RowInsertRequests, ctx: QueryContextRef) -> Result<u64> {
184        self.submit_with(requests, ctx, |_| ready(Ok(())))
185            .await
186            .map(|(rows, ())| rows)
187    }
188
189    /// Returns the physical metric table's time index unit resolved from
190    /// `ctx`, falling back to the configured auto-create unit when the table
191    /// does not exist yet (the schema alterer auto-creates it with that unit).
192    async fn physical_time_index_unit_or_default(&self, ctx: &QueryContextRef) -> TimeUnit {
193        let key = batch_key_from_ctx(ctx);
194        let Ok(Some(table)) = self
195            .catalog_manager
196            .table(&key.catalog, &key.schema, &key.physical_table, None)
197            .await
198        else {
199            return self.auto_create_physical_table_timestamp_unit;
200        };
201        table
202            .table_info()
203            .meta
204            .schema
205            .timestamp_column()
206            .and_then(|col| col.data_type.as_timestamp().map(|ts| ts.unit()))
207            .unwrap_or(TimeUnit::Millisecond)
208    }
209
210    /// Returns whether the bulk path can accept `batches`: every existing
211    /// destination table must be a metric logical table bound to the
212    /// physical table selected by its context. A destination bound to
213    /// another physical table would be flushed through the selected
214    /// physical's regions, silently misplacing its rows, so such requests
215    /// must stay on the ordinary insert path (which routes per destination).
216    /// New tables are always fine: they are created on the selected physical
217    /// table. Time index units need no check here — the bulk encode converts
218    /// each request to its destination's unit. Destinations are resolved
219    /// once per distinct (schema, table).
220    pub(crate) async fn accepts_bulk_destinations<'a>(
221        &self,
222        batches: impl Iterator<Item = (&'a QueryContextRef, &'a RowInsertRequests)>,
223    ) -> bool {
224        // One request can select different physical tables per batch (e.g.
225        // per-series physical-table labels), so the dedupe key includes the
226        // selected physical table: every distinct (schema, table, physical)
227        // triple is validated against the table's actual binding.
228        let mut checked = HashSet::new();
229        // For missing tables, one request must not select two different
230        // physical tables: the batcher would create the table through one
231        // selection and flush its rows through the other's regions.
232        let mut missing_selections: HashMap<(String, String), String> = HashMap::new();
233        for (ctx, requests) in batches {
234            if !self.schema_alterer.auto_create_enabled(ctx) {
235                return false;
236            }
237            let physical_table = batch_key_from_ctx(ctx).physical_table;
238            let schema = ctx.current_schema();
239            for request in &requests.inserts {
240                if !checked.insert((
241                    schema.clone(),
242                    request.table_name.clone(),
243                    physical_table.clone(),
244                )) {
245                    continue;
246                }
247                let Ok(Some(table)) = self
248                    .catalog_manager
249                    .table(ctx.current_catalog(), &schema, &request.table_name, None)
250                    .await
251                else {
252                    // New table: created on the selected physical table, but
253                    // a conflicting selection within the same request cannot
254                    // be batched.
255                    if missing_selections
256                        .insert(
257                            (schema.clone(), request.table_name.clone()),
258                            physical_table.clone(),
259                        )
260                        .is_some_and(|previous| previous != physical_table)
261                    {
262                        return false;
263                    }
264                    continue;
265                };
266                let info = table.table_info();
267                if info.meta.engine != METRIC_ENGINE_NAME
268                    || info
269                        .meta
270                        .options
271                        .extra_options
272                        .get(LOGICAL_TABLE_METADATA_KEY)
273                        .map(String::as_str)
274                        != Some(physical_table.as_str())
275                {
276                    return false;
277                }
278            }
279        }
280        true
281    }
282
283    /// Submits with request-level accounting after schema preparation and before
284    /// queue admission. Acknowledgement follows the global batching policy.
285    /// In synchronous mode, waits for storage even when confirmed writes are enabled.
286    /// Use [`Self::submit_output_with`] with confirmed writes to retain partial row
287    /// counts on failure.
288    pub async fn submit_with<T, F>(
289        &self,
290        requests: RowInsertRequests,
291        ctx: QueryContextRef,
292        after_prepare: impl FnOnce(RowInsertRequests) -> F,
293    ) -> Result<(u64, T)>
294    where
295        F: Future<Output = Result<T>> + Send,
296    {
297        let (output, prepared) = self
298            .submit_output_with(requests, ctx, after_prepare)
299            .await?;
300        let rows = output.extract_rows_and_cost().0 as u64;
301        if self.pending_rows_batch_sync {
302            output
303                .write_progress()
304                .await
305                .into_result()
306                .context(error::ExecuteGrpcQuerySnafu)?;
307        }
308        Ok((rows, prepared))
309    }
310
311    /// Retains completion even when the batching policy acknowledges queue admission.
312    /// With confirmed writes, callers must await [`Output::write_progress`] to observe
313    /// storage errors and acknowledged rows, including in synchronous batching mode.
314    pub async fn submit_output_with<T, F>(
315        &self,
316        requests: RowInsertRequests,
317        ctx: QueryContextRef,
318        after_prepare: impl FnOnce(RowInsertRequests) -> F,
319    ) -> Result<(Output, T)>
320    where
321        F: Future<Output = Result<T>> + Send,
322    {
323        let confirmed = ctx.confirmed_writes();
324        let (table_batches, total_rows) = {
325            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
326                .with_label_values(&["submit_build_and_align"])
327                .start_timer();
328            self.build_and_align_table_batches(&requests, &ctx).await?
329        };
330        let prepared = after_prepare(requests).await?;
331        if total_rows == 0 {
332            return Ok((Output::new_with_affected_rows(0), prepared));
333        }
334
335        // Flushes dispatch directly to datanodes, so admit once before enqueueing.
336        write_meter!(MeterRecord::new(
337            ctx.current_catalog().to_string(),
338            ctx.current_schema(),
339            0,
340            ctx.write_rows_to_admit(
341                ctx.current_catalog(),
342                &ctx.current_schema(),
343                total_rows as u64
344            ),
345            ctx.channel() as u8,
346        ))
347        .await
348        .context(error::WriteRejectedSnafu)?;
349
350        let permit = {
351            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
352                .with_label_values(&["submit_acquire_inflight_permit"])
353                .start_timer();
354            self.request_limiter
355                .acquire()
356                .await
357                .map_err(|_| error::BatcherChannelClosedSnafu.build())?
358        };
359
360        let (response_tx, response_rx) = oneshot::channel();
361        let progress = ctx.write_progress().cloned();
362
363        let batch_key = batch_key_from_ctx(&ctx);
364        let mut cmd = Some(WorkerCommand::Submit {
365            _completion: progress.as_ref().map(|progress| progress.start()),
366            table_batches,
367            total_rows,
368            ctx,
369            response_tx,
370            _permit: permit,
371        });
372
373        {
374            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
375                .with_label_values(&["submit_send_to_worker"])
376                .start_timer();
377
378            for _ in 0..2 {
379                let worker = self.get_or_spawn_worker(batch_key.clone()).await;
380                let Some(worker_cmd) = cmd.take() else {
381                    break;
382                };
383
384                match worker.tx.send(worker_cmd).await {
385                    Ok(()) => break,
386                    Err(err) => {
387                        cmd = Some(err.0);
388                        remove_worker_if_same_channel(
389                            self.workers.as_ref(),
390                            &batch_key,
391                            &worker.tx,
392                        )
393                        .await;
394                    }
395                }
396            }
397
398            if cmd.is_some() {
399                return Err(Error::BatcherChannelClosed);
400            }
401        }
402
403        let completion = async move {
404            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
405                .with_label_values(&["submit_wait_flush_result"])
406                .start_timer();
407            response_rx.await.unwrap_or_else(|_| {
408                WriteProgress::failed(BoxedError::new(error::BatcherChannelClosedSnafu.build()))
409            })
410        };
411        let mut output = Output::new_with_affected_rows(total_rows);
412        if self.pending_rows_batch_sync && !confirmed {
413            completion
414                .await
415                .into_result()
416                .context(error::ExecuteGrpcQuerySnafu)?;
417        } else {
418            if let Some(progress) = progress {
419                progress.mark_accepted();
420            }
421            output
422                .meta
423                .write_completions
424                .push(WriteCompletion::with_progress(completion));
425        }
426        Ok((output, prepared))
427    }
428}
429
430impl LogicalTablePendingRowsBatcher {
431    async fn get_or_spawn_worker(&self, key: BatchKey) -> PendingWorker {
432        let (tx, receiver) = self
433            .workers
434            .get_or_create(key.clone(), self.worker_channel_capacity)
435            .await;
436        if let Some(rx) = receiver {
437            self.spawn_worker(key, tx.clone(), rx);
438            PENDING_WORKERS.set(self.workers.len().await as i64);
439        }
440        PendingWorker { tx }
441    }
442}
443
444impl LogicalTablePendingRowsBatcher {
445    fn spawn_worker(
446        &self,
447        key: BatchKey,
448        tx: mpsc::Sender<WorkerCommand>,
449        rx: mpsc::Receiver<WorkerCommand>,
450    ) {
451        let worker_idle_timeout = self
452            .flush_interval
453            .checked_mul(WORKER_IDLE_TIMEOUT_MULTIPLIER)
454            .unwrap_or(self.flush_interval);
455
456        start_worker(
457            key,
458            tx,
459            self.workers.clone(),
460            rx,
461            self.shutdown.clone(),
462            self.partition_manager.clone(),
463            self.write_dispatcher.clone(),
464            self.catalog_manager.clone(),
465            self.flow_notification_tx.clone(),
466            worker_idle_timeout,
467            self.flush_policy,
468            self.flush_limiter.clone(),
469        );
470    }
471}
472
473impl Drop for LogicalTablePendingRowsBatcher {
474    fn drop(&mut self) {
475        let _ = self.shutdown.send(());
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use std::future::ready;
482    use std::sync::Arc;
483
484    use api::v1::value::ValueData;
485    use api::v1::{
486        ColumnDataType, ColumnSchema, Row, RowInsertRequest, RowInsertRequests, Rows, SemanticType,
487        Value,
488    };
489    use arrow::array::{StringArray, TimestampMillisecondArray};
490    use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema};
491    use arrow::record_batch::RecordBatch;
492    use common_error::ext::{BoxedError, ErrorExt};
493    use common_error::status_code::StatusCode;
494    use common_query::WriteProgress;
495    use common_query::prelude::greptime_timestamp;
496    use session::context::QueryContext;
497
498    use crate::batcher::logical_table::batch_convert::{RecordBatchWithTsIdx, TableBatch};
499    use crate::batcher::logical_table::flow_notifier::extract_timestamps;
500    use crate::batcher::logical_table::pending_worker::WorkerCommand;
501    use crate::batcher::logical_table::test_util::{
502        mock_aligned_tag_batch, mock_tag_batch, submission_batcher,
503    };
504    use crate::error;
505
506    fn submission_requests() -> RowInsertRequests {
507        RowInsertRequests {
508            inserts: vec![RowInsertRequest {
509                table_name: "cpu".to_string(),
510                rows: Some(Rows {
511                    schema: vec![ColumnSchema {
512                        column_name: "greptime_timestamp".to_string(),
513                        datatype: ColumnDataType::TimestampMillisecond as i32,
514                        semantic_type: SemanticType::Timestamp as i32,
515                        ..Default::default()
516                    }],
517                    rows: [1000, 2000]
518                        .into_iter()
519                        .map(|ts| Row {
520                            values: vec![Value {
521                                value_data: Some(ValueData::TimestampMillisecondValue(ts)),
522                            }],
523                        })
524                        .collect(),
525                }),
526            }],
527        }
528    }
529
530    fn flush_progress(affected_rows: usize) -> WriteProgress {
531        WriteProgress {
532            affected_rows,
533            error: (affected_rows < 2).then(|| {
534                Arc::new(BoxedError::new(
535                    error::InvalidQuerySnafu {
536                        reason: "storage write failed",
537                    }
538                    .build(),
539                ))
540            }),
541        }
542    }
543
544    #[tokio::test]
545    async fn test_submit_with_preserves_sync_acknowledgement() {
546        for confirmed in [false, true] {
547            for sync in [false, true] {
548                for affected_rows in [0, 1, 2] {
549                    let (batcher, mut receiver) = submission_batcher(sync).await;
550                    let ctx = QueryContext::arc();
551                    let ctx = if confirmed {
552                        Arc::new(ctx.with_confirmed_writes())
553                    } else {
554                        ctx
555                    };
556                    let submit = batcher.submit_with(submission_requests(), ctx, |_| ready(Ok(7)));
557                    tokio::pin!(submit);
558                    let mut early_result = None;
559                    // Poll submission first to detect early acknowledgement without timing assumptions.
560                    let command = tokio::select! {
561                        biased;
562                        result = &mut submit => {
563                            assert!(result.is_ok(), "{result:?}");
564                            early_result = Some(result);
565                            receiver.try_recv().unwrap()
566                        }
567                        command = receiver.recv() => command.unwrap(),
568                    };
569                    assert_eq!(early_result.is_none(), sync);
570                    let WorkerCommand::Submit { response_tx, .. } = command else {
571                        panic!("expected submission")
572                    };
573                    assert_eq!(
574                        response_tx.send(flush_progress(affected_rows)).is_ok(),
575                        sync
576                    );
577                    let result = match early_result {
578                        Some(result) => result,
579                        None => submit.await,
580                    };
581                    if sync && affected_rows < 2 {
582                        assert_eq!(
583                            result.unwrap_err().status_code(),
584                            StatusCode::InvalidArguments
585                        );
586                    } else {
587                        assert_eq!(result.unwrap(), (2, 7));
588                    }
589                }
590            }
591        }
592    }
593
594    #[tokio::test]
595    async fn test_submit_output_with_preserves_confirmed_partial_progress() {
596        for sync in [false, true] {
597            let (batcher, mut receiver) = submission_batcher(sync).await;
598            let ctx = Arc::new(QueryContext::arc().with_confirmed_writes());
599            let (output, prepared) = batcher
600                .submit_output_with(submission_requests(), ctx, |_| ready(Ok(7)))
601                .await
602                .unwrap();
603            assert_eq!(prepared, 7);
604            assert_eq!(output.meta.write_completions.len(), 1);
605            let WorkerCommand::Submit { response_tx, .. } = receiver.try_recv().unwrap() else {
606                panic!("expected submission")
607            };
608            let progress = output.write_progress();
609            tokio::pin!(progress);
610            assert!(futures::poll!(progress.as_mut()).is_pending());
611            response_tx.send(flush_progress(1)).unwrap();
612            let progress = progress.await;
613            assert_eq!(progress.affected_rows, 1);
614            assert_eq!(
615                progress.error.unwrap().status_code(),
616                StatusCode::InvalidArguments
617            );
618        }
619    }
620
621    #[test]
622    fn test_extract_timestamps_appends_non_null_batches_in_order() {
623        let table_batch = TableBatch {
624            table_name: "cpu".to_string(),
625            table_id: 42,
626            batches: vec![
627                mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0),
628                mock_aligned_tag_batch("tag1", "host-1", 2000, 2.0),
629            ],
630            row_count: 2,
631        };
632
633        assert_eq!(vec![1000, 2000], extract_timestamps(&table_batch));
634    }
635
636    #[test]
637    fn test_extract_timestamps_omits_nulls_and_retains_order() {
638        let table_batch = TableBatch {
639            table_name: "cpu".to_string(),
640            table_id: 42,
641            batches: vec![
642                mock_timestamp_batch(vec![Some(1000), None, Some(3000)]),
643                mock_timestamp_batch(vec![None, Some(5000)]),
644            ],
645            row_count: 5,
646        };
647
648        assert_eq!(vec![1000, 3000, 5000], extract_timestamps(&table_batch));
649    }
650
651    #[test]
652    fn test_record_batch_with_ts_idx_rejects_out_of_bounds_index() {
653        let batch = mock_tag_batch("tag1", "host-1", 1000, 1.0);
654
655        assert!(RecordBatchWithTsIdx::try_new(batch, 3).is_err());
656    }
657
658    #[test]
659    fn test_record_batch_with_ts_idx_rejects_non_timestamp_column() {
660        let batch = mock_tag_batch("tag1", "host-1", 1000, 1.0);
661
662        assert!(RecordBatchWithTsIdx::try_new(batch, 1).is_err());
663    }
664
665    #[test]
666    fn test_extract_timestamps_supports_per_batch_timestamp_indices() {
667        let timestamp_first = RecordBatch::try_new(
668            Arc::new(ArrowSchema::new(vec![
669                Field::new(
670                    "ts",
671                    ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
672                    false,
673                ),
674                Field::new("host", ArrowDataType::Utf8, true),
675            ])),
676            vec![
677                Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])),
678                Arc::new(StringArray::from(vec!["host-1", "host-2"])),
679            ],
680        )
681        .unwrap();
682        let timestamp_second = RecordBatch::try_new(
683            Arc::new(ArrowSchema::new(vec![
684                Field::new("host", ArrowDataType::Utf8, true),
685                Field::new(
686                    "timestamp",
687                    ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
688                    false,
689                ),
690            ])),
691            vec![
692                Arc::new(StringArray::from(vec!["host-3", "host-4"])),
693                Arc::new(TimestampMillisecondArray::from(vec![3000, 4000])),
694            ],
695        )
696        .unwrap();
697        let table_batch = TableBatch {
698            table_name: "cpu".to_string(),
699            table_id: 42,
700            batches: vec![
701                RecordBatchWithTsIdx::try_new(timestamp_first, 0).unwrap(),
702                RecordBatchWithTsIdx::try_new(timestamp_second, 1).unwrap(),
703            ],
704            row_count: 4,
705        };
706
707        assert_eq!(
708            vec![1000, 2000, 3000, 4000],
709            extract_timestamps(&table_batch)
710        );
711    }
712
713    fn mock_timestamp_batch(timestamps: Vec<Option<i64>>) -> RecordBatchWithTsIdx {
714        let batch = RecordBatch::try_new(
715            Arc::new(ArrowSchema::new(vec![Field::new(
716                greptime_timestamp(),
717                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
718                true,
719            )])),
720            vec![Arc::new(TimestampMillisecondArray::from(timestamps))],
721        )
722        .unwrap();
723        RecordBatchWithTsIdx::try_new(batch, 0).unwrap()
724    }
725    #[test]
726    fn test_batch_key_groups_by_skip_wal() {
727        use std::collections::HashMap;
728
729        use crate::batcher::logical_table::batch_key_from_ctx;
730
731        let wal_ctx = session::context::QueryContext::arc();
732        let skip_wal_ctx = session::context::QueryContext::arc();
733        skip_wal_ctx.set_skip_wal(true);
734        let another_skip_wal_ctx = session::context::QueryContext::arc();
735        another_skip_wal_ctx.set_skip_wal(true);
736
737        let mut batches = HashMap::new();
738        *batches.entry(batch_key_from_ctx(&wal_ctx)).or_insert(0) += 1;
739        *batches
740            .entry(batch_key_from_ctx(&skip_wal_ctx))
741            .or_insert(0) += 1;
742        *batches
743            .entry(batch_key_from_ctx(&another_skip_wal_ctx))
744            .or_insert(0) += 1;
745        *batches
746            .entry(batch_key_from_ctx(&session::context::QueryContext::arc()))
747            .or_insert(0) += 1;
748
749        assert_eq!(batches.len(), 2);
750        assert_eq!(batches[&batch_key_from_ctx(&wal_ctx)], 2);
751        assert_eq!(batches[&batch_key_from_ctx(&skip_wal_ctx)], 2);
752    }
753}