Skip to main content

servers/batcher/logical_table/
batch.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;
16use std::time::Instant;
17
18use catalog::CatalogManagerRef;
19use common_batcher::flush_limiter::FlushLimiter;
20use common_error::ext::BoxedError;
21use common_query::{WriteProgress, prelude};
22use common_telemetry::{debug, warn};
23use operator::write_dispatcher::TrackedWrite;
24use operator::write_dispatcher::WriteDispatcherRef;
25use partition::manager::PartitionRuleManagerRef;
26use session::context::QueryContextRef;
27use snafu::{IntoError, OptionExt, ensure};
28
29use crate::batcher::flow_notifier::FlowNotifier;
30use crate::batcher::logical_table;
31use crate::batcher::logical_table::batch_convert::{self, TableBatch};
32use crate::batcher::logical_table::flow_notifier;
33use crate::batcher::logical_table::pending_worker::FlushWaiter;
34use crate::batcher::logical_table::region_write::{
35    self, CatalogManagerPhysicalFlushAdapter, PartitionManagerPhysicalFlushAdapter,
36    PhysicalFlushCatalogProvider, PhysicalFlushPartitionProvider, PhysicalFlushWriteDispatcher,
37    WriteDispatcherPhysicalFlushAdapter,
38};
39use crate::error;
40use crate::error::Result;
41use crate::metrics;
42
43/// Rows and completion waiters owned by one physical flush.
44pub(crate) struct Batch {
45    pub(crate) table_batches: Vec<TableBatch>,
46    pub(crate) total_row_count: usize,
47    pub(crate) db_string: String,
48    pub(crate) ctx: QueryContextRef,
49    pub(crate) waiters: Vec<FlushWaiter>,
50}
51
52/// Spawns a physical flush with the configured concurrency limit.
53pub(crate) async fn spawn_flush(
54    flush: Batch,
55    partition_manager: PartitionRuleManagerRef,
56    write_dispatcher: WriteDispatcherRef,
57    catalog_manager: CatalogManagerRef,
58    flow_notification_tx: FlowNotifier,
59    flush_limiter: FlushLimiter,
60) {
61    match flush_limiter.acquire().await {
62        Ok(permit) => {
63            tokio::spawn(async move {
64                let _permit = permit;
65                flush_batch_with_managers(
66                    flush,
67                    partition_manager,
68                    write_dispatcher,
69                    catalog_manager,
70                    flow_notification_tx,
71                )
72                .await;
73            });
74        }
75        Err(err) => {
76            warn!(err; "Flush semaphore closed, flushing inline");
77            flush_batch_with_managers(
78                flush,
79                partition_manager,
80                write_dispatcher,
81                catalog_manager,
82                flow_notification_tx,
83            )
84            .await;
85        }
86    }
87}
88
89/// Connects shared routing and dispatch dependencies to a physical flush.
90pub(crate) async fn flush_batch_with_managers(
91    flush: Batch,
92    partition_manager: PartitionRuleManagerRef,
93    write_dispatcher: WriteDispatcherRef,
94    catalog_manager: CatalogManagerRef,
95    flow_notification_tx: FlowNotifier,
96) {
97    let partition_provider = PartitionManagerPhysicalFlushAdapter { partition_manager };
98    let write_dispatcher = WriteDispatcherPhysicalFlushAdapter { write_dispatcher };
99    let catalog_provider = CatalogManagerPhysicalFlushAdapter { catalog_manager };
100    flush_batch(
101        flush,
102        &partition_provider,
103        &write_dispatcher,
104        &catalog_provider,
105        flow_notification_tx,
106    )
107    .await;
108}
109
110/// Flushes a batch and reports completion to its waiters.
111pub(crate) async fn flush_batch(
112    flush: Batch,
113    partition_manager: &(impl PhysicalFlushPartitionProvider + ?Sized),
114    write_dispatcher: &(impl PhysicalFlushWriteDispatcher + ?Sized),
115    catalog_manager: &(impl PhysicalFlushCatalogProvider + ?Sized),
116    flow_notification_tx: FlowNotifier,
117) {
118    let Batch {
119        table_batches,
120        total_row_count,
121        db_string,
122        ctx,
123        waiters,
124    } = flush;
125    let start = Instant::now();
126
127    // Physical-table-level flush: transform all logical table batches
128    // into physical format and write them together.
129    let physical_table_name = ctx
130        .extension(logical_table::PHYSICAL_TABLE_KEY)
131        .unwrap_or(prelude::GREPTIME_PHYSICAL_TABLE)
132        .to_string();
133    let result = flush_batch_physical_tracked(
134        &table_batches,
135        &physical_table_name,
136        &ctx,
137        partition_manager,
138        write_dispatcher,
139        catalog_manager,
140        waiters.len().max(
141            table_batches
142                .iter()
143                .flat_map(|table| &table.batches)
144                .map(|batch| batch.owner + 1)
145                .max()
146                .unwrap_or(0),
147        ),
148    )
149    .await;
150
151    let elapsed = start.elapsed().as_secs_f64();
152    metrics::FLUSH_ELAPSED.observe(elapsed);
153
154    debug!(
155        "Pending rows batch flushed, total rows: {}, elapsed time: {}s",
156        total_row_count, elapsed
157    );
158
159    match result {
160        Ok(progress) => {
161            if progress.iter().any(|result| result.error.is_some()) {
162                metrics::FLUSH_FAILURES.inc();
163            } else {
164                metrics::FLUSH_TOTAL.inc();
165                metrics::FLUSH_ROWS.observe(total_row_count as f64);
166            }
167            let affected_rows = progress.iter().map(|result| result.affected_rows).sum();
168            metrics::FLUSH_DROPPED_ROWS
169                .inc_by(total_row_count.saturating_sub(affected_rows) as u64);
170            let successful = progress
171                .iter()
172                .enumerate()
173                .filter_map(|(owner, result)| result.error.is_none().then_some(owner))
174                .collect::<HashSet<_>>();
175            for (waiter, result) in waiters.into_iter().zip(progress) {
176                operator::metrics::DIST_INGEST_ROW_COUNT
177                    .with_label_values(&[db_string.as_str()])
178                    .inc_by(result.affected_rows as u64);
179                let _ = waiter.response_tx.send(result);
180            }
181            let accepted = table_batches
182                .into_iter()
183                .filter_map(|mut table| {
184                    table
185                        .batches
186                        .retain(|batch| successful.contains(&batch.owner));
187                    table.row_count = table
188                        .batches
189                        .iter()
190                        .map(|batch| batch.batch.num_rows())
191                        .sum();
192                    (!table.batches.is_empty()).then_some(table)
193                })
194                .collect();
195            flow_notifier::enqueue_flow_notifications(accepted, &flow_notification_tx);
196        }
197        Err(err) => {
198            metrics::FLUSH_FAILURES.inc();
199            metrics::FLUSH_DROPPED_ROWS.inc_by(total_row_count as u64);
200            notify_waiters(waiters, Err(err));
201        }
202    }
203}
204
205/// Flushes a batch of logical table rows by transforming them into the physical table format
206/// and writing them to the appropriate datanode regions.
207///
208/// This function performs the end-to-end physical flush pipeline:
209/// 1. Resolves the physical table metadata and column ID mapping.
210/// 2. Fetches the physical table's partition rule.
211/// 3. Transforms each logical table batch into the physical (sparse primary key) format.
212/// 4. Concatenates all transformed batches into a single combined batch.
213/// 5. Splits the combined batch by partition rule and sends region write requests
214///    concurrently to the target datanodes.
215pub async fn flush_batch_physical(
216    table_batches: &[TableBatch],
217    physical_table_name: &str,
218    ctx: &QueryContextRef,
219    partition_manager: &(impl PhysicalFlushPartitionProvider + ?Sized),
220    write_dispatcher: &(impl PhysicalFlushWriteDispatcher + ?Sized),
221    catalog_manager: &(impl PhysicalFlushCatalogProvider + ?Sized),
222) -> Result<usize> {
223    let inputs = table_batches
224        .iter()
225        .flat_map(|table| &table.batches)
226        .map(|batch| batch.owner + 1)
227        .max()
228        .unwrap_or(1);
229    let progress = flush_batch_physical_tracked(
230        table_batches,
231        physical_table_name,
232        ctx,
233        partition_manager,
234        write_dispatcher,
235        catalog_manager,
236        inputs,
237    )
238    .await?;
239    let mut result = WriteProgress::default();
240    for part in progress {
241        result.merge(part);
242    }
243    result
244        .into_result()
245        .map_err(|source| error::ExecuteGrpcQuerySnafu.into_error(source))
246}
247
248async fn flush_batch_physical_tracked(
249    table_batches: &[TableBatch],
250    physical_table_name: &str,
251    ctx: &QueryContextRef,
252    partition_manager: &(impl PhysicalFlushPartitionProvider + ?Sized),
253    write_dispatcher: &(impl PhysicalFlushWriteDispatcher + ?Sized),
254    catalog_manager: &(impl PhysicalFlushCatalogProvider + ?Sized),
255    inputs: usize,
256) -> Result<Vec<WriteProgress>> {
257    // 1. Resolve the physical table and get column ID mapping
258    let physical_table = {
259        let _timer = metrics::PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
260            .with_label_values(&["flush_physical_resolve_table"])
261            .start_timer();
262        catalog_manager
263            .physical_table(
264                ctx.current_catalog(),
265                &ctx.current_schema(),
266                physical_table_name,
267                ctx.as_ref(),
268            )
269            .await?
270            .with_context(|| error::InternalSnafu {
271                err_msg: format!(
272                    "Physical table '{}' not found during pending flush",
273                    physical_table_name
274                ),
275            })?
276    };
277
278    let physical_table_info = physical_table.table_info;
279    let name_to_ids = physical_table
280        .col_name_to_ids
281        .with_context(|| error::InternalSnafu {
282            err_msg: format!(
283                "Physical table '{}' has no column IDs for pending flush",
284                physical_table_name
285            ),
286        })?;
287
288    // 2. Get the physical table's partition rule (one lookup instead of N)
289    let (partition_rule, partition_versions) = {
290        let _timer = metrics::PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
291            .with_label_values(&["flush_physical_fetch_partition_rule"])
292            .start_timer();
293        partition_manager
294            .find_table_partition_rule(physical_table_info.as_ref())
295            .await?
296    };
297    let partition_columns = partition_rule.partition_columns();
298    let partition_columns_set: HashSet<&str> =
299        partition_columns.iter().map(String::as_str).collect();
300
301    // 3. Transform each logical table batch into physical format
302    let modified_batches = batch_convert::transform_logical_batches_to_physical(
303        table_batches,
304        &name_to_ids,
305        &partition_columns_set,
306    )?;
307
308    // 4. Concatenate all modified batches (all share the same physical schema)
309    let combined_batch = batch_convert::concat_modified_batches(&modified_batches, table_batches)?;
310    // 5. Use the physical rule with FromPayload context: the combined batch carries
311    // each row's logical table id, rather than one identity for the whole batch.
312    let physical_table_id = physical_table_info.table_id();
313    let row_count = table_batches
314        .iter()
315        .flat_map(|table| &table.batches)
316        .map(|batch| batch.batch.num_rows())
317        .sum::<usize>();
318    ensure!(
319        row_count == combined_batch.num_rows(),
320        error::InternalSnafu {
321            err_msg: "Physical transformation changed row ownership"
322        }
323    );
324    let masks =
325        region_write::split_combined_batch_by_region(&combined_batch, partition_rule.as_ref())?;
326    let mut writes = Vec::new();
327    for (region, mask) in masks {
328        let mut selected = Vec::with_capacity(mask.selected_rows());
329        let bits = mask.array().values();
330        let mut offset = 0;
331        // Filtering preserves batch order, and each original batch has one owner.
332        for batch in table_batches.iter().flat_map(|table| &table.batches) {
333            let num_rows = batch.batch.num_rows();
334            let selected_rows = if num_rows == 1 {
335                // Avoid bitmap range setup for single-row submissions.
336                usize::from(bits.value(offset))
337            } else {
338                // `offset` is mask-relative; the raw buffer also needs the mask's slice offset.
339                bits.inner()
340                    .count_set_bits_offset(bits.offset() + offset, num_rows)
341            };
342            selected.extend(std::iter::repeat_n(batch.owner, selected_rows));
343            offset += num_rows;
344        }
345        if let Some(batch) =
346            region_write::plan_region_batch(&combined_batch, physical_table_id, region, &mask)?
347        {
348            let request = region_write::encode_region_write_request(
349                batch,
350                ctx.skip_wal(),
351                &partition_versions,
352            )?;
353            writes.push(TrackedWrite {
354                request,
355                owners: selected,
356            });
357        }
358    }
359    let progress = write_dispatcher.dispatch_tracked(writes, inputs).await;
360    // A submission can contribute several logical batches; credit its counter once.
361    let counters = table_batches
362        .iter()
363        .flat_map(|table| &table.batches)
364        .filter_map(|batch| {
365            batch
366                .progress
367                .as_ref()
368                .map(|counter| (batch.owner, counter))
369        })
370        .collect::<std::collections::HashMap<_, _>>();
371    for (owner, counter) in counters {
372        counter.add_written(progress[owner].affected_rows);
373    }
374    Ok(progress)
375}
376
377pub(in crate::batcher::logical_table) fn notify_waiters(
378    waiters: Vec<FlushWaiter>,
379    result: Result<()>,
380) {
381    let progress = match result {
382        Ok(()) => WriteProgress::default(),
383        Err(error) => WriteProgress::failed(BoxedError::new(error)),
384    };
385    for waiter in waiters {
386        let _ = waiter.response_tx.send(progress.clone());
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use std::collections::HashMap;
393    use std::future::poll_fn;
394    use std::sync::Arc;
395    use std::sync::atomic::{AtomicUsize, Ordering};
396    use std::task::Poll;
397    use std::time::Duration;
398
399    use api::v1::meta::Peer;
400    use api::v1::region::RegionRequest;
401    use arrow::record_batch::RecordBatch;
402    use async_trait::async_trait;
403    use catalog::error::Result as CatalogResult;
404    use common_batcher::request_limiter::RequestLimiter;
405    use common_meta::cache::TableFlownodeSetCacheRef;
406    use common_meta::node_manager::NodeManagerRef;
407    use datatypes::schema::{ColumnSchema as DtColumnSchema, Schema as DtSchema};
408    use partition::error::Result as PartitionResult;
409    use partition::partition::{PartitionRule, PartitionRuleRef, RegionMask};
410    use table::metadata::TableId;
411    use table::test_util::table_info::test_table_info;
412    use tokio::sync::{mpsc, oneshot};
413
414    use crate::batcher::flow_notifier::{FlowNotifier, start_flow_notification_worker};
415    use crate::batcher::logical_table::batch::{
416        Batch, flush_batch, flush_batch_physical, notify_waiters,
417    };
418    use crate::batcher::logical_table::batch_convert::TableBatch;
419    use crate::batcher::logical_table::pending_worker::FlushWaiter;
420    use crate::batcher::logical_table::region_write::{
421        PhysicalFlushCatalogProvider, PhysicalFlushPartitionProvider, PhysicalFlushWriteDispatcher,
422        PhysicalTableMetadata,
423    };
424    use crate::batcher::logical_table::test_util::{
425        FlowNotificationMockNodeManager, RecordingFlownode, mock_aligned_tag_batch,
426    };
427    use crate::batcher::test_util::mock_table_flownode_cache;
428    use crate::error;
429    use crate::error::Error;
430    use crate::metrics::{self, FLOW_NOTIFICATION_DROPPED};
431
432    #[tokio::test]
433    async fn test_flush_batch_notifies_flownode_after_successful_physical_write() {
434        let table_id = 42;
435        let peer = Peer {
436            id: 7,
437            addr: "flow-7".to_string(),
438        };
439        let cache = mock_table_flownode_cache(table_id, vec![(0, peer.clone()), (1, peer)]).await;
440        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
441        let _requests_tx = requests_tx.clone();
442        let flow_node_manager: NodeManagerRef = Arc::new(FlowNotificationMockNodeManager {
443            flownode: Arc::new(RecordingFlownode { requests_tx }),
444        });
445        let flow_notification_tx = mock_flow_notification_sender(cache, flow_node_manager.clone());
446        let ctx = session::context::QueryContext::arc();
447        let table_batches = vec![TableBatch {
448            table_name: "cpu".to_string(),
449            table_id,
450            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
451            row_count: 1,
452        }];
453        let writes = Arc::new(AtomicUsize::new(0));
454
455        flush_batch(
456            Batch {
457                table_batches,
458                total_row_count: 1,
459                db_string: ctx.get_db_string(),
460                ctx,
461                waiters: Vec::new(),
462            },
463            &MockFlushPartitionProvider {
464                partition_rule_calls: Arc::new(AtomicUsize::new(0)),
465            },
466            &MockFlushWriteDispatcher {
467                writes: writes.clone(),
468                fail: false,
469            },
470            &MockFlushCatalogProvider {
471                table: Some(mock_physical_table_metadata(1024)),
472            },
473            flow_notification_tx,
474        )
475        .await;
476
477        assert_eq!(1, writes.load(Ordering::SeqCst));
478        let requests = tokio::time::timeout(Duration::from_secs(1), requests_rx.recv())
479            .await
480            .unwrap()
481            .unwrap();
482        assert_eq!(
483            vec![api::v1::flow::DirtyWindowRequest {
484                table_id,
485                timestamps: vec![1000],
486                time_ranges: Vec::new(),
487            }],
488            requests.requests
489        );
490    }
491
492    #[tokio::test]
493    async fn test_flush_batch_does_not_notify_flownode_after_physical_write_error() {
494        let table_id = 42;
495        let peer = Peer {
496            id: 7,
497            addr: "flow-7".to_string(),
498        };
499        let cache = mock_table_flownode_cache(table_id, vec![(0, peer.clone()), (1, peer)]).await;
500        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
501        let _requests_tx = requests_tx.clone();
502        let flow_node_manager: NodeManagerRef = Arc::new(FlowNotificationMockNodeManager {
503            flownode: Arc::new(RecordingFlownode { requests_tx }),
504        });
505        let flow_notification_tx = mock_flow_notification_sender(cache, flow_node_manager.clone());
506        let ctx = session::context::QueryContext::arc();
507        let table_batches = vec![TableBatch {
508            table_name: "cpu".to_string(),
509            table_id,
510            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
511            row_count: 1,
512        }];
513        let writes = Arc::new(AtomicUsize::new(0));
514
515        flush_batch(
516            Batch {
517                table_batches,
518                total_row_count: 1,
519                db_string: ctx.get_db_string(),
520                ctx,
521                waiters: Vec::new(),
522            },
523            &MockFlushPartitionProvider {
524                partition_rule_calls: Arc::new(AtomicUsize::new(0)),
525            },
526            &MockFlushWriteDispatcher {
527                writes: writes.clone(),
528                fail: true,
529            },
530            &MockFlushCatalogProvider {
531                table: Some(mock_physical_table_metadata(1024)),
532            },
533            flow_notification_tx,
534        )
535        .await;
536
537        assert_eq!(1, writes.load(Ordering::SeqCst));
538        assert!(
539            tokio::time::timeout(Duration::from_millis(50), requests_rx.recv())
540                .await
541                .is_err()
542        );
543    }
544
545    #[tokio::test]
546    async fn test_cancelled_waiter_retains_request_slot_until_notification() {
547        let limiter = RequestLimiter::try_new(1).unwrap();
548        let (response_tx, response_rx) = oneshot::channel();
549        let waiter = FlushWaiter {
550            _completion: None,
551            response_tx,
552            _permit: limiter.acquire().await.unwrap(),
553        };
554        drop(response_rx);
555        let next = limiter.acquire();
556        tokio::pin!(next);
557        assert!(poll_fn(|cx| Poll::Ready(next.as_mut().poll(cx).is_pending())).await);
558        notify_waiters(vec![waiter], Ok(()));
559        let _permit = next.await.unwrap();
560    }
561
562    #[tokio::test]
563    async fn test_flush_batch_physical_uses_mockable_trait_dependencies() {
564        let table_batches = vec![TableBatch {
565            table_name: "t1".to_string(),
566            table_id: 11,
567            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
568            row_count: 1,
569        }];
570        let partition_calls = Arc::new(AtomicUsize::new(0));
571        let dispatcher = MockFlushWriteDispatcher::default();
572        let ctx = session::context::QueryContext::arc();
573
574        flush_batch_physical(
575            &table_batches,
576            "phy",
577            &ctx,
578            &MockFlushPartitionProvider {
579                partition_rule_calls: partition_calls.clone(),
580            },
581            &dispatcher,
582            &MockFlushCatalogProvider {
583                table: Some(mock_physical_table_metadata(1024)),
584            },
585        )
586        .await
587        .unwrap();
588
589        assert_eq!(1, partition_calls.load(Ordering::SeqCst));
590        assert_eq!(1, dispatcher.writes.load(Ordering::SeqCst));
591    }
592
593    #[tokio::test]
594    async fn test_flush_batch_physical_rejects_unattributable_affected_rows() {
595        let table_batches = vec![TableBatch {
596            table_name: "t1".to_string(),
597            table_id: 11,
598            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
599            row_count: 1,
600        }];
601        let ctx = session::context::QueryContext::arc();
602
603        let error = flush_batch_physical(
604            &table_batches,
605            "phy",
606            &ctx,
607            &MockFlushPartitionProvider {
608                partition_rule_calls: Arc::new(AtomicUsize::new(0)),
609            },
610            &AffectedRowsFlushWriteDispatcher { affected_rows: 7 },
611            &MockFlushCatalogProvider {
612                table: Some(mock_physical_table_metadata(1024)),
613            },
614        )
615        .await
616        .unwrap_err();
617
618        assert!(format!("{error:?}").contains("Unattributable"));
619    }
620
621    #[tokio::test]
622    async fn test_exemplar_coalesced_logical_flush_retains_each_requests_progress() {
623        use common_error::ext::BoxedError;
624        use common_query::WriteProgress;
625        use operator::write_dispatcher::TrackedWrite;
626
627        struct ProgressDispatcher([(usize, bool); 2]);
628        #[async_trait]
629        impl PhysicalFlushWriteDispatcher for ProgressDispatcher {
630            async fn dispatch(&self, _: Vec<RegionRequest>) -> error::Result<usize> {
631                unreachable!()
632            }
633            async fn dispatch_tracked(
634                &self,
635                requests: Vec<TrackedWrite>,
636                inputs: usize,
637            ) -> Vec<WriteProgress> {
638                assert_eq!(inputs, 2);
639                assert_eq!(
640                    requests
641                        .iter()
642                        .flat_map(|r| &r.owners)
643                        .copied()
644                        .collect::<Vec<_>>(),
645                    vec![0, 1, 1]
646                );
647                self.0
648                    .iter()
649                    .map(|&(affected_rows, failed)| WriteProgress {
650                        affected_rows,
651                        error: failed.then(|| {
652                            Arc::new(BoxedError::new(
653                                error::InternalSnafu {
654                                    err_msg: "lost acknowledgement",
655                                }
656                                .build(),
657                            ))
658                        }),
659                    })
660                    .collect()
661            }
662        }
663        let ctx = session::context::QueryContext::arc();
664        let ingested = operator::metrics::DIST_INGEST_ROW_COUNT
665            .with_label_values(&[ctx.get_db_string().as_str()]);
666        for (expected_progress, successful_flush, expected_timestamps) in [
667            ([(1, false), (2, false)], true, vec![1000; 3]),
668            ([(1, false), (1, true)], false, vec![1000]),
669            ([(0, true), (0, true)], false, vec![]),
670        ] {
671            let limiter = RequestLimiter::try_new(2).unwrap();
672            let mut waiters = Vec::new();
673            let mut receivers = Vec::new();
674            let counters =
675                [0, 1].map(|_| Arc::new(session::write_progress::WriteProgress::default()));
676            for counter in &counters {
677                let (response_tx, response_rx) = oneshot::channel();
678                waiters.push(FlushWaiter {
679                    _completion: Some(counter.start()),
680                    response_tx,
681                    _permit: limiter.acquire().await.unwrap(),
682                });
683                receivers.push(response_rx);
684            }
685            let batches = [0, 1, 1]
686                .into_iter()
687                .map(|owner| {
688                    let mut batch = mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0);
689                    batch.owner = owner;
690                    batch.progress = Some(counters[owner].clone());
691                    batch
692                })
693                .collect();
694            let (notifier, mut notifications) =
695                FlowNotifier::try_new(1, FLOW_NOTIFICATION_DROPPED.clone()).unwrap();
696            let successes = metrics::FLUSH_TOTAL.get();
697            let failures = metrics::FLUSH_FAILURES.get();
698            let samples = metrics::FLUSH_ROWS.get_sample_count();
699            let sum = metrics::FLUSH_ROWS.get_sample_sum();
700            let dropped = metrics::FLUSH_DROPPED_ROWS.get();
701            let written = ingested.get();
702            flush_batch(
703                Batch {
704                    table_batches: vec![TableBatch {
705                        table_name: "cpu".into(),
706                        table_id: 42,
707                        batches,
708                        row_count: 3,
709                    }],
710                    total_row_count: 3,
711                    db_string: ctx.get_db_string(),
712                    ctx: ctx.clone(),
713                    waiters,
714                },
715                &MockFlushPartitionProvider {
716                    partition_rule_calls: Arc::new(AtomicUsize::new(0)),
717                },
718                &ProgressDispatcher(expected_progress),
719                &MockFlushCatalogProvider {
720                    table: Some(mock_physical_table_metadata(1024)),
721                },
722                notifier,
723            )
724            .await;
725            let expected_written: usize = expected_progress.iter().map(|(rows, _)| rows).sum();
726            assert_eq!(
727                metrics::FLUSH_TOTAL.get(),
728                successes + u64::from(successful_flush)
729            );
730            assert_eq!(
731                metrics::FLUSH_FAILURES.get(),
732                failures + u64::from(!successful_flush)
733            );
734            assert_eq!(
735                metrics::FLUSH_ROWS.get_sample_count(),
736                samples + u64::from(successful_flush)
737            );
738            assert_eq!(
739                metrics::FLUSH_ROWS.get_sample_sum(),
740                sum + if successful_flush { 3.0 } else { 0.0 }
741            );
742            assert_eq!(
743                metrics::FLUSH_DROPPED_ROWS.get(),
744                dropped + (3 - expected_written) as u64
745            );
746            assert_eq!(ingested.get(), written + expected_written as u64);
747            for (counter, (affected_rows, _)) in counters.iter().zip(expected_progress) {
748                counter.wait().await;
749                assert_eq!(counter.written(), affected_rows as u64);
750            }
751            for (receiver, (affected_rows, failed)) in receivers.into_iter().zip(expected_progress)
752            {
753                let result = receiver.await.unwrap();
754                assert_eq!(result.affected_rows, affected_rows);
755                assert_eq!(result.error.is_some(), failed);
756            }
757            if !expected_timestamps.is_empty() {
758                let notification = notifications.try_recv().unwrap();
759                assert_eq!(notification.table_id, 42);
760                assert_eq!(notification.timestamps, expected_timestamps);
761            }
762            assert!(notifications.try_recv().is_err());
763        }
764    }
765
766    #[tokio::test]
767    async fn test_flush_batch_physical_preserves_owners_with_sliced_masks() {
768        use std::sync::Mutex;
769
770        use api::v1::region::{bulk_insert_request, region_request};
771        use arrow::array::{BooleanArray, Float64Array, StringArray, TimestampMillisecondArray};
772        use common_grpc::flight::FlightDecoder;
773        use common_query::WriteProgress;
774        use operator::write_dispatcher::TrackedWrite;
775
776        #[derive(Clone)]
777        struct MaskPartitions {
778            offset: usize,
779            pattern: usize,
780        }
781
782        impl PartitionRule for MaskPartitions {
783            fn as_any(&self) -> &dyn std::any::Any {
784                self
785            }
786
787            fn partition_columns(&self) -> &[String] {
788                &[]
789            }
790
791            fn find_region(&self, _: &[datatypes::prelude::Value]) -> PartitionResult<u32> {
792                unreachable!()
793            }
794
795            fn split_record_batch(
796                &self,
797                batch: &RecordBatch,
798            ) -> PartitionResult<HashMap<u32, RegionMask>> {
799                Ok([false, true]
800                    .into_iter()
801                    .enumerate()
802                    .map(|(region, selected)| {
803                        let values = std::iter::repeat_n(true, self.offset)
804                            .chain((0..batch.num_rows()).map(|row| {
805                                let matches = match self.pattern {
806                                    0 => false,
807                                    1 => true,
808                                    _ => row % 3 != 0,
809                                };
810                                matches == selected
811                            }))
812                            .chain([true; 8])
813                            .collect::<Vec<_>>();
814                        let mask = BooleanArray::from(values).slice(self.offset, batch.num_rows());
815                        (region as u32, RegionMask::from(mask))
816                    })
817                    .collect())
818            }
819        }
820
821        #[async_trait]
822        impl PhysicalFlushPartitionProvider for MaskPartitions {
823            async fn find_table_partition_rule(
824                &self,
825                _: &table::metadata::TableInfo,
826            ) -> PartitionResult<(PartitionRuleRef, HashMap<u32, Option<u64>>)> {
827                Ok((Arc::new(self.clone()), HashMap::new()))
828            }
829        }
830
831        #[derive(Default)]
832        struct RecordingDispatcher(Mutex<Vec<TrackedWrite>>);
833
834        #[async_trait]
835        impl PhysicalFlushWriteDispatcher for RecordingDispatcher {
836            async fn dispatch(&self, _: Vec<RegionRequest>) -> error::Result<usize> {
837                unreachable!()
838            }
839
840            async fn dispatch_tracked(
841                &self,
842                requests: Vec<TrackedWrite>,
843                inputs: usize,
844            ) -> Vec<WriteProgress> {
845                let mut progress = vec![WriteProgress::default(); inputs];
846                for owner in requests.iter().flat_map(|request| &request.owners) {
847                    progress[*owner].affected_rows += 1;
848                }
849                *self.0.lock().unwrap() = requests;
850                progress
851            }
852        }
853
854        let ctx = session::context::QueryContext::arc();
855        let catalog = MockFlushCatalogProvider {
856            table: Some(mock_physical_table_metadata(1024)),
857        };
858        for lengths in [[0; 7], [1; 7], [0, 3, 65, 1, 127, 0, 64]] {
859            let mut expected = Vec::new();
860            let tables = lengths
861                .chunks(4)
862                .enumerate()
863                .map(|(table, lengths)| {
864                    let batches = lengths
865                        .iter()
866                        .enumerate()
867                        .map(|(index, &rows)| {
868                            let owner = [2, 0, 1, 0, 2, 1, 0][table * 4 + index];
869                            let start = expected.len();
870                            expected.extend(std::iter::repeat_n(owner, rows));
871                            let mut batch = mock_aligned_tag_batch("tag1", "host-1", 0, 1.0);
872                            batch.batch = RecordBatch::try_new(
873                                batch.batch.schema(),
874                                vec![
875                                    Arc::new(TimestampMillisecondArray::from_iter_values(
876                                        (start..start + rows).map(|row| row as i64),
877                                    )),
878                                    Arc::new(Float64Array::from(vec![1.0; rows])),
879                                    Arc::new(StringArray::from(vec!["host-1"; rows])),
880                                ],
881                            )
882                            .unwrap();
883                            batch.owner = owner;
884                            batch
885                        })
886                        .collect();
887                    TableBatch {
888                        table_name: format!("logical_{table}"),
889                        table_id: 100 + table as u32,
890                        batches,
891                        row_count: lengths.iter().sum(),
892                    }
893                })
894                .collect::<Vec<_>>();
895            for offset in [0, 1, 7, 65] {
896                for pattern in 0..3 {
897                    let dispatcher = RecordingDispatcher::default();
898                    let affected = flush_batch_physical(
899                        &tables,
900                        "phy",
901                        &ctx,
902                        &MaskPartitions { offset, pattern },
903                        &dispatcher,
904                        &catalog,
905                    )
906                    .await
907                    .unwrap();
908                    assert_eq!(affected, expected.len());
909                    let mut actual = Vec::new();
910                    for write in dispatcher.0.into_inner().unwrap() {
911                        let Some(region_request::Body::BulkInsert(request)) = write.request.body
912                        else {
913                            panic!("expected bulk request")
914                        };
915                        let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = request.body else {
916                            panic!("expected Arrow IPC")
917                        };
918                        let batch = FlightDecoder::try_from_schema_bytes(&ipc.schema)
919                            .unwrap()
920                            .try_decode_record_batch(&ipc.data_header, &ipc.payload)
921                            .unwrap();
922                        assert_eq!(batch.num_rows(), write.owners.len());
923                        let timestamps = batch
924                            .column_by_name("greptime_timestamp")
925                            .unwrap()
926                            .as_any()
927                            .downcast_ref::<TimestampMillisecondArray>()
928                            .unwrap();
929                        assert!(timestamps.values().windows(2).all(|pair| pair[0] < pair[1]));
930                        actual.extend(timestamps.values().iter().copied().zip(write.owners));
931                    }
932                    actual.sort_unstable();
933                    assert_eq!(
934                        actual,
935                        expected
936                            .iter()
937                            .enumerate()
938                            .map(|(row, owner)| (row as i64, *owner))
939                            .collect::<Vec<_>>(),
940                    );
941                }
942            }
943        }
944    }
945
946    #[tokio::test]
947    async fn test_flush_batch_physical_stops_before_partition_and_dispatch_when_table_missing() {
948        let table_batches = vec![TableBatch {
949            table_name: "t1".to_string(),
950            table_id: 11,
951            batches: vec![mock_aligned_tag_batch("tag1", "host-1", 1000, 1.0)],
952            row_count: 1,
953        }];
954        let partition_calls = Arc::new(AtomicUsize::new(0));
955        let dispatcher = MockFlushWriteDispatcher::default();
956        let ctx = session::context::QueryContext::arc();
957
958        let err = flush_batch_physical(
959            &table_batches,
960            "missing_phy",
961            &ctx,
962            &MockFlushPartitionProvider {
963                partition_rule_calls: partition_calls.clone(),
964            },
965            &dispatcher,
966            &MockFlushCatalogProvider { table: None },
967        )
968        .await
969        .unwrap_err();
970
971        assert!(
972            err.to_string()
973                .contains("Physical table 'missing_phy' not found")
974        );
975        assert_eq!(0, partition_calls.load(Ordering::SeqCst));
976        assert_eq!(0, dispatcher.writes.load(Ordering::SeqCst));
977    }
978
979    #[tokio::test]
980    async fn test_flush_batch_physical_aborts_immediately_on_transform_error() {
981        let table_batches = vec![
982            TableBatch {
983                table_name: "broken".to_string(),
984                table_id: 11,
985                batches: vec![mock_aligned_tag_batch("unknown_tag", "host-1", 1000, 1.0)],
986                row_count: 1,
987            },
988            TableBatch {
989                table_name: "healthy".to_string(),
990                table_id: 12,
991                batches: vec![mock_aligned_tag_batch("tag1", "host-2", 2000, 2.0)],
992                row_count: 1,
993            },
994        ];
995        let partition_calls = Arc::new(AtomicUsize::new(0));
996        let dispatcher = MockFlushWriteDispatcher::default();
997        let ctx = session::context::QueryContext::arc();
998
999        let err = flush_batch_physical(
1000            &table_batches,
1001            "phy",
1002            &ctx,
1003            &MockFlushPartitionProvider {
1004                partition_rule_calls: partition_calls.clone(),
1005            },
1006            &dispatcher,
1007            &MockFlushCatalogProvider {
1008                table: Some(mock_physical_table_metadata(1024)),
1009            },
1010        )
1011        .await
1012        .unwrap_err();
1013
1014        assert!(err.to_string().contains("unknown_tag"));
1015        assert_eq!(1, partition_calls.load(Ordering::SeqCst));
1016        assert_eq!(0, dispatcher.writes.load(Ordering::SeqCst));
1017    }
1018
1019    fn mock_physical_table_metadata(table_id: TableId) -> PhysicalTableMetadata {
1020        let schema = Arc::new(
1021            DtSchema::try_new(vec![
1022                DtColumnSchema::new(
1023                    "__primary_key",
1024                    datatypes::prelude::ConcreteDataType::binary_datatype(),
1025                    false,
1026                ),
1027                DtColumnSchema::new(
1028                    "greptime_timestamp",
1029                    datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype(),
1030                    false,
1031                ),
1032                DtColumnSchema::new(
1033                    "greptime_value",
1034                    datatypes::prelude::ConcreteDataType::float64_datatype(),
1035                    true,
1036                ),
1037                DtColumnSchema::new(
1038                    "tag1",
1039                    datatypes::prelude::ConcreteDataType::string_datatype(),
1040                    true,
1041                ),
1042            ])
1043            .unwrap(),
1044        );
1045        let mut table_info = test_table_info(table_id, "phy", "public", "greptime", schema);
1046        table_info.meta.column_ids = vec![0, 1, 2, 3];
1047
1048        PhysicalTableMetadata {
1049            table_info: Arc::new(table_info),
1050            col_name_to_ids: Some(HashMap::from([("tag1".to_string(), 3)])),
1051        }
1052    }
1053
1054    struct MockFlushCatalogProvider {
1055        table: Option<PhysicalTableMetadata>,
1056    }
1057
1058    #[async_trait]
1059    impl PhysicalFlushCatalogProvider for MockFlushCatalogProvider {
1060        async fn physical_table(
1061            &self,
1062            _catalog: &str,
1063            _schema: &str,
1064            _table_name: &str,
1065            _query_ctx: &session::context::QueryContext,
1066        ) -> CatalogResult<Option<PhysicalTableMetadata>> {
1067            Ok(self.table.clone())
1068        }
1069    }
1070
1071    struct SingleRegionPartitionRule;
1072
1073    impl PartitionRule for SingleRegionPartitionRule {
1074        fn as_any(&self) -> &dyn std::any::Any {
1075            self
1076        }
1077
1078        fn partition_columns(&self) -> &[String] {
1079            &[]
1080        }
1081
1082        fn find_region(
1083            &self,
1084            _values: &[datatypes::prelude::Value],
1085        ) -> partition::error::Result<store_api::storage::RegionNumber> {
1086            unimplemented!()
1087        }
1088
1089        fn split_record_batch(
1090            &self,
1091            record_batch: &RecordBatch,
1092        ) -> partition::error::Result<HashMap<store_api::storage::RegionNumber, RegionMask>>
1093        {
1094            Ok(HashMap::from([(
1095                1,
1096                RegionMask::new(
1097                    arrow::array::BooleanArray::from(vec![true; record_batch.num_rows()]),
1098                    record_batch.num_rows(),
1099                ),
1100            )]))
1101        }
1102    }
1103
1104    struct MockFlushPartitionProvider {
1105        partition_rule_calls: Arc<AtomicUsize>,
1106    }
1107
1108    #[async_trait]
1109    impl PhysicalFlushPartitionProvider for MockFlushPartitionProvider {
1110        async fn find_table_partition_rule(
1111            &self,
1112            _table_info: &table::metadata::TableInfo,
1113        ) -> PartitionResult<(PartitionRuleRef, HashMap<u32, Option<u64>>)> {
1114            self.partition_rule_calls.fetch_add(1, Ordering::SeqCst);
1115            Ok((Arc::new(SingleRegionPartitionRule), HashMap::new()))
1116        }
1117    }
1118
1119    #[derive(Default)]
1120    struct MockFlushWriteDispatcher {
1121        writes: Arc<AtomicUsize>,
1122        fail: bool,
1123    }
1124
1125    #[async_trait]
1126    impl PhysicalFlushWriteDispatcher for MockFlushWriteDispatcher {
1127        async fn dispatch(&self, _requests: Vec<RegionRequest>) -> error::Result<usize> {
1128            self.writes.fetch_add(1, Ordering::SeqCst);
1129            if self.fail {
1130                return Err(Error::Internal {
1131                    err_msg: "physical write failed".to_string(),
1132                });
1133            }
1134            Ok(1)
1135        }
1136    }
1137
1138    fn mock_flow_notification_sender(
1139        cache: TableFlownodeSetCacheRef,
1140        node_manager: NodeManagerRef,
1141    ) -> FlowNotifier {
1142        let (tx, rx) = FlowNotifier::try_new(16, FLOW_NOTIFICATION_DROPPED.clone()).unwrap();
1143        start_flow_notification_worker(rx, cache, node_manager);
1144        tx
1145    }
1146
1147    #[derive(Default)]
1148    struct AffectedRowsFlushWriteDispatcher {
1149        affected_rows: usize,
1150    }
1151
1152    #[async_trait]
1153    impl PhysicalFlushWriteDispatcher for AffectedRowsFlushWriteDispatcher {
1154        async fn dispatch(&self, _requests: Vec<RegionRequest>) -> error::Result<usize> {
1155            Ok(self.affected_rows)
1156        }
1157    }
1158}