Skip to main content

operator/
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
15pub(crate) mod exemplar;
16mod otlp;
17
18pub use exemplar::{Exemplar, ExemplarBatch, is_reserved_exemplar_tag};
19pub use otlp::MetricInsertPreflight;
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::{Arc, LazyLock};
24use std::time::{Duration, Instant};
25
26use ahash::{HashMap, HashMapExt, HashSet, HashSetExt};
27use api::v1::alter_table_expr::Kind;
28use api::v1::column_def::{options_from_compression, options_from_skipping, try_as_column_def};
29use api::v1::region::{
30    InsertRequest as RegionInsertRequest, InsertRequests as RegionInsertRequests, RegionRequest,
31    RegionRequestHeader,
32};
33use api::v1::value::ValueData;
34use api::v1::{
35    AlterTableExpr, ColumnDataType, ColumnSchema, CreateTableExpr, InsertRequests,
36    RowInsertRequest, RowInsertRequests, Rows, SemanticType,
37};
38use arrow::datatypes::{DataType as ArrowDataType, Schema as ArrowSchema};
39use arrow::record_batch::RecordBatch;
40use arrow_schema::extension::ExtensionType;
41use catalog::CatalogManagerRef;
42use client::{OutputData, OutputMeta};
43use common_base::readable_size::ReadableSize;
44use common_catalog::consts::{
45    DEFAULT_PRIVATE_SCHEMA_NAME, METRICS_EXEMPLARS_TABLE, PARENT_SPAN_ID_COLUMN,
46    SERVICE_NAME_COLUMN, SPAN_ID_COLUMN, TIMESTAMP_END_COLUMN, TRACE_ID_COLUMN, TRACE_TABLE_NAME,
47    TRACE_TABLE_NAME_SESSION_KEY, default_engine, is_ddl_reserved_table,
48    trace_operations_table_name, trace_services_table_name,
49};
50use common_event_recorder::DEFAULT_EVENTS_TABLE_NAME;
51use common_frontend::slow_query_event::SLOW_QUERY_TABLE_NAME;
52use common_grpc_expr::util::ColumnExpr;
53use common_meta::cache::TableFlownodeSetCacheRef;
54use common_meta::datanode::REGION_STATS_HISTORY_TABLE_NAME;
55use common_meta::node_manager::NodeManagerRef;
56use common_meta::peer::Peer;
57use common_meta::rpc::ddl::TriggerReason;
58use common_query::Output;
59use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type};
60use common_query::prelude::{
61    EXEMPLAR_METRIC_COLUMN, greptime_exemplar_labels, greptime_timestamp, greptime_value,
62};
63use common_telemetry::tracing_context::TracingContext;
64use common_telemetry::{debug, error, warn};
65use common_time::Timestamp;
66use common_time::timestamp::TimeUnit;
67use datatypes::schema::{
68    ColumnDefaultConstraint, ColumnEncoding, CompressionOptions, SkippingIndexOptions,
69};
70use futures_util::{StreamExt, TryStreamExt, future, stream};
71use meter_core::data::MeterRecord;
72use meter_macros::write_meter;
73use partition::manager::PartitionRuleManagerRef;
74use session::context::QueryContextRef;
75use snafu::ResultExt;
76use snafu::prelude::*;
77use sql::partition::partition_rule_for_hexstring;
78use sql::statements::create::Partitions;
79use sql::statements::insert::Insert;
80use store_api::metric_engine_consts::{
81    DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY,
82    METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
83};
84use store_api::mito_engine_options::{
85    APPEND_MODE_KEY, COMPACTION_OPTION_KEYS, COMPACTION_TWCS_PREFIX, COMPACTION_TYPE,
86    COMPACTION_TYPE_TWCS, MERGE_MODE_KEY, TTL_KEY,
87};
88use store_api::storage::consts::ReservedColumnId;
89use store_api::storage::{RegionId, TableId};
90use table::TableRef;
91use table::metadata::{TableInfo, TableInfoRef};
92use table::requests::{
93    AUTO_CREATE_TABLE_KEY, InsertRequest as TableInsertRequest, SEMANTIC_PER_TABLE_INDEX_KEY,
94    SEMANTIC_PIPELINE, TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1, TABLE_DATA_MODEL_TRACE_V2,
95    TRACE_TABLE_PARTITIONS_HINT_KEY, VALID_TABLE_OPTION_KEYS, is_semantic_option_key,
96    validate_semantic_option,
97};
98use table::table_reference::TableReference;
99use tokio_util::sync::CancellationToken;
100
101use crate::batcher::{ConversionMemoryLimiter, PendingRowsBatcher, PendingRowsPermit};
102use crate::error::{
103    CatalogSnafu, ColumnOptionsSnafu, CreatePartitionRulesSnafu, InvalidInsertRequestSnafu,
104    JoinTaskSnafu, RequestInsertsSnafu, Result, TableNotFoundSnafu, WriteRejectedSnafu,
105};
106use crate::expr_helper;
107use crate::region_req_factory::RegionRequestFactory;
108use crate::req_convert::TablePartitioner;
109use crate::req_convert::common::preprocess_row_insert_requests;
110use crate::req_convert::insert::{
111    ColumnToRow, ImpureDefaultFiller, RowToRegion, StatementToRegion, TableToRegion,
112    estimated_exemplar_record_batch_bytes, estimated_sparse_record_batch_bytes,
113    exemplars_to_sparse_record_batch, fill_reqs_with_impure_default, rows_to_record_batch,
114    sparse_rows_to_record_batch,
115};
116use crate::statement::StatementExecutor;
117use crate::statement::ddl::is_retention_ttl;
118use crate::write_dispatcher::{WriteDispatcher, WriteDispatcherRef};
119
120pub struct Inserter {
121    catalog_manager: CatalogManagerRef,
122    pub(crate) partition_manager: PartitionRuleManagerRef,
123    pub(crate) node_manager: NodeManagerRef,
124    pub(crate) write_dispatcher: WriteDispatcherRef,
125    pub(crate) table_flownode_set_cache: TableFlownodeSetCacheRef,
126    /// Server-side upper bound for auto table creation on write.
127    /// When `false`, missing tables are never auto-created regardless of the
128    /// per-request `auto_create_table` hint. When `true`, the hint still applies.
129    auto_create_table: bool,
130    /// Time index unit for physical metric tables created by auto table creation.
131    /// New logical tables created under such a physical table inherit its unit,
132    /// so all metric-engine ingestion paths write timestamps in this unit.
133    /// Defaults to milliseconds for compatibility.
134    auto_create_physical_table_timestamp_unit: TimeUnit,
135    pending_rows_batcher: Option<Arc<dyn PendingRowsBatcher>>,
136    conversion_memory_limiter: Option<Arc<dyn ConversionMemoryLimiter>>,
137    /// Rows handed to detached flow mirror tasks that have not finished yet.
138    /// Bounds how much row data in-flight mirror writes may keep alive, see
139    /// [`MAX_MIRROR_PENDING_ROWS`].
140    mirror_pending_rows: Arc<AtomicU64>,
141}
142
143pub type InserterRef = Arc<Inserter>;
144
145/// Hint for the table type to create automatically.
146#[derive(Clone)]
147pub enum AutoCreateTableType {
148    /// A logical table with the physical table name.
149    Logical(String),
150    /// A physical table.
151    Physical,
152    /// The ordinary sparse append table for metric exemplars.
153    Exemplar,
154    /// A log table which is append-only.
155    Log,
156    /// A table that merges rows by `last_non_null` strategy.
157    LastNonNull,
158    /// Create table that build index and default partition rules on trace_id
159    Trace { alter_existing: bool },
160}
161
162impl AutoCreateTableType {
163    pub fn as_str(&self) -> &'static str {
164        match self {
165            AutoCreateTableType::Logical(_) => "logical",
166            AutoCreateTableType::Physical => "physical",
167            AutoCreateTableType::Exemplar => "exemplar",
168            AutoCreateTableType::Log => "log",
169            AutoCreateTableType::LastNonNull => "last_non_null",
170            AutoCreateTableType::Trace { .. } => "trace",
171        }
172    }
173
174    fn alter_existing(&self) -> bool {
175        !matches!(
176            self,
177            Self::Trace {
178                alter_existing: false
179            }
180        )
181    }
182}
183
184/// Split insert requests into normal and instant requests.
185///
186/// Where instant requests are requests with ttl=instant,
187/// and normal requests are requests with ttl set to other values.
188///
189/// This is used to split requests for different processing.
190#[derive(Clone, Default)]
191pub struct InstantAndNormalInsertRequests {
192    /// Requests with normal ttl.
193    pub normal_requests: RegionInsertRequests,
194    /// Requests with ttl=instant.
195    /// Will be discarded immediately at frontend, wouldn't even insert into memtable, and only sent to flow node if needed.
196    pub instant_requests: RegionInsertRequests,
197}
198
199/// Metric writes bound to the same resolved tables used by their exemplars.
200#[derive(Default)]
201pub struct PreparedMetricInserts {
202    requests: InstantAndNormalInsertRequests,
203    table_infos: HashMap<TableId, TableInfoRef>,
204}
205
206impl PreparedMetricInserts {
207    /// Returns the source tables captured during routing, including auto-created tables.
208    pub fn source_tables(&self) -> impl Iterator<Item = &TableInfoRef> {
209        self.table_infos.values()
210    }
211}
212
213impl Inserter {
214    /// Checks the assumptions of the logical bulk path without changing tables.
215    /// Unsupported requests retain ordinary insertion, including schema policy,
216    /// defaults, instant TTL and row-based Flow delivery.
217    pub async fn can_batch_metric_rows(
218        &self,
219        requests: &RowInsertRequests,
220        ctx: &QueryContextRef,
221        physical_table: &str,
222    ) -> Result<bool> {
223        if self.auto_create_disabled_reason(ctx)?.is_some() || ctx.extension(TTL_KEY).is_some() {
224            return Ok(false);
225        }
226        for request in &requests.inserts {
227            // The logical bulk encoder only supports scalar metric schemas;
228            // any time index unit is accepted — requests are converted to the
229            // destination table's unit during batch alignment.
230            // Check new tables too, before catalog lookup or schema changes.
231            if request.rows.as_ref().is_some_and(|rows| {
232                rows.schema.iter().any(|column| {
233                    column.datatype_extension.is_some()
234                        || !matches!(
235                            ColumnDataType::try_from(column.datatype),
236                            Ok(ColumnDataType::TimestampSecond
237                                | ColumnDataType::TimestampMillisecond
238                                | ColumnDataType::TimestampMicrosecond
239                                | ColumnDataType::TimestampNanosecond
240                                | ColumnDataType::Float64
241                                | ColumnDataType::String)
242                        )
243                })
244            }) {
245                return Ok(false);
246            }
247
248            let Some(table) = self
249                .get_table(
250                    ctx.current_catalog(),
251                    &ctx.current_schema(),
252                    &request.table_name,
253                )
254                .await?
255            else {
256                continue;
257            };
258            let info = table.table_info();
259            if info.meta.engine != METRIC_ENGINE_NAME
260                || info.is_ttl_instant_table()
261                || info
262                    .meta
263                    .options
264                    .extra_options
265                    .get(LOGICAL_TABLE_METADATA_KEY)
266                    .map(String::as_str)
267                    != Some(physical_table)
268                || info
269                    .meta
270                    .schema
271                    .column_schemas()
272                    .iter()
273                    .any(|column| column.default_constraint().is_some())
274            {
275                return Ok(false);
276            }
277            // Physical metric tags are nullable even when their logical schema
278            // is not. Arrow alignment is stricter than ordinary metric insertion.
279            if info
280                .meta
281                .primary_key_indices
282                .iter()
283                .any(|&index| !info.meta.schema.column_schemas()[index].is_nullable())
284            {
285                return Ok(false);
286            }
287            // The current Flow cache does not distinguish streaming and batch
288            // flows. Keep all Flow sources on the row-based delivery path.
289            match self.table_flownode_set_cache.get(info.table_id()).await {
290                Ok(None) => {}
291                Ok(Some(flows)) if flows.is_empty() => {}
292                _ => return Ok(false),
293            }
294        }
295        Ok(true)
296    }
297
298    /// Meters an original logical-table request before bulk routing, without
299    /// cloning its rows or changing the request boundary used for accounting.
300    pub async fn meter_row_inserts(
301        requests: &mut RowInsertRequests,
302        ctx: &QueryContextRef,
303    ) -> Result<u64> {
304        let metered = InstantAndNormalInsertRequests {
305            normal_requests: RegionInsertRequests {
306                requests: requests
307                    .inserts
308                    .iter_mut()
309                    .map(|request| RegionInsertRequest {
310                        rows: request.rows.take(),
311                        ..Default::default()
312                    })
313                    .collect(),
314            },
315            instant_requests: RegionInsertRequests::default(),
316        };
317        let cost = write_meter!(
318            ctx.current_catalog(),
319            ctx.current_schema(),
320            metered,
321            ctx.write_rows_to_admit(
322                ctx.current_catalog(),
323                &ctx.current_schema(),
324                count_insert_rows(&metered)?
325            ),
326            ctx.channel() as u8
327        )
328        .await
329        .context(WriteRejectedSnafu);
330        for (request, region) in requests
331            .inserts
332            .iter_mut()
333            .zip(metered.normal_requests.requests)
334        {
335            request.rows = region.rows;
336        }
337        cost
338    }
339
340    /// Creates a row inserter with the default write dispatcher.
341    pub fn new(
342        catalog_manager: CatalogManagerRef,
343        partition_manager: PartitionRuleManagerRef,
344        node_manager: NodeManagerRef,
345        table_flownode_set_cache: TableFlownodeSetCacheRef,
346        auto_create_table: bool,
347    ) -> Self {
348        Self {
349            write_dispatcher: Arc::new(WriteDispatcher::new(
350                node_manager.clone(),
351                partition_manager.clone(),
352            )),
353            catalog_manager,
354            partition_manager,
355            node_manager,
356            table_flownode_set_cache,
357            auto_create_table,
358            auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
359            pending_rows_batcher: None,
360            conversion_memory_limiter: None,
361            mirror_pending_rows: Arc::new(AtomicU64::new(0)),
362        }
363    }
364
365    /// Sets the time index unit for auto-created physical metric tables.
366    pub fn with_auto_create_physical_table_timestamp_unit(mut self, unit: TimeUnit) -> Self {
367        self.auto_create_physical_table_timestamp_unit = unit;
368        self
369    }
370
371    /// Installs the shared dispatcher used by direct writes and batch flushes.
372    pub fn with_write_dispatcher(mut self, dispatcher: WriteDispatcherRef) -> Self {
373        self.write_dispatcher = dispatcher;
374        self
375    }
376
377    /// Installs the shared batcher; callers explicitly select its ingestion entry point.
378    pub fn with_pending_rows_batcher(
379        mut self,
380        batcher: Option<Arc<dyn PendingRowsBatcher>>,
381    ) -> Self {
382        self.pending_rows_batcher = batcher;
383        self
384    }
385
386    /// Installs a non-blocking memory limiter for unbatched sparse conversion paths.
387    pub fn with_conversion_memory_limiter(
388        mut self,
389        limiter: Option<Arc<dyn ConversionMemoryLimiter>>,
390    ) -> Self {
391        self.conversion_memory_limiter = limiter;
392        self
393    }
394
395    pub async fn handle_column_inserts(
396        &self,
397        requests: InsertRequests,
398        ctx: QueryContextRef,
399        statement_executor: &StatementExecutor,
400    ) -> Result<Output> {
401        let row_inserts = ColumnToRow::convert(requests)?;
402        self.handle_row_inserts(row_inserts, ctx, statement_executor, false, false)
403            .await
404    }
405
406    /// Handles row inserts request and creates a physical table on demand.
407    pub async fn handle_row_inserts(
408        &self,
409        mut requests: RowInsertRequests,
410        ctx: QueryContextRef,
411        statement_executor: &StatementExecutor,
412        accommodate_existing_schema: bool,
413        is_single_value: bool,
414    ) -> Result<Output> {
415        preprocess_row_insert_requests(&mut requests.inserts)?;
416        self.handle_row_inserts_with_create_type(
417            requests,
418            ctx,
419            statement_executor,
420            AutoCreateTableType::Physical,
421            accommodate_existing_schema,
422            is_single_value,
423        )
424        .await
425    }
426
427    /// Inserts exemplars using sparse bulk ingestion, Flow mirroring, and nanosecond auto-create defaults.
428    pub async fn handle_exemplar_inserts(
429        &self,
430        exemplars: ExemplarBatch,
431        ctx: QueryContextRef,
432        statement_executor: &StatementExecutor,
433        sources: &[TableInfoRef],
434    ) -> Result<Output> {
435        if exemplars.is_empty() {
436            let catalog = ctx.current_catalog();
437            let schema = ctx.current_schema();
438            let metered = InstantAndNormalInsertRequests::default();
439            let write_cost = write_meter!(
440                catalog,
441                schema.clone(),
442                metered,
443                ctx.write_rows_to_admit(catalog, &schema, 0),
444                ctx.channel() as u8
445            )
446            .await
447            .context(WriteRejectedSnafu)?;
448            return Ok(Output::new(
449                OutputData::AffectedRows(0),
450                OutputMeta::new_with_cost(write_cost as _),
451            ));
452        }
453
454        let resolved_table_ids = self
455            .resolve_exemplar_sources(&exemplars, &ctx, sources, statement_executor)
456            .await?;
457
458        let mut schema_requests = RowInsertRequests {
459            inserts: vec![RowInsertRequest {
460                table_name: METRICS_EXEMPLARS_TABLE.to_string(),
461                rows: Some(Rows {
462                    schema: exemplars.request_schema()?,
463                    rows: Vec::new(),
464                }),
465            }],
466        };
467        let CreateAlterTableResult {
468            instant_table_ids,
469            table_infos,
470        } = self
471            .create_or_alter_tables_on_demand(
472                &mut schema_requests,
473                &ctx,
474                AutoCreateTableType::Exemplar,
475                statement_executor,
476                false,
477                false,
478                Some(TimeUnit::Nanosecond),
479            )
480            .await?;
481        let destination = table_infos
482            .values()
483            .next()
484            .cloned()
485            .context(TableNotFoundSnafu {
486                table_name: METRICS_EXEMPLARS_TABLE,
487            })?;
488
489        self.execute_exemplar_write(
490            exemplars,
491            resolved_table_ids,
492            destination,
493            !instant_table_ids.is_empty(),
494            ctx,
495        )
496        .await
497    }
498
499    async fn resolve_exemplar_sources(
500        &self,
501        exemplars: &ExemplarBatch,
502        ctx: &QueryContextRef,
503        sources: &[TableInfoRef],
504        statement_executor: &StatementExecutor,
505    ) -> Result<HashMap<String, TableId>> {
506        let mut tables = HashMap::new();
507        for info in sources.iter().filter(|info| {
508            info.catalog_name == ctx.current_catalog() && info.schema_name == ctx.current_schema()
509        }) {
510            if let Some(previous) = tables.insert(info.name.clone(), info.clone()) {
511                ensure!(
512                    previous.table_id() == info.table_id(),
513                    InvalidInsertRequestSnafu {
514                        reason: format!(
515                            "exemplar source {} changed during write preparation",
516                            info.name
517                        ),
518                    }
519                );
520            }
521        }
522
523        for name in exemplars.sources() {
524            if !tables.contains_key(name) {
525                let table = self
526                    .get_table(ctx.current_catalog(), &ctx.current_schema(), name)
527                    .await?
528                    .with_context(|| InvalidInsertRequestSnafu {
529                        reason: format!(
530                            "exemplar source {name} must be an existing logical metric-engine table"
531                        ),
532                    })?;
533                tables.insert(name.clone(), table.table_info());
534            }
535            let info = &tables[name];
536            ensure!(
537                info.meta.engine == METRIC_ENGINE_NAME
538                    && info
539                        .meta
540                        .options
541                        .extra_options
542                        .contains_key(LOGICAL_TABLE_METADATA_KEY),
543                InvalidInsertRequestSnafu {
544                    reason: format!(
545                        "exemplar source {name} must be an existing logical metric-engine table"
546                    ),
547                }
548            );
549        }
550
551        let mut required_tags = BTreeMap::<String, BTreeSet<String>>::new();
552        let mut last_series: Option<(&str, &BTreeMap<String, String>)> = None;
553        for exemplar in exemplars.exemplars() {
554            let series_ref: &BTreeMap<String, String> = &exemplar.series_labels;
555            if let Some((prev_metric, prev_series)) = last_series
556                && prev_metric == exemplar.metric.as_ref()
557                && std::ptr::eq(prev_series, series_ref)
558            {
559                continue;
560            }
561            let tags = required_tags
562                .entry(exemplar.metric.to_string())
563                .or_default();
564            for name in series_ref.keys() {
565                if !tags.contains(name) {
566                    tags.insert(name.clone());
567                }
568            }
569            last_series = Some((exemplar.metric.as_ref(), series_ref));
570        }
571
572        let mut alters = Vec::new();
573        let mut refresh = Vec::new();
574        for (name, tags) in required_tags {
575            let info = &tables[&name];
576            let tags = tags
577                .into_iter()
578                .map(|name| api::v1::helper::tag_column_schema(&name, ColumnDataType::String))
579                .collect::<Vec<_>>();
580            if let Some(add_columns) = exemplar_source_add_columns(info, &tags)? {
581                ensure!(
582                    self.auto_create_disabled_reason(ctx)?.is_none(),
583                    InvalidInsertRequestSnafu {
584                        reason: format!(
585                            "exemplar source {name} requires new tags, but automatic DDL is disabled"
586                        ),
587                    }
588                );
589                alters.push((
590                    info.table_id(),
591                    AlterTableExpr {
592                        catalog_name: info.catalog_name.clone(),
593                        schema_name: info.schema_name.clone(),
594                        table_name: name,
595                        kind: Some(Kind::AddColumns(add_columns)),
596                    },
597                ));
598                refresh.push((info.clone(), tags));
599            }
600        }
601        if !alters.is_empty() {
602            if let Some(table) = self
603                .get_table(
604                    ctx.current_catalog(),
605                    &ctx.current_schema(),
606                    METRICS_EXEMPLARS_TABLE,
607                )
608                .await?
609            {
610                // Reject an incompatible destination before changing any source schema.
611                validate_exemplar_table(&table.table_info())?;
612            }
613            statement_executor
614                .alter_logical_tables_with_ids(alters, ctx.clone(), TriggerReason::AutoAlter)
615                .await?;
616            for (pinned, tags) in refresh {
617                let table = self
618                    .get_table(&pinned.catalog_name, &pinned.schema_name, &pinned.name)
619                    .await?
620                    .with_context(|| InvalidInsertRequestSnafu {
621                        reason: format!(
622                            "exemplar source {} disappeared during reconciliation",
623                            pinned.name
624                        ),
625                    })?;
626                let info = table.table_info();
627                ensure!(
628                    info.table_id() == pinned.table_id(),
629                    InvalidInsertRequestSnafu {
630                        reason: format!(
631                            "exemplar source {} changed during reconciliation",
632                            pinned.name
633                        ),
634                    }
635                );
636                // Concurrent ADD IF NOT EXISTS can succeed on names alone; verify their definitions.
637                ensure!(
638                    exemplar_source_add_columns(&info, &tags)?.is_none(),
639                    InvalidInsertRequestSnafu {
640                        reason: format!(
641                            "exemplar source {} is still missing inherited tags",
642                            pinned.name
643                        ),
644                    }
645                );
646                tables.insert(pinned.name.clone(), info);
647            }
648        }
649
650        Ok(tables
651            .into_iter()
652            .map(|(name, info)| (name, info.table_id()))
653            .collect())
654    }
655
656    async fn meter_and_mirror_exemplars(
657        &self,
658        exemplars: &ExemplarBatch,
659        resolved_table_ids: &HashMap<String, TableId>,
660        destination: &TableInfoRef,
661        is_instant: bool,
662        has_flow: bool,
663        ctx: &QueryContextRef,
664    ) -> Result<u64> {
665        let catalog = destination.catalog_name.as_str();
666        let schema = destination.schema_name.clone();
667        let rows_to_admit = ctx.write_rows_to_admit(catalog, &schema, exemplars.len() as u64);
668        let channel = ctx.channel() as u8;
669        if has_flow {
670            let metered = build_exemplar_metered_requests(
671                exemplars.to_unpadded_region_requests(resolved_table_ids, destination)?,
672                is_instant,
673            );
674            let write_cost = write_meter!(catalog, schema, metered, rows_to_admit, channel)
675                .await
676                .context(WriteRejectedSnafu)?;
677            let requests = if is_instant {
678                metered.instant_requests.requests.iter()
679            } else {
680                metered.normal_requests.requests.iter()
681            };
682            let flow_mirror_task =
683                FlowMirrorTask::new(&self.table_flownode_set_cache, requests).await?;
684            flow_mirror_task.detach(
685                self.node_manager.clone(),
686                self.mirror_pending_rows.clone(),
687                is_instant,
688            )?;
689            return Ok(write_cost);
690        }
691
692        write_meter!(
693            catalog,
694            schema,
695            build_exemplar_metered_requests(
696                exemplars.to_unpadded_region_requests(resolved_table_ids, destination)?,
697                is_instant,
698            ),
699            rows_to_admit,
700            channel
701        )
702        .await
703        .context(WriteRejectedSnafu)
704    }
705
706    async fn execute_exemplar_write(
707        &self,
708        exemplars: ExemplarBatch,
709        resolved_table_ids: HashMap<String, TableId>,
710        destination: TableInfoRef,
711        is_instant: bool,
712        ctx: QueryContextRef,
713    ) -> Result<Output> {
714        let is_instant = is_instant || destination.is_ttl_instant_table();
715        let has_flow = self.table_has_flow(destination.table_id()).await;
716
717        if is_instant {
718            exemplars.validate_destination_tags(&destination.name, |tag| {
719                destination.meta.schema.contains_column(tag)
720            })?;
721            if !has_flow {
722                exemplars.validate_for_destination(&resolved_table_ids, &destination)?;
723            }
724            let write_cost = self
725                .meter_and_mirror_exemplars(
726                    &exemplars,
727                    &resolved_table_ids,
728                    &destination,
729                    true,
730                    has_flow,
731                    &ctx,
732                )
733                .await?;
734            return Ok(Output::new(
735                OutputData::AffectedRows(0),
736                OutputMeta::new_with_cost(write_cost as _),
737            ));
738        }
739
740        if !has_flow && let Some(batcher) = self.table_batcher(&destination, &ctx) {
741            let estimated_bytes = if batcher.memory_limit_bytes() != 0 {
742                estimated_exemplar_record_batch_bytes(&exemplars, &destination)
743            } else {
744                Some(0)
745            };
746            let permit = batcher
747                .acquire(
748                    estimated_bytes.unwrap_or(usize::MAX),
749                    ctx.held_memory_bytes(),
750                )
751                .await?;
752            let batch =
753                exemplars_to_sparse_record_batch(&exemplars, &resolved_table_ids, &destination)?;
754            let write_cost = self
755                .meter_and_mirror_exemplars(
756                    &exemplars,
757                    &resolved_table_ids,
758                    &destination,
759                    false,
760                    false,
761                    &ctx,
762                )
763                .await?;
764
765            let mut target_ctx = ctx.fork();
766            target_ctx.set_current_catalog(&destination.catalog_name);
767            target_ctx.set_current_schema(&destination.schema_name);
768            let output = batcher
769                .submit(destination, batch, Arc::new(target_ctx), permit)
770                .await;
771            return collect_batcher_outputs(vec![output], write_cost as _, &ctx).await;
772        }
773
774        let permit = self.reserve_conversion_memory_with(
775            || estimated_exemplar_record_batch_bytes(&exemplars, &destination),
776            &ctx,
777        )?;
778        let batch =
779            exemplars_to_sparse_record_batch(&exemplars, &resolved_table_ids, &destination)?;
780        let write_cost = self
781            .meter_and_mirror_exemplars(
782                &exemplars,
783                &resolved_table_ids,
784                &destination,
785                false,
786                has_flow,
787                &ctx,
788            )
789            .await?;
790
791        self.dispatch_sparse_bulk_batch(
792            &destination,
793            batch,
794            &ctx,
795            ctx.skip_wal(),
796            write_cost as _,
797            permit,
798        )
799        .await
800    }
801
802    /// Handles row inserts request and creates a log table on demand.
803    pub async fn handle_log_inserts(
804        &self,
805        requests: RowInsertRequests,
806        ctx: QueryContextRef,
807        statement_executor: &StatementExecutor,
808    ) -> Result<Output> {
809        self.handle_row_inserts_with_create_type(
810            requests,
811            ctx,
812            statement_executor,
813            AutoCreateTableType::Log,
814            false,
815            false,
816        )
817        .await
818    }
819
820    pub async fn handle_trace_inserts(
821        &self,
822        requests: RowInsertRequests,
823        ctx: QueryContextRef,
824        statement_executor: &StatementExecutor,
825    ) -> Result<Output> {
826        self.handle_row_inserts_with_create_type(
827            requests,
828            ctx,
829            statement_executor,
830            AutoCreateTableType::Trace {
831                alter_existing: true,
832            },
833            false,
834            false,
835        )
836        .await
837    }
838
839    /// Handles row inserts request and creates a table with `last_non_null` merge mode on demand.
840    pub async fn handle_last_non_null_inserts(
841        &self,
842        requests: RowInsertRequests,
843        ctx: QueryContextRef,
844        statement_executor: &StatementExecutor,
845        accommodate_existing_schema: bool,
846        is_single_value: bool,
847    ) -> Result<Output> {
848        self.handle_row_inserts_with_create_type(
849            requests,
850            ctx,
851            statement_executor,
852            AutoCreateTableType::LastNonNull,
853            accommodate_existing_schema,
854            is_single_value,
855        )
856        .await
857    }
858
859    /// Handles row inserts request with specified [AutoCreateTableType].
860    async fn handle_row_inserts_with_create_type(
861        &self,
862        mut requests: RowInsertRequests,
863        ctx: QueryContextRef,
864        statement_executor: &StatementExecutor,
865        create_type: AutoCreateTableType,
866        accommodate_existing_schema: bool,
867        is_single_value: bool,
868    ) -> Result<Output> {
869        let skip_wal = ctx.skip_wal();
870        let align_time_index_unit =
871            matches!(create_type, AutoCreateTableType::Exemplar).then_some(TimeUnit::Nanosecond);
872
873        let batcher = self
874            .pending_rows_batcher
875            .as_ref()
876            .filter(|_| ctx.batching_enabled());
877
878        // remove empty requests
879        requests.inserts.retain(|req| {
880            req.rows
881                .as_ref()
882                .map(|r| !r.rows.is_empty())
883                .unwrap_or_default()
884        });
885        validate_column_count_match(&requests)?;
886
887        let CreateAlterTableResult {
888            instant_table_ids,
889            table_infos,
890        } = self
891            .create_or_alter_tables_on_demand(
892                &mut requests,
893                &ctx,
894                create_type,
895                statement_executor,
896                accommodate_existing_schema,
897                is_single_value,
898                align_time_index_unit,
899            )
900            .await?;
901
902        // Instant tables have no persisted data for dirty-window Flow to read.
903        // Metric tables keep their existing dedicated ingestion path.
904        // Subscribed Flow sources stay off the batcher so streaming Flows receive rows.
905        if let Some(batcher) = batcher
906            && instant_table_ids.is_empty()
907            && table_infos
908                .values()
909                .all(|info| info.meta.engine == default_engine())
910            && !self.any_table_has_flow(table_infos.keys().copied()).await
911        {
912            return self
913                .submit_pending_rows(requests, table_infos, skip_wal, ctx, batcher)
914                .await;
915        }
916
917        if table_infos.values().any(|info| info.is_sparse_mito_table()) {
918            return self
919                .dispatch_direct_sparse_row_inserts(
920                    requests,
921                    table_infos,
922                    instant_table_ids,
923                    skip_wal,
924                    &ctx,
925                )
926                .await;
927        }
928
929        let name_to_info = table_infos
930            .values()
931            .map(|info| (info.name.clone(), info.clone()))
932            .collect::<HashMap<_, _>>();
933        let inserts = RowToRegion::new(
934            name_to_info,
935            instant_table_ids,
936            self.partition_manager.as_ref(),
937        )
938        .convert(requests, skip_wal)
939        .await?;
940
941        self.do_request(inserts, &table_infos, &ctx).await
942    }
943
944    async fn submit_pending_rows(
945        &self,
946        mut requests: RowInsertRequests,
947        table_infos: HashMap<TableId, Arc<TableInfo>>,
948        skip_wal: bool,
949        ctx: QueryContextRef,
950        batcher: &Arc<dyn PendingRowsBatcher>,
951    ) -> Result<Output> {
952        // All entry points, including single-table and SQL writes, skip empty input
953        // before evaluating defaults or converting prepared rows.
954        requests.inserts.retain(|request| {
955            request
956                .rows
957                .as_ref()
958                .is_some_and(|rows| !rows.rows.is_empty())
959        });
960        let by_name = table_infos
961            .values()
962            .map(|info| (info.name.as_str(), info))
963            .collect::<HashMap<_, _>>();
964        let mut estimated_bytes = Some(0usize);
965        for request in &mut requests.inserts {
966            let table_info =
967                by_name
968                    .get(request.table_name.as_str())
969                    .context(TableNotFoundSnafu {
970                        table_name: &request.table_name,
971                    })?;
972            let Some(rows) = &mut request.rows else {
973                continue;
974            };
975            ImpureDefaultFiller::new((*table_info).clone())?.fill_rows(rows);
976            if batcher.memory_limit_bytes() != 0 {
977                let item_bytes = if table_info.is_sparse_mito_table() {
978                    estimated_sparse_record_batch_bytes(rows, table_info)
979                } else {
980                    crate::req_convert::insert::estimated_record_batch_bytes(rows, table_info)
981                };
982                estimated_bytes = estimated_bytes.and_then(|bytes| bytes.checked_add(item_bytes?));
983            }
984        }
985        // Reserve once for the whole request before constructing any Arrow arrays.
986        // PB rows and the converted batches coexist, so this is additional memory.
987        let permit = if requests.inserts.is_empty() {
988            None
989        } else {
990            Some(
991                batcher
992                    .acquire(
993                        estimated_bytes.unwrap_or(usize::MAX),
994                        ctx.held_memory_bytes(),
995                    )
996                    .await?,
997            )
998        };
999        let mut prepared = Vec::with_capacity(requests.inserts.len());
1000        for request in &requests.inserts {
1001            let table_info = by_name[request.table_name.as_str()];
1002            if let Some(rows) = &request.rows {
1003                let batch = if table_info.is_sparse_mito_table() {
1004                    sparse_rows_to_record_batch(rows, table_info)?
1005                } else {
1006                    rows_to_record_batch(rows, table_info)?
1007                };
1008                prepared.push(((*table_info).clone(), batch));
1009            }
1010        }
1011        // Preserve the existing meter input and original request boundary. These
1012        // envelopes are only for accounting; routing happens after batching.
1013        let metered = InstantAndNormalInsertRequests {
1014            normal_requests: RegionInsertRequests {
1015                requests: requests
1016                    .inserts
1017                    .into_iter()
1018                    .map(|request| RegionInsertRequest {
1019                        rows: request.rows,
1020                        ..Default::default()
1021                    })
1022                    .collect(),
1023            },
1024            instant_requests: RegionInsertRequests::default(),
1025        };
1026        let table_info = table_infos.values().next();
1027        let catalog = table_info.map_or(ctx.current_catalog(), |info| info.catalog_name.as_str());
1028        let schema =
1029            table_info.map_or_else(|| ctx.current_schema(), |info| info.schema_name.clone());
1030        let write_cost = write_meter!(
1031            catalog,
1032            &schema,
1033            metered,
1034            ctx.write_rows_to_admit(catalog, &schema, count_insert_rows(&metered)?),
1035            ctx.channel() as u8
1036        )
1037        .await
1038        .context(WriteRejectedSnafu)?;
1039        prepared.retain(|(_, batch)| batch.num_rows() != 0);
1040        let results = if let Some(permit) = permit {
1041            // One original request shares admission across all table submissions.
1042            let submissions = prepared.into_iter().map(|(info, batch)| {
1043                // Route to the same target database used for admission above.
1044                let mut target_ctx = ctx.fork();
1045                target_ctx.set_current_catalog(&info.catalog_name);
1046                target_ctx.set_current_schema(&info.schema_name);
1047                target_ctx.set_skip_wal(skip_wal);
1048                batcher.submit(info, batch, Arc::new(target_ctx), permit.clone())
1049            });
1050            // Observe every table completion even when another table fails.
1051            future::join_all(submissions).await
1052        } else {
1053            Vec::new()
1054        };
1055        collect_batcher_outputs(results, write_cost as _, &ctx).await
1056    }
1057
1058    /// Handles row inserts request with metric engine.
1059    ///
1060    /// Resolves or creates `physical_table` only when a logical target is missing.
1061    /// Existing targets retain their backing tables and time-index units.
1062    pub async fn handle_metric_row_inserts(
1063        &self,
1064        requests: RowInsertRequests,
1065        ctx: QueryContextRef,
1066        statement_executor: &StatementExecutor,
1067        physical_table: String,
1068    ) -> Result<Output> {
1069        let prepared = self
1070            .prepare_metric_row_inserts(requests, ctx.clone(), statement_executor, physical_table)
1071            .await?;
1072        self.handle_prepared_metric_inserts(prepared, ctx).await
1073    }
1074
1075    /// Resolves schemas and routes metric rows before dependent exemplar writes start.
1076    pub async fn prepare_metric_row_inserts(
1077        &self,
1078        mut requests: RowInsertRequests,
1079        ctx: QueryContextRef,
1080        statement_executor: &StatementExecutor,
1081        physical_table: String,
1082    ) -> Result<PreparedMetricInserts> {
1083        let skip_wal = ctx.skip_wal();
1084
1085        // remove empty requests
1086        requests.inserts.retain(|req| {
1087            req.rows
1088                .as_ref()
1089                .map(|r| !r.rows.is_empty())
1090                .unwrap_or_default()
1091        });
1092        validate_column_count_match(&requests)?;
1093
1094        // The selected backing table is needed only by new logical targets.
1095        let mut has_new_tables = false;
1096        for request in &requests.inserts {
1097            if self
1098                .get_table(
1099                    ctx.current_catalog(),
1100                    &ctx.current_schema(),
1101                    &request.table_name,
1102                )
1103                .await?
1104                .is_none()
1105            {
1106                has_new_tables = true;
1107                break;
1108            }
1109        }
1110        let new_table_unit = if has_new_tables {
1111            let physical = self
1112                .create_physical_table_on_demand(&ctx, physical_table.clone(), statement_executor)
1113                .await?;
1114            table_time_index_unit(&physical)
1115        } else {
1116            None
1117        };
1118        let CreateAlterTableResult {
1119            instant_table_ids,
1120            table_infos,
1121        } = self
1122            .create_or_alter_tables_on_demand(
1123                &mut requests,
1124                &ctx,
1125                AutoCreateTableType::Logical(physical_table.clone()),
1126                statement_executor,
1127                true,
1128                true,
1129                new_table_unit,
1130            )
1131            .await?;
1132        let name_to_info = table_infos
1133            .values()
1134            .map(|info| (info.name.clone(), info.clone()))
1135            .collect::<HashMap<_, _>>();
1136        let inserts = RowToRegion::new(name_to_info, instant_table_ids, &self.partition_manager)
1137            .convert(requests, skip_wal)
1138            .await?;
1139
1140        Ok(PreparedMetricInserts {
1141            requests: inserts,
1142            table_infos,
1143        })
1144    }
1145
1146    /// Dispatches metric rows using the source table definitions captured during preparation.
1147    pub async fn handle_prepared_metric_inserts(
1148        &self,
1149        prepared: PreparedMetricInserts,
1150        ctx: QueryContextRef,
1151    ) -> Result<Output> {
1152        self.do_request(prepared.requests, &prepared.table_infos, &ctx)
1153            .await
1154    }
1155
1156    fn table_batcher(
1157        &self,
1158        table_info: &TableInfoRef,
1159        ctx: &QueryContextRef,
1160    ) -> Option<&Arc<dyn PendingRowsBatcher>> {
1161        self.pending_rows_batcher.as_ref().filter(|_| {
1162            ctx.batching_enabled()
1163                && !table_info.is_ttl_instant_table()
1164                && table_info.meta.engine == default_engine()
1165        })
1166    }
1167
1168    async fn submit_table_rows(
1169        &self,
1170        rows: Rows,
1171        table_info: TableInfoRef,
1172        skip_wal: bool,
1173        ctx: QueryContextRef,
1174        batcher: &Arc<dyn PendingRowsBatcher>,
1175    ) -> Result<Output> {
1176        let requests = RowInsertRequests {
1177            inserts: vec![RowInsertRequest {
1178                table_name: table_info.name.clone(),
1179                rows: Some(rows),
1180            }],
1181        };
1182        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info)]);
1183        self.submit_pending_rows(requests, table_infos, skip_wal, ctx, batcher)
1184            .await
1185    }
1186
1187    async fn table_has_flow(&self, table_id: TableId) -> bool {
1188        match self.table_flownode_set_cache.get(table_id).await {
1189            Ok(None) => false,
1190            Ok(Some(flows)) if flows.is_empty() => false,
1191            _ => true,
1192        }
1193    }
1194
1195    async fn any_table_has_flow(&self, table_ids: impl IntoIterator<Item = TableId>) -> bool {
1196        stream::iter(table_ids)
1197            .map(|table_id| self.table_has_flow(table_id))
1198            .buffer_unordered(MAX_CONCURRENT_FLOW_LOOKUPS)
1199            .any(future::ready)
1200            .await
1201    }
1202
1203    async fn eligible_table_batcher(
1204        &self,
1205        table_info: &TableInfoRef,
1206        ctx: &QueryContextRef,
1207    ) -> Option<&Arc<dyn PendingRowsBatcher>> {
1208        let batcher = self.table_batcher(table_info, ctx)?;
1209        (!self.table_has_flow(table_info.table_id()).await).then_some(batcher)
1210    }
1211
1212    fn reserve_conversion_memory_with(
1213        &self,
1214        estimate: impl FnOnce() -> Option<usize>,
1215        ctx: &QueryContextRef,
1216    ) -> Result<Option<PendingRowsPermit>> {
1217        let Some(limiter) = &self.conversion_memory_limiter else {
1218            return Ok(None);
1219        };
1220        if limiter.limit_bytes() == 0 {
1221            return Ok(None);
1222        }
1223        let bytes = estimate().unwrap_or(usize::MAX);
1224        Ok(Some(limiter.reserve(bytes, ctx.held_memory_bytes())?))
1225    }
1226
1227    async fn dispatch_single_sparse_table_rows(
1228        &self,
1229        rows: Rows,
1230        table_info: TableInfoRef,
1231        skip_wal: bool,
1232        ctx: &QueryContextRef,
1233    ) -> Result<Output> {
1234        let mut instant_table_ids = HashSet::new();
1235        if table_info.is_ttl_instant_table() {
1236            instant_table_ids.insert(table_info.table_id());
1237        }
1238        let requests = RowInsertRequests {
1239            inserts: vec![RowInsertRequest {
1240                table_name: table_info.name.clone(),
1241                rows: Some(rows),
1242            }],
1243        };
1244        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info)]);
1245        self.dispatch_direct_sparse_row_inserts(
1246            requests,
1247            table_infos,
1248            instant_table_ids,
1249            skip_wal,
1250            ctx,
1251        )
1252        .await
1253    }
1254
1255    async fn dispatch_direct_sparse_row_inserts(
1256        &self,
1257        mut requests: RowInsertRequests,
1258        table_infos: HashMap<TableId, Arc<TableInfo>>,
1259        instant_table_ids: HashSet<TableId>,
1260        skip_wal: bool,
1261        ctx: &QueryContextRef,
1262    ) -> Result<Output> {
1263        requests
1264            .inserts
1265            .retain(|req| req.rows.as_ref().is_some_and(|rows| !rows.rows.is_empty()));
1266        let table_info = table_infos.values().next();
1267        let catalog = table_info.map_or(ctx.current_catalog(), |info| info.catalog_name.as_str());
1268        let schema =
1269            table_info.map_or_else(|| ctx.current_schema(), |info| info.schema_name.clone());
1270
1271        if requests.inserts.is_empty() {
1272            let metered = InstantAndNormalInsertRequests::default();
1273            let write_cost = write_meter!(
1274                catalog,
1275                schema.clone(),
1276                metered,
1277                ctx.write_rows_to_admit(catalog, &schema, 0),
1278                ctx.channel() as u8
1279            )
1280            .await
1281            .context(WriteRejectedSnafu)?;
1282            return Ok(Output::new(
1283                OutputData::AffectedRows(0),
1284                OutputMeta::new_with_cost(write_cost as _),
1285            ));
1286        }
1287
1288        let by_name = table_infos
1289            .values()
1290            .map(|info| (info.name.clone(), info.clone()))
1291            .collect::<HashMap<_, _>>();
1292        let is_instant_table = |info: &TableInfo| {
1293            instant_table_ids.contains(&info.table_id()) || info.is_ttl_instant_table()
1294        };
1295        for request in &mut requests.inserts {
1296            let info = by_name
1297                .get(&request.table_name)
1298                .context(TableNotFoundSnafu {
1299                    table_name: &request.table_name,
1300                })?;
1301            if !is_instant_table(info)
1302                && let Some(rows) = &mut request.rows
1303            {
1304                ImpureDefaultFiller::new(info.clone())?.fill_rows(rows);
1305            }
1306        }
1307
1308        let permit = self.reserve_conversion_memory_with(
1309            || {
1310                let mut total = 0usize;
1311                for request in &requests.inserts {
1312                    let info = by_name.get(&request.table_name)?;
1313                    if !is_instant_table(info)
1314                        && info.is_sparse_mito_table()
1315                        && let Some(rows) = &request.rows
1316                    {
1317                        total =
1318                            total.checked_add(estimated_sparse_record_batch_bytes(rows, info)?)?;
1319                    }
1320                }
1321                Some(total)
1322            },
1323            ctx,
1324        )?;
1325
1326        let mut sparse_batches = Vec::new();
1327        let mut sparse_envelopes = Vec::new();
1328        let mut metered = InstantAndNormalInsertRequests::default();
1329        for request in requests.inserts {
1330            let info = &by_name[&request.table_name];
1331            let Some(rows) = request.rows else {
1332                continue;
1333            };
1334            let is_instant = is_instant_table(info);
1335            if info.is_sparse_mito_table() {
1336                if !is_instant {
1337                    sparse_batches.push((info.clone(), sparse_rows_to_record_batch(&rows, info)?));
1338                }
1339                let region_req = RegionInsertRequest {
1340                    region_id: RegionId::new(info.table_id(), 0).as_u64(),
1341                    rows: Some(rows),
1342                    ..Default::default()
1343                };
1344                if is_instant {
1345                    metered.instant_requests.requests.push(region_req);
1346                } else {
1347                    sparse_envelopes.push(region_req);
1348                }
1349            } else {
1350                let partitioned = crate::req_convert::common::partitioner::Partitioner::new(
1351                    &self.partition_manager,
1352                )
1353                .partition_insert_requests(info, rows, skip_wal)
1354                .await?;
1355                if is_instant {
1356                    metered.instant_requests.requests.extend(partitioned);
1357                } else {
1358                    metered.normal_requests.requests.extend(partitioned);
1359                }
1360            }
1361        }
1362
1363        // The suffix is needed for metering and Flow only. Its rows go to storage as Arrow batches.
1364        let dense_request_count = metered.normal_requests.requests.len();
1365        metered.normal_requests.requests.extend(sparse_envelopes);
1366        let write_cost = write_meter!(
1367            catalog,
1368            schema.clone(),
1369            metered,
1370            ctx.write_rows_to_admit(catalog, &schema, count_insert_rows(&metered)?),
1371            ctx.channel() as u8
1372        )
1373        .await
1374        .context(WriteRejectedSnafu)?;
1375
1376        let flow_mirror_task = FlowMirrorTask::new(
1377            &self.table_flownode_set_cache,
1378            metered
1379                .normal_requests
1380                .requests
1381                .iter()
1382                .chain(metered.instant_requests.requests.iter()),
1383        )
1384        .await?;
1385        let has_instant_rows = metered.instant_requests.requests.iter().any(|request| {
1386            request
1387                .rows
1388                .as_ref()
1389                .is_some_and(|rows| !rows.rows.is_empty())
1390        });
1391        flow_mirror_task.detach(
1392            self.node_manager.clone(),
1393            self.mirror_pending_rows.clone(),
1394            has_instant_rows,
1395        )?;
1396        drop(metered.instant_requests);
1397        let mut dense_inserts = metered.normal_requests;
1398        dense_inserts.requests.truncate(dense_request_count);
1399
1400        let mut results = Vec::new();
1401        for (info, batch) in sparse_batches {
1402            results.push(
1403                self.dispatch_sparse_bulk_batch(&info, batch, ctx, skip_wal, 0, permit.clone())
1404                    .await,
1405            );
1406        }
1407        if !dense_inserts.requests.is_empty() {
1408            results.push(
1409                self.dispatch_normal_region_requests(dense_inserts, 0, ctx)
1410                    .await,
1411            );
1412        }
1413        collect_batcher_outputs(results, write_cost as usize, ctx).await
1414    }
1415
1416    async fn dispatch_sparse_bulk_batch(
1417        &self,
1418        table_info: &TableInfoRef,
1419        batch: RecordBatch,
1420        ctx: &QueryContextRef,
1421        skip_wal: bool,
1422        write_cost: usize,
1423        permit: Option<PendingRowsPermit>,
1424    ) -> Result<Output> {
1425        let partitioner = TablePartitioner::try_new(&self.partition_manager, table_info)
1426            .await
1427            .context(crate::error::InvalidPartitionSnafu)?;
1428        let header = Some(RegionRequestHeader {
1429            tracing_context: TracingContext::from_current_span().to_w3c(),
1430            dbname: ctx.get_db_string(),
1431            ..Default::default()
1432        });
1433
1434        if ctx.confirmed_writes() {
1435            let num_rows = batch.num_rows();
1436            let writes = partitioner
1437                .partition_tracked_bulk_insert_requests(batch, vec![0; num_rows], skip_wal)?
1438                .into_iter()
1439                .map(|(request, owners)| crate::write_dispatcher::TrackedWrite {
1440                    request: RegionRequest {
1441                        header: header.clone(),
1442                        body: Some(api::v1::region::region_request::Body::BulkInsert(request)),
1443                    },
1444                    owners,
1445                })
1446                .collect();
1447            return self
1448                .execute_tracked_writes(writes, ctx, write_cost, permit)
1449                .await;
1450        }
1451
1452        let requests = partitioner
1453            .partition_bulk_insert_requests(batch, None, skip_wal)?
1454            .into_iter()
1455            .map(|request| RegionRequest {
1456                header: header.clone(),
1457                body: Some(api::v1::region::region_request::Body::BulkInsert(request)),
1458            })
1459            .collect();
1460        self.execute_untracked_writes(requests, ctx, write_cost, permit)
1461            .await
1462    }
1463
1464    pub async fn handle_table_insert(
1465        &self,
1466        request: TableInsertRequest,
1467        ctx: QueryContextRef,
1468    ) -> Result<Output> {
1469        let catalog = request.catalog_name.as_str();
1470        let schema = request.schema_name.as_str();
1471        let table_name = request.table_name.as_str();
1472        let table = self.get_table(catalog, schema, table_name).await?;
1473        let table = table.with_context(|| TableNotFoundSnafu {
1474            table_name: common_catalog::format_full_table_name(catalog, schema, table_name),
1475        })?;
1476        let table_info = table.table_info();
1477
1478        let converter = TableToRegion::new(&table_info, &self.partition_manager);
1479        let skip_wal = request.skip_wal;
1480        let rows = converter.prepare(request)?;
1481        if let Some(batcher) = self.eligible_table_batcher(&table_info, &ctx).await {
1482            return self
1483                .submit_table_rows(rows, table_info, skip_wal, ctx, batcher)
1484                .await;
1485        }
1486        if table_info.is_sparse_mito_table() {
1487            return self
1488                .dispatch_single_sparse_table_rows(rows, table_info, skip_wal, &ctx)
1489                .await;
1490        }
1491        let inserts = converter.partition(rows, skip_wal).await?;
1492
1493        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
1494
1495        self.do_request(inserts, &table_infos, &ctx).await
1496    }
1497
1498    pub async fn handle_statement_insert(
1499        &self,
1500        insert: &Insert,
1501        ctx: &QueryContextRef,
1502    ) -> Result<Output> {
1503        let converter =
1504            StatementToRegion::new(self.catalog_manager.as_ref(), &self.partition_manager, ctx);
1505        let (rows, table_info) = converter.prepare(insert, ctx).await?;
1506        if let Some(batcher) = self.eligible_table_batcher(&table_info, ctx).await {
1507            return self
1508                .submit_table_rows(rows, table_info, ctx.skip_wal(), ctx.clone(), batcher)
1509                .await;
1510        }
1511        if table_info.is_sparse_mito_table() {
1512            return self
1513                .dispatch_single_sparse_table_rows(rows, table_info, ctx.skip_wal(), ctx)
1514                .await;
1515        }
1516        let inserts = converter.partition(rows, table_info.clone(), ctx).await?;
1517
1518        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
1519
1520        self.do_request(inserts, &table_infos, ctx).await
1521    }
1522}
1523
1524/// Admits a finite request before it is split into internal writes.
1525/// The returned context preserves accounting while preventing a second row debit.
1526pub async fn admit_write(rows: u64, ctx: &QueryContextRef) -> Result<QueryContextRef> {
1527    // The zero value is WCU: this record only admits rows. Actual inserts retain
1528    // their existing WCU accounting, so charging here would count it twice.
1529    write_meter!(MeterRecord::new(
1530        ctx.current_catalog().to_string(),
1531        ctx.current_schema(),
1532        0,
1533        ctx.write_rows_to_admit(ctx.current_catalog(), &ctx.current_schema(), rows),
1534        ctx.channel() as u8,
1535    ))
1536    .await
1537    .context(WriteRejectedSnafu)?;
1538    Ok(Arc::new(ctx.with_write_admission()))
1539}
1540
1541/// Admits all database totals before dispatching any batch of a finite request.
1542/// Each batch keeps its own protocol options and target database.
1543/// Admits a finite set of per-request row counts across one shared per-database
1544/// pass and marks every context to prevent a duplicate downstream row debit.
1545pub async fn admit_insert_row_counts<'a>(
1546    batches: impl IntoIterator<Item = (&'a mut QueryContextRef, u64)>,
1547) -> Result<()> {
1548    let batches: Vec<(&'a mut QueryContextRef, u64)> = batches.into_iter().collect();
1549    let mut totals = BTreeMap::<_, (QueryContextRef, u64)>::new();
1550    for (ctx, rows) in &batches {
1551        let catalog = ctx.current_catalog();
1552        let schema = ctx.current_schema();
1553
1554        if ctx.write_rows_to_admit(catalog, &schema, 1) == 0 {
1555            continue;
1556        }
1557        let (_, total) = totals
1558            .entry((catalog.to_string(), schema.clone()))
1559            .or_insert_with(|| ((*ctx).clone(), 0));
1560        *total = total
1561            .checked_add(*rows)
1562            .context(InvalidInsertRequestSnafu {
1563                reason: "Insert row count exceeds u64::MAX",
1564            })?;
1565    }
1566    for (ctx, rows) in totals.values() {
1567        admit_write(*rows, ctx).await?;
1568    }
1569    for (ctx, _) in batches {
1570        *ctx = Arc::new(ctx.with_write_admission());
1571    }
1572    Ok(())
1573}
1574
1575pub async fn admit_row_insert_batches(
1576    batches: &mut [(QueryContextRef, RowInsertRequests)],
1577) -> Result<()> {
1578    let mut counts = Vec::with_capacity(batches.len());
1579    for (_, requests) in batches.iter() {
1580        let mut total = 0u64;
1581        for rows in requests.inserts.iter().filter_map(|r| r.rows.as_ref()) {
1582            total =
1583                total
1584                    .checked_add(rows.rows.len() as u64)
1585                    .context(InvalidInsertRequestSnafu {
1586                        reason: "Insert row count exceeds u64::MAX",
1587                    })?;
1588        }
1589        counts.push(total);
1590    }
1591    admit_insert_row_counts(
1592        batches
1593            .iter_mut()
1594            .zip(counts)
1595            .map(|((ctx, _), count)| (ctx, count)),
1596    )
1597    .await
1598}
1599
1600fn build_exemplar_metered_requests(
1601    requests: Vec<RegionInsertRequest>,
1602    is_instant: bool,
1603) -> InstantAndNormalInsertRequests {
1604    let wrapped = RegionInsertRequests { requests };
1605    if is_instant {
1606        InstantAndNormalInsertRequests {
1607            normal_requests: RegionInsertRequests::default(),
1608            instant_requests: wrapped,
1609        }
1610    } else {
1611        InstantAndNormalInsertRequests {
1612            normal_requests: wrapped,
1613            instant_requests: RegionInsertRequests::default(),
1614        }
1615    }
1616}
1617
1618async fn collect_batcher_outputs(
1619    results: Vec<Result<Output>>,
1620    write_cost: usize,
1621    ctx: &QueryContextRef,
1622) -> Result<Output> {
1623    let mut affected_rows = 0;
1624    let mut meta = OutputMeta::new_with_cost(write_cost);
1625    let mut first_error = None;
1626    for result in results {
1627        match result {
1628            Ok(output) => {
1629                affected_rows += output.extract_rows_and_cost().0;
1630                meta.write_completions.extend(output.meta.write_completions);
1631            }
1632            Err(error) if ctx.confirmed_writes() => {
1633                meta.write_completions
1634                    .push(common_query::WriteCompletion::with_progress(async move {
1635                        common_query::WriteProgress::failed(common_error::ext::BoxedError::new(
1636                            error,
1637                        ))
1638                    }));
1639            }
1640            Err(error) => {
1641                first_error.get_or_insert(error);
1642            }
1643        }
1644    }
1645    if let Some(error) = first_error {
1646        for completion in meta.write_completions {
1647            let _ = completion.wait().await;
1648        }
1649        return Err(error);
1650    }
1651    Ok(Output::new(OutputData::AffectedRows(affected_rows), meta))
1652}
1653
1654fn count_insert_rows(requests: &InstantAndNormalInsertRequests) -> Result<u64> {
1655    requests
1656        .normal_requests
1657        .requests
1658        .iter()
1659        .chain(&requests.instant_requests.requests)
1660        .filter_map(|request| request.rows.as_ref())
1661        .try_fold(0u64, |total, rows| {
1662            total
1663                .checked_add(rows.rows.len() as u64)
1664                .context(InvalidInsertRequestSnafu {
1665                    reason: "Insert row count exceeds u64::MAX",
1666                })
1667        })
1668}
1669
1670impl Inserter {
1671    async fn do_request(
1672        &self,
1673        requests: InstantAndNormalInsertRequests,
1674        table_infos: &HashMap<TableId, Arc<TableInfo>>,
1675        ctx: &QueryContextRef,
1676    ) -> Result<Output> {
1677        // Fill impure default values in the request
1678        let requests = fill_reqs_with_impure_default(table_infos, requests)?;
1679
1680        // All tables in a batch resolve to the same database. Qualified SQL
1681        // inserts may target a different database than the session's current one.
1682        let table_info = table_infos.values().next();
1683        let catalog = table_info.map_or(ctx.current_catalog(), |info| info.catalog_name.as_str());
1684        let schema =
1685            table_info.map_or_else(|| ctx.current_schema(), |info| info.schema_name.clone());
1686        let write_cost = write_meter!(
1687            catalog,
1688            schema.clone(),
1689            requests,
1690            ctx.write_rows_to_admit(catalog, &schema, count_insert_rows(&requests)?),
1691            ctx.channel() as u8
1692        )
1693        .await
1694        .context(WriteRejectedSnafu)?;
1695
1696        let InstantAndNormalInsertRequests {
1697            normal_requests,
1698            instant_requests,
1699        } = requests;
1700
1701        // Mirror requests for source table to flownode asynchronously
1702        let flow_mirror_task = FlowMirrorTask::new(
1703            &self.table_flownode_set_cache,
1704            normal_requests
1705                .requests
1706                .iter()
1707                .chain(instant_requests.requests.iter()),
1708        )
1709        .await?;
1710        let has_instant_rows = instant_requests.requests.iter().any(|request| {
1711            request
1712                .rows
1713                .as_ref()
1714                .is_some_and(|rows| !rows.rows.is_empty())
1715        });
1716        flow_mirror_task.detach(
1717            self.node_manager.clone(),
1718            self.mirror_pending_rows.clone(),
1719            has_instant_rows,
1720        )?;
1721
1722        self.dispatch_normal_region_requests(normal_requests, write_cost as _, ctx)
1723            .await
1724    }
1725
1726    async fn execute_tracked_writes(
1727        &self,
1728        writes: Vec<crate::write_dispatcher::TrackedWrite>,
1729        ctx: &QueryContextRef,
1730        write_cost: usize,
1731        permit: Option<PendingRowsPermit>,
1732    ) -> Result<Output> {
1733        let dispatcher = self.write_dispatcher.clone();
1734        let (writes, progress) = dispatcher.prepare_tracked(writes, 1).await;
1735        let cancellation = CancellationToken::new();
1736        let _guard = cancellation.clone().drop_guard();
1737        let counter = ctx.write_progress().cloned();
1738        let progress = common_runtime::spawn_global(async move {
1739            let _permit = permit;
1740            let progress = dispatcher
1741                .execute_tracked(writes, progress, None, Some(&cancellation))
1742                .await;
1743            if let Some(counter) = counter {
1744                counter.add_written(progress.iter().map(|part| part.affected_rows).sum());
1745            }
1746            progress
1747        })
1748        .await
1749        .context(JoinTaskSnafu)?
1750        .into_iter()
1751        .fold(
1752            common_query::WriteProgress::default(),
1753            |mut result, part| {
1754                result.merge(part);
1755                result
1756            },
1757        );
1758        crate::metrics::DIST_INGEST_ROW_COUNT
1759            .with_label_values(&[ctx.get_db_string().as_str()])
1760            .inc_by(progress.affected_rows as u64);
1761        let mut meta = OutputMeta::new_with_cost(write_cost);
1762        let rows = progress.affected_rows;
1763        meta.write_completions
1764            .push(common_query::WriteCompletion::with_progress(async move {
1765                progress
1766            }));
1767        Ok(Output::new(OutputData::AffectedRows(rows), meta))
1768    }
1769
1770    async fn execute_untracked_writes(
1771        &self,
1772        requests: Vec<RegionRequest>,
1773        ctx: &QueryContextRef,
1774        write_cost: usize,
1775        permit: Option<PendingRowsPermit>,
1776    ) -> Result<Output> {
1777        let dispatcher = self.write_dispatcher.clone();
1778        let writes = dispatcher.prepare(requests).await?;
1779        // Dropping the caller stops retries without abandoning in-flight writes.
1780        let cancellation = CancellationToken::new();
1781        let _guard = cancellation.clone().drop_guard();
1782        let progress = ctx.write_progress().cloned();
1783        let affected_rows = common_runtime::spawn_global(async move {
1784            let _permit = permit;
1785            dispatcher
1786                .execute_with_progress(writes, None, Some(&cancellation), progress)
1787                .await
1788        })
1789        .await
1790        .context(JoinTaskSnafu)?
1791        .context(RequestInsertsSnafu)?
1792        .affected_rows;
1793        crate::metrics::DIST_INGEST_ROW_COUNT
1794            .with_label_values(&[ctx.get_db_string().as_str()])
1795            .inc_by(affected_rows as u64);
1796        Ok(Output::new(
1797            OutputData::AffectedRows(affected_rows),
1798            OutputMeta::new_with_cost(write_cost),
1799        ))
1800    }
1801
1802    async fn dispatch_normal_region_requests(
1803        &self,
1804        normal_requests: RegionInsertRequests,
1805        write_cost: usize,
1806        ctx: &QueryContextRef,
1807    ) -> Result<Output> {
1808        let request_factory = RegionRequestFactory::new(RegionRequestHeader {
1809            tracing_context: TracingContext::from_current_span().to_w3c(),
1810            dbname: ctx.get_db_string(),
1811            ..Default::default()
1812        });
1813        if ctx.confirmed_writes() {
1814            let writes = normal_requests
1815                .requests
1816                .into_iter()
1817                .map(|request| {
1818                    let rows = request.rows.as_ref().map_or(0, |rows| rows.rows.len());
1819                    crate::write_dispatcher::TrackedWrite {
1820                        request: request_factory.build_insert(RegionInsertRequests {
1821                            requests: vec![request],
1822                        }),
1823                        owners: vec![0; rows],
1824                    }
1825                })
1826                .collect();
1827            return self
1828                .execute_tracked_writes(writes, ctx, write_cost, None)
1829                .await;
1830        }
1831        let request = request_factory.build_insert(normal_requests);
1832        self.execute_untracked_writes(vec![request], ctx, write_cost, None)
1833            .await
1834    }
1835
1836    /// Returns `Some(reason)` if the config or request hint disables automatic
1837    /// table creation. Exempt private system tables are handled by
1838    /// [`Self::is_auto_create_exempt_private_table`].
1839    fn auto_create_disabled_reason(&self, ctx: &QueryContextRef) -> Result<Option<&'static str>> {
1840        let auto_create_table_hint = ctx
1841            .extension(AUTO_CREATE_TABLE_KEY)
1842            .map(|v| v.parse::<bool>())
1843            .transpose()
1844            .map_err(|_| {
1845                InvalidInsertRequestSnafu {
1846                    reason: "`auto_create_table` hint must be a boolean",
1847                }
1848                .build()
1849            })?
1850            .unwrap_or(true);
1851        Ok(if !self.auto_create_table {
1852            Some("auto-create table is disabled by frontend config")
1853        } else if !auto_create_table_hint {
1854            Some("`auto_create_table` hint is disabled")
1855        } else {
1856            None
1857        })
1858    }
1859
1860    /// Returns whether a private system table may infer and reconcile its schema
1861    /// even when automatic table creation is disabled.
1862    fn is_auto_create_exempt_private_table(schema: &str, table: &str) -> bool {
1863        schema == DEFAULT_PRIVATE_SCHEMA_NAME
1864            && matches!(
1865                table,
1866                DEFAULT_EVENTS_TABLE_NAME | SLOW_QUERY_TABLE_NAME | REGION_STATS_HISTORY_TABLE_NAME
1867            )
1868    }
1869
1870    /// Adds missing columns from a bulk stream's schema and returns the refreshed table.
1871    /// Call once when initializing the stream, before writing its first batch.
1872    /// Does not infer new nested or dictionary columns.
1873    pub async fn ensure_bulk_insert_schema(
1874        &self,
1875        table: TableRef,
1876        request_schema: &ArrowSchema,
1877        ctx: &QueryContextRef,
1878        statement_executor: &StatementExecutor,
1879    ) -> Result<TableRef> {
1880        let table_info = table.table_info();
1881        if self.auto_create_disabled_reason(ctx)?.is_some()
1882            && !Self::is_auto_create_exempt_private_table(&table_info.schema_name, &table_info.name)
1883        {
1884            return Ok(table);
1885        }
1886
1887        let table_schema = table.schema();
1888        let schema = request_schema
1889            .fields()
1890            .iter()
1891            .filter(|field| table_schema.column_schema_by_name(field.name()).is_none())
1892            .map(|field| {
1893                let data_type = field.data_type();
1894                // Dictionary values can reach the same infallible child-type conversion
1895                // as nested types, even when Arrow's is_nested() returns false.
1896                ensure!(
1897                    !data_type.is_nested() && !matches!(data_type, ArrowDataType::Dictionary(..)),
1898                    crate::error::NotSupportedSnafu {
1899                        feat: format!(
1900                            "automatically adding bulk insert column '{}' with type {:?}",
1901                            field.name(),
1902                            data_type
1903                        ),
1904                    }
1905                );
1906                let column = datatypes::schema::ColumnSchema::try_from(field.as_ref())
1907                    .context(crate::error::ConvertSchemaSnafu)?;
1908                // Arrow fields do not carry primary-key semantics. New columns are
1909                // fields, unless explicitly marked as a time index.
1910                let column_def =
1911                    try_as_column_def(&column, false).context(crate::error::ColumnDataTypeSnafu)?;
1912                Ok(ColumnSchema {
1913                    column_name: column_def.name,
1914                    datatype: column_def.data_type,
1915                    semantic_type: column_def.semantic_type,
1916                    datatype_extension: column_def.datatype_extension,
1917                    options: column_def.options,
1918                })
1919            })
1920            .collect::<Result<Vec<_>>>()?;
1921        let mut request = RowInsertRequest {
1922            table_name: table_info.name.clone(),
1923            rows: Some(Rows {
1924                schema,
1925                rows: Vec::new(),
1926            }),
1927        };
1928        let Some(alter_expr) =
1929            self.get_alter_table_expr_on_demand(&mut request, &table, ctx, false, false, true)?
1930        else {
1931            return Ok(table);
1932        };
1933
1934        statement_executor
1935            .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
1936            .await?;
1937        self.get_table(
1938            &table_info.catalog_name,
1939            &table_info.schema_name,
1940            &table_info.name,
1941        )
1942        .await?
1943        .with_context(|| TableNotFoundSnafu {
1944            table_name: table_info.full_table_name(),
1945        })
1946    }
1947
1948    /// Ensures a trace table has the request-global schema without requiring a
1949    /// padded data row to drive on-demand creation or alteration. When
1950    /// `alter_existing` is false, a table created after planning is left for the
1951    /// caller to re-plan.
1952    pub async fn ensure_trace_table_on_demand(
1953        &self,
1954        table_name: &str,
1955        request_schema: Vec<ColumnSchema>,
1956        alter_existing: bool,
1957        ctx: &QueryContextRef,
1958        statement_executor: &StatementExecutor,
1959    ) -> Result<()> {
1960        let mut requests = RowInsertRequests {
1961            inserts: vec![RowInsertRequest {
1962                table_name: table_name.to_string(),
1963                rows: Some(api::v1::Rows {
1964                    schema: request_schema,
1965                    rows: Vec::new(),
1966                }),
1967            }],
1968        };
1969        self.create_or_alter_tables_on_demand(
1970            &mut requests,
1971            ctx,
1972            AutoCreateTableType::Trace { alter_existing },
1973            statement_executor,
1974            false,
1975            false,
1976            None,
1977        )
1978        .await?;
1979        Ok(())
1980    }
1981
1982    /// Creates or alter tables on demand:
1983    /// - if table does not exist, create table by inferred CreateExpr
1984    /// - if table exist, check if schema matches. If any new column found, alter table by inferred `AlterExpr`
1985    ///
1986    /// Returns a mapping from table name to table id, where table name is the table name involved in the requests.
1987    /// This mapping is used in the conversion of RowToRegion.
1988    ///
1989    /// `accommodate_existing_schema` is used to determine if the existing schema should override the new schema.
1990    /// It only works for TIME_INDEX and single VALUE columns. This is for the case where the user creates a table with
1991    /// custom schema, and then inserts data with endpoints that have default schema setting, like prometheus
1992    /// remote write. This will modify the `RowInsertRequests` in place.
1993    /// `is_single_value` indicates whether the default schema only contains single value column so we can accommodate it.
1994    ///
1995    /// `align_time_index_unit` supplies the selected physical table's time-index
1996    /// unit for new logical tables. Existing logical targets always use their
1997    /// own unit, even when this argument is `None` because no new target needs
1998    /// the selected backing table.
1999    #[allow(clippy::too_many_arguments)]
2000    async fn create_or_alter_tables_on_demand(
2001        &self,
2002        requests: &mut RowInsertRequests,
2003        ctx: &QueryContextRef,
2004        auto_create_table_type: AutoCreateTableType,
2005        statement_executor: &StatementExecutor,
2006        accommodate_existing_schema: bool,
2007        is_single_value: bool,
2008        align_time_index_unit: Option<TimeUnit>,
2009    ) -> Result<CreateAlterTableResult> {
2010        let is_exemplar = matches!(&auto_create_table_type, AutoCreateTableType::Exemplar);
2011        let _timer = crate::metrics::CREATE_ALTER_ON_DEMAND
2012            .with_label_values(&[auto_create_table_type.as_str()])
2013            .start_timer();
2014        let catalog = ctx.current_catalog();
2015        let schema = ctx.current_schema();
2016
2017        let auto_create_disabled_reason = self.auto_create_disabled_reason(ctx)?;
2018        // Enabled batches permit every table, so only disabled batches need a whitelist scan.
2019        let has_auto_create_exempt_table = auto_create_disabled_reason.is_some()
2020            && requests
2021                .inserts
2022                .iter()
2023                .any(|req| Self::is_auto_create_exempt_private_table(&schema, &req.table_name));
2024        let mut table_infos = HashMap::new();
2025        // Without exempt tables, verify existing tables and reject missing ones without inferring schemas.
2026        if let Some(disabled_reason) = auto_create_disabled_reason
2027            && !has_auto_create_exempt_table
2028        {
2029            let mut instant_table_ids = HashSet::new();
2030            for req in &mut requests.inserts {
2031                let table = match self.get_table(catalog, &schema, &req.table_name).await? {
2032                    Some(table) => table,
2033                    // System-defined table: created canonically by the system,
2034                    // so the auto-create config/hint does not apply.
2035                    None if is_ddl_reserved_table(&schema, &req.table_name) => {
2036                        statement_executor
2037                            .create_declared_relationships_table(catalog, ctx.clone())
2038                            .await?
2039                    }
2040                    None => {
2041                        return InvalidInsertRequestSnafu {
2042                            reason: format!(
2043                                "Table `{}` does not exist, and {}",
2044                                req.table_name, disabled_reason
2045                            ),
2046                        }
2047                        .fail();
2048                    }
2049                };
2050                // Existing metric and exemplar destinations keep their time index unit.
2051                if matches!(
2052                    auto_create_table_type,
2053                    AutoCreateTableType::Logical(_) | AutoCreateTableType::Exemplar
2054                ) && let Some(rows) = req.rows.as_mut()
2055                    && let Some(target_unit) = table_time_index_unit(&table)
2056                {
2057                    convert_rows_time_unit(rows, target_unit)?;
2058                }
2059                let table_info = table.table_info();
2060                if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) {
2061                    validate_exemplar_table(&table_info)?;
2062                }
2063                if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) {
2064                    validate_trace_table_model(&table_info, ctx)?;
2065                }
2066                if table_info.is_ttl_instant_table() {
2067                    instant_table_ids.insert(table_info.table_id());
2068                }
2069                table_infos.insert(table_info.table_id(), table.table_info());
2070            }
2071            let ret = CreateAlterTableResult {
2072                instant_table_ids,
2073                table_infos,
2074            };
2075            return Ok(ret);
2076        }
2077
2078        let mut create_tables = vec![];
2079        let mut alter_tables = vec![];
2080        let mut need_refresh_table_infos = HashSet::new();
2081        let mut instant_table_ids = HashSet::new();
2082        let mut per_table_semantics: Option<Option<PerTableSemanticIndex>> = None;
2083
2084        for req in &mut requests.inserts {
2085            // Mixed batches need a per-table decision so an exempt table cannot authorize others.
2086            let auto_create_allowed = auto_create_disabled_reason.is_none()
2087                || Self::is_auto_create_exempt_private_table(&schema, &req.table_name);
2088            match self.get_table(catalog, &schema, &req.table_name).await? {
2089                Some(table) => {
2090                    let table_info = table.table_info();
2091                    if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) {
2092                        validate_exemplar_table(&table_info)?;
2093                    }
2094                    if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) {
2095                        validate_trace_table_model(&table_info, ctx)?;
2096                    }
2097                    if table_info.is_ttl_instant_table() {
2098                        instant_table_ids.insert(table_info.table_id());
2099                    }
2100                    // Metric path: an existing destination table keeps its
2101                    // own time index unit (it may be bound to another
2102                    // physical table than the one selected by this request).
2103                    if matches!(auto_create_table_type, AutoCreateTableType::Logical(_))
2104                        && let Some(rows) = req.rows.as_mut()
2105                        && let Some(target_unit) = table_time_index_unit(&table)
2106                    {
2107                        convert_rows_time_unit(rows, target_unit)?;
2108                    }
2109                    if auto_create_allowed
2110                        && let Some(alter_expr) = self.get_alter_table_expr_on_demand(
2111                            req,
2112                            &table,
2113                            ctx,
2114                            accommodate_existing_schema,
2115                            is_single_value,
2116                            auto_create_table_type.alter_existing(),
2117                        )?
2118                    {
2119                        alter_tables.push(alter_expr);
2120                        need_refresh_table_infos.insert((
2121                            catalog.to_string(),
2122                            schema.clone(),
2123                            req.table_name.clone(),
2124                        ));
2125                    } else {
2126                        table_infos.insert(table_info.table_id(), table.table_info());
2127                    }
2128                }
2129                // A DDL-reserved table's definition never derives from the
2130                // write request; the system creates it canonically, below the
2131                // user-DDL guard that rejects the generic create path.
2132                None if is_ddl_reserved_table(&schema, &req.table_name) => {
2133                    let table = statement_executor
2134                        .create_declared_relationships_table(catalog, ctx.clone())
2135                        .await?;
2136                    let table_info = table.table_info();
2137                    if table_info.is_ttl_instant_table() {
2138                        instant_table_ids.insert(table_info.table_id());
2139                    }
2140                    table_infos.insert(table_info.table_id(), table_info);
2141                }
2142                None if !auto_create_allowed
2143                    && let Some(disabled_reason) = auto_create_disabled_reason =>
2144                {
2145                    return InvalidInsertRequestSnafu {
2146                        reason: format!(
2147                            "Table `{}` does not exist, and {}",
2148                            req.table_name, disabled_reason,
2149                        ),
2150                    }
2151                    .fail();
2152                }
2153                None => {
2154                    // Metric path: a new table uses the selected physical
2155                    // table's unit; convert before the create expression is
2156                    // derived from the request schema.
2157                    if let Some(physical_unit) = align_time_index_unit
2158                        && let Some(rows) = req.rows.as_mut()
2159                    {
2160                        convert_rows_time_unit(rows, physical_unit)?;
2161                    }
2162                    let semantic_index = per_table_semantics
2163                        .get_or_insert_with(|| parse_per_table_semantic_index(ctx))
2164                        .as_ref();
2165                    let create_expr = self.get_create_table_expr_on_demand(
2166                        req,
2167                        &auto_create_table_type,
2168                        ctx,
2169                        semantic_index,
2170                    )?;
2171                    create_tables.push(create_expr);
2172                }
2173            }
2174        }
2175
2176        match auto_create_table_type {
2177            AutoCreateTableType::Logical(_) => {
2178                if !create_tables.is_empty() {
2179                    // Creates logical tables in batch.
2180                    let tables = self
2181                        .create_logical_tables(create_tables, ctx, statement_executor)
2182                        .await?;
2183
2184                    for table in tables {
2185                        let table_info = table.table_info();
2186                        if table_info.is_ttl_instant_table() {
2187                            instant_table_ids.insert(table_info.table_id());
2188                        }
2189                        table_infos.insert(table_info.table_id(), table.table_info());
2190                    }
2191                }
2192                if !alter_tables.is_empty() {
2193                    // Alter logical tables in batch.
2194                    statement_executor
2195                        .alter_logical_tables(alter_tables, ctx.clone(), TriggerReason::AutoAlter)
2196                        .await?;
2197                }
2198            }
2199            AutoCreateTableType::Physical
2200            | AutoCreateTableType::Exemplar
2201            | AutoCreateTableType::Log
2202            | AutoCreateTableType::LastNonNull => {
2203                // note that auto create table shouldn't be ttl instant table
2204                // for it's a very unexpected behavior and should be set by user explicitly
2205                for create_table in create_tables {
2206                    let table = self
2207                        .create_physical_table(create_table, None, ctx, statement_executor)
2208                        .await?;
2209                    // A concurrent CREATE can return our proposed schema with the winner's ID.
2210                    let table = if is_exemplar {
2211                        let name = table.table_info().name.clone();
2212                        self.get_table(catalog, &schema, &name)
2213                            .await?
2214                            .context(TableNotFoundSnafu { table_name: name })?
2215                    } else {
2216                        table
2217                    };
2218                    if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) {
2219                        validate_exemplar_table(&table.table_info())?;
2220                        if let Some(req) = requests
2221                            .inserts
2222                            .iter_mut()
2223                            .find(|r| r.table_name == table.table_info().name)
2224                            && let Some(alter) = self.get_alter_table_expr_on_demand(
2225                                req, &table, ctx, false, false, true,
2226                            )?
2227                        {
2228                            alter_tables.push(alter);
2229                            need_refresh_table_infos.insert((
2230                                catalog.to_string(),
2231                                schema.clone(),
2232                                req.table_name.clone(),
2233                            ));
2234                        }
2235                    }
2236                    let table_info = table.table_info();
2237                    if table_info.is_ttl_instant_table() {
2238                        instant_table_ids.insert(table_info.table_id());
2239                    }
2240                    table_infos.insert(table_info.table_id(), table.table_info());
2241                }
2242                for alter_expr in alter_tables.into_iter() {
2243                    statement_executor
2244                        .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
2245                        .await?;
2246                }
2247            }
2248
2249            AutoCreateTableType::Trace { .. } => {
2250                let trace_table_name = ctx
2251                    .extension(TRACE_TABLE_NAME_SESSION_KEY)
2252                    .unwrap_or(TRACE_TABLE_NAME);
2253
2254                let trace_table_partitions = if let Some(trace_table_partitions) =
2255                    ctx.extension(TRACE_TABLE_PARTITIONS_HINT_KEY)
2256                {
2257                    let p = trace_table_partitions.parse::<u32>().map_err(|_| {
2258                        InvalidInsertRequestSnafu {
2259                            reason: format!(
2260                                "Failed to parse trace_table_partitions: {}",
2261                                trace_table_partitions
2262                            ),
2263                        }
2264                        .build()
2265                    })?;
2266                    Some(p)
2267                } else {
2268                    None
2269                };
2270
2271                // note that auto create table shouldn't be ttl instant table
2272                // for it's a very unexpected behavior and should be set by user explicitly
2273                for mut create_table in create_tables {
2274                    if create_table.table_name == trace_services_table_name(trace_table_name)
2275                        || create_table.table_name == trace_operations_table_name(trace_table_name)
2276                    {
2277                        // Disable append mode for auxiliary tables (services/operations) since they require upsert behavior.
2278                        create_table
2279                            .table_options
2280                            .insert(APPEND_MODE_KEY.to_string(), "false".to_string());
2281                        // Remove `ttl` key from table options if it exists
2282                        create_table.table_options.remove(TTL_KEY);
2283
2284                        let table = self
2285                            .create_physical_table(create_table, None, ctx, statement_executor)
2286                            .await?;
2287                        let table_info = table.table_info();
2288                        if table_info.is_ttl_instant_table() {
2289                            instant_table_ids.insert(table_info.table_id());
2290                        }
2291                        table_infos.insert(table_info.table_id(), table.table_info());
2292                    } else {
2293                        // prebuilt partition rules for uuid data: see the function
2294                        // for more information
2295                        let partitions = if matches!(trace_table_partitions, Some(0) | Some(1)) {
2296                            // disable partitions
2297                            None
2298                        } else {
2299                            let p = partition_rule_for_hexstring(
2300                                TRACE_ID_COLUMN,
2301                                trace_table_partitions,
2302                            )
2303                            .context(CreatePartitionRulesSnafu)?;
2304                            Some(p)
2305                        };
2306
2307                        // add skip index to
2308                        // - trace_id: when searching by trace id
2309                        // - parent_span_id: when searching root span
2310                        // - span_name: when searching certain types of span
2311                        let index_columns =
2312                            [TRACE_ID_COLUMN, PARENT_SPAN_ID_COLUMN, SERVICE_NAME_COLUMN];
2313                        for index_column in index_columns {
2314                            if let Some(col) = create_table
2315                                .column_defs
2316                                .iter_mut()
2317                                .find(|c| c.name == index_column)
2318                            {
2319                                col.options =
2320                                    options_from_skipping(&SkippingIndexOptions::default())
2321                                        .context(ColumnOptionsSnafu)?;
2322                            } else {
2323                                warn!(
2324                                    "Column {} not found when creating index for trace table: {}.",
2325                                    index_column, create_table.table_name
2326                                );
2327                            }
2328                        }
2329
2330                        // Span ids and end timestamps rarely repeat within an SST, so a
2331                        // dictionary costs more than it saves. Small span id pages let
2332                        // lookups by trace id decode only the pages holding matched rows.
2333                        let id_compression = CompressionOptions {
2334                            encoding: Some(ColumnEncoding::Plain),
2335                            page_size: Some(ReadableSize::kb(64)),
2336                            ..Default::default()
2337                        };
2338                        let compressed_columns = [
2339                            (SPAN_ID_COLUMN, id_compression),
2340                            (PARENT_SPAN_ID_COLUMN, id_compression),
2341                            (
2342                                TIMESTAMP_END_COLUMN,
2343                                CompressionOptions {
2344                                    encoding: Some(ColumnEncoding::DeltaBinaryPacked),
2345                                    ..Default::default()
2346                                },
2347                            ),
2348                        ];
2349                        for (name, compression) in compressed_columns {
2350                            if let Some(col) =
2351                                create_table.column_defs.iter_mut().find(|c| c.name == name)
2352                            {
2353                                let compression = options_from_compression(&compression)
2354                                    .context(ColumnOptionsSnafu)?;
2355                                col.options
2356                                    .get_or_insert_with(Default::default)
2357                                    .options
2358                                    .extend(compression.options);
2359                            }
2360                        }
2361
2362                        // use table_options to mark table model version
2363                        create_table.table_options.insert(
2364                            TABLE_DATA_MODEL.to_string(),
2365                            ctx.extension(SEMANTIC_PIPELINE)
2366                                .unwrap_or(TABLE_DATA_MODEL_TRACE_V1)
2367                                .to_string(),
2368                        );
2369
2370                        let table = self
2371                            .create_physical_table(
2372                                create_table,
2373                                partitions,
2374                                ctx,
2375                                statement_executor,
2376                            )
2377                            .await?;
2378                        let table_info = table.table_info();
2379                        if table_info.is_ttl_instant_table() {
2380                            instant_table_ids.insert(table_info.table_id());
2381                        }
2382                        table_infos.insert(table_info.table_id(), table.table_info());
2383                    }
2384                }
2385                for alter_expr in alter_tables.into_iter() {
2386                    statement_executor
2387                        .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
2388                        .await?;
2389                }
2390            }
2391        }
2392
2393        // refresh table infos for altered tables
2394        for (catalog, schema, table_name) in need_refresh_table_infos {
2395            let table = self
2396                .get_table(&catalog, &schema, &table_name)
2397                .await?
2398                .context(TableNotFoundSnafu {
2399                    table_name: common_catalog::format_full_table_name(
2400                        &catalog,
2401                        &schema,
2402                        &table_name,
2403                    ),
2404                })?;
2405            let table_info = table.table_info();
2406            if is_exemplar {
2407                validate_exemplar_table(&table_info)?;
2408            }
2409            table_infos.insert(table_info.table_id(), table.table_info());
2410        }
2411
2412        if is_exemplar {
2413            for info in table_infos.values() {
2414                if let Some(unit) = info
2415                    .meta
2416                    .schema
2417                    .timestamp_column()
2418                    .and_then(|column| column.data_type.as_timestamp())
2419                    .map(|timestamp| timestamp.unit())
2420                {
2421                    for request in &mut requests.inserts {
2422                        if request.table_name == info.name
2423                            && let Some(rows) = request.rows.as_mut()
2424                        {
2425                            convert_rows_time_unit(rows, unit)?;
2426                        }
2427                    }
2428                }
2429            }
2430        }
2431
2432        Ok(CreateAlterTableResult {
2433            instant_table_ids,
2434            table_infos,
2435        })
2436    }
2437
2438    async fn create_physical_table_on_demand(
2439        &self,
2440        ctx: &QueryContextRef,
2441        physical_table: String,
2442        statement_executor: &StatementExecutor,
2443    ) -> Result<TableRef> {
2444        let catalog_name = ctx.current_catalog();
2445        let schema_name = ctx.current_schema();
2446
2447        // check if exist
2448        if let Some(table) = self
2449            .get_table(catalog_name, &schema_name, &physical_table)
2450            .await?
2451        {
2452            return Ok(table);
2453        }
2454
2455        // Gate here too, otherwise a disabled switch would still leak the physical table.
2456        if let Some(disabled_reason) = self.auto_create_disabled_reason(ctx)? {
2457            return InvalidInsertRequestSnafu {
2458                reason: format!(
2459                    "Physical table `{physical_table}` does not exist, and {disabled_reason}"
2460                ),
2461            }
2462            .fail();
2463        }
2464
2465        let table_reference = TableReference::full(catalog_name, &schema_name, &physical_table);
2466        debug!("Ensuring physical metric table `{table_reference}` exists for insert");
2467
2468        // schema with timestamp and field column
2469        let default_schema = vec![
2470            ColumnSchema {
2471                column_name: greptime_timestamp().to_string(),
2472                datatype: api::helper::timestamp_datatype(
2473                    self.auto_create_physical_table_timestamp_unit,
2474                ) as _,
2475                semantic_type: SemanticType::Timestamp as _,
2476                datatype_extension: None,
2477                options: None,
2478            },
2479            ColumnSchema {
2480                column_name: greptime_value().to_string(),
2481                datatype: ColumnDataType::Float64 as _,
2482                semantic_type: SemanticType::Field as _,
2483                datatype_extension: None,
2484                options: None,
2485            },
2486        ];
2487        let create_table_expr =
2488            &mut build_create_table_expr(&table_reference, &default_schema, default_engine())?;
2489
2490        create_table_expr.engine = METRIC_ENGINE_NAME.to_string();
2491        create_table_expr
2492            .table_options
2493            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), "true".to_string());
2494        apply_retention_ttl_hint(&mut create_table_expr.table_options, ctx);
2495
2496        // create physical table
2497        let res = statement_executor
2498            .create_table_inner(
2499                create_table_expr,
2500                None,
2501                ctx.clone(),
2502                TriggerReason::AutoCreate,
2503            )
2504            .await;
2505
2506        match res {
2507            Ok(table) => Ok(table),
2508            Err(err) => {
2509                error!(err; "Failed to create table {table_reference}");
2510                Err(err)
2511            }
2512        }
2513    }
2514
2515    async fn get_table(
2516        &self,
2517        catalog: &str,
2518        schema: &str,
2519        table: &str,
2520    ) -> Result<Option<TableRef>> {
2521        self.catalog_manager
2522            .table(catalog, schema, table, None)
2523            .await
2524            .context(CatalogSnafu)
2525    }
2526
2527    fn get_create_table_expr_on_demand(
2528        &self,
2529        req: &RowInsertRequest,
2530        create_type: &AutoCreateTableType,
2531        ctx: &QueryContextRef,
2532        semantic_index: Option<&PerTableSemanticIndex>,
2533    ) -> Result<CreateTableExpr> {
2534        let schema = ctx.current_schema();
2535        let mut table_options = std::collections::HashMap::with_capacity(4);
2536        fill_table_options_for_create(&mut table_options, create_type, ctx);
2537        if !matches!(create_type, AutoCreateTableType::Exemplar) {
2538            apply_per_table_semantic_options(
2539                &mut table_options,
2540                semantic_index,
2541                ctx.current_schema().as_str(),
2542                &req.table_name,
2543            );
2544        }
2545
2546        let engine_name = if let AutoCreateTableType::Logical(_) = create_type {
2547            // engine should be metric engine when creating logical tables.
2548            METRIC_ENGINE_NAME
2549        } else {
2550            default_engine()
2551        };
2552
2553        let table_ref = TableReference::full(ctx.current_catalog(), &schema, &req.table_name);
2554        // SAFETY: `req.rows` is guaranteed to be `Some` by `handle_row_inserts_with_create_type()`.
2555        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
2556        let mut create_table_expr =
2557            build_create_table_expr(&table_ref, request_schema, engine_name)?;
2558
2559        if matches!(create_type, AutoCreateTableType::Exemplar) {
2560            // Preserve the stored schema order without shifting every incoming row.
2561            create_table_expr
2562                .column_defs
2563                .sort_by_key(|column| column.name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
2564            create_table_expr
2565                .primary_keys
2566                .sort_by_key(|name| name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
2567            for column in &mut create_table_expr.column_defs {
2568                if [
2569                    DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
2570                    DATA_SCHEMA_TSID_COLUMN_NAME,
2571                ]
2572                .contains(&column.name.as_str())
2573                {
2574                    column.is_nullable = false;
2575                }
2576            }
2577        }
2578
2579        // extension set by the Splunk HEC handler for identity path
2580        if ctx.extension(SPLUNK_PK_METADATA_ORDER_KEY).is_some() {
2581            reorder_splunk_primary_keys(&mut create_table_expr.primary_keys);
2582        }
2583
2584        debug!("Ensuring table `{table_ref}` exists for insert");
2585        create_table_expr.table_options.extend(table_options);
2586        Ok(create_table_expr)
2587    }
2588
2589    /// Returns an alter table expression if it finds new columns in the request.
2590    /// When `accommodate_existing_schema` is false, it always adds columns if not exist.
2591    /// When `accommodate_existing_schema` is true, it may modify the input `req` to
2592    /// accommodate it with existing schema. See [`create_or_alter_tables_on_demand`](Self::create_or_alter_tables_on_demand)
2593    /// for more details.
2594    /// When `is_single_value` is true, it also rejects native-histogram/float kind
2595    /// changes even when no columns need adding.
2596    /// When both options are true, it considers fields when modifying the input `req`.
2597    fn get_alter_table_expr_on_demand(
2598        &self,
2599        req: &mut RowInsertRequest,
2600        table: &TableRef,
2601        ctx: &QueryContextRef,
2602        accommodate_existing_schema: bool,
2603        is_single_value: bool,
2604        alter_existing: bool,
2605    ) -> Result<Option<AlterTableExpr>> {
2606        if !alter_existing {
2607            return Ok(None);
2608        }
2609
2610        let catalog_name = ctx.current_catalog();
2611        let schema_name = ctx.current_schema();
2612        let table_name = table.table_info().name.clone();
2613
2614        // Never auto-alter a system-defined table to fit a write; a request
2615        // with unknown columns fails instead.
2616        if is_ddl_reserved_table(&schema_name, &table_name) {
2617            return Ok(None);
2618        }
2619
2620        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
2621        let request_field_count = request_schema
2622            .iter()
2623            .filter(|col| col.semantic_type == SemanticType::Field as i32)
2624            .count();
2625        if is_single_value {
2626            let request_is_native_histogram = request_is_native_histogram(request_schema);
2627            let table_is_native_histogram = table_is_native_histogram(table);
2628            ensure!(
2629                request_is_native_histogram == table_is_native_histogram,
2630                InvalidInsertRequestSnafu {
2631                    reason: format!(
2632                        "Table `{table_name}` cannot mix native histogram and float sample fields"
2633                    ),
2634                }
2635            );
2636        }
2637
2638        let column_exprs = ColumnExpr::from_column_schemas(request_schema);
2639        let add_columns = expr_helper::extract_add_columns_expr(&table.schema(), column_exprs)?;
2640        let Some(mut add_columns) = add_columns else {
2641            return Ok(None);
2642        };
2643
2644        // If accommodate_existing_schema is true, update request schema for Timestamp/Field columns
2645        if accommodate_existing_schema {
2646            let table_schema = table.schema();
2647            // Find timestamp column name
2648            let ts_col_name = table_schema.timestamp_column().map(|c| c.name.clone());
2649            // Find field column name if there is only one and `is_single_value` is true.
2650            let mut field_col_name = None;
2651            if is_single_value && request_field_count <= 1 {
2652                let mut multiple_field_cols = false;
2653                table.field_columns().for_each(|col| {
2654                    if field_col_name.is_none() {
2655                        field_col_name = Some(col.name.clone());
2656                    } else {
2657                        multiple_field_cols = true;
2658                    }
2659                });
2660                if multiple_field_cols {
2661                    field_col_name = None;
2662                }
2663            }
2664
2665            // Update column name in request schema for Timestamp/Field columns
2666            if let Some(rows) = req.rows.as_mut() {
2667                for col in &mut rows.schema {
2668                    match col.semantic_type {
2669                        x if x == SemanticType::Timestamp as i32 => {
2670                            if let Some(ref ts_name) = ts_col_name
2671                                && col.column_name != *ts_name
2672                            {
2673                                col.column_name = ts_name.clone();
2674                            }
2675                        }
2676                        x if x == SemanticType::Field as i32 => {
2677                            if let Some(ref field_name) = field_col_name
2678                                && col.column_name != *field_name
2679                            {
2680                                col.column_name = field_name.clone();
2681                            }
2682                        }
2683                        _ => {}
2684                    }
2685                }
2686            }
2687
2688            // Only keep columns that are tags or non-single field.
2689            add_columns.add_columns.retain(|col| {
2690                let def = col.column_def.as_ref().unwrap();
2691                def.semantic_type == SemanticType::Tag as i32
2692                    || (def.semantic_type == SemanticType::Field as i32 && field_col_name.is_none())
2693            });
2694
2695            if add_columns.add_columns.is_empty() {
2696                return Ok(None);
2697            }
2698        }
2699
2700        Ok(Some(AlterTableExpr {
2701            catalog_name: catalog_name.to_string(),
2702            schema_name: schema_name.clone(),
2703            table_name: table_name.clone(),
2704            kind: Some(Kind::AddColumns(add_columns)),
2705        }))
2706    }
2707
2708    /// Creates a table with options.
2709    async fn create_physical_table(
2710        &self,
2711        mut create_table_expr: CreateTableExpr,
2712        partitions: Option<Partitions>,
2713        ctx: &QueryContextRef,
2714        statement_executor: &StatementExecutor,
2715    ) -> Result<TableRef> {
2716        let res = statement_executor
2717            .create_table_inner(
2718                &mut create_table_expr,
2719                partitions,
2720                ctx.clone(),
2721                TriggerReason::AutoCreate,
2722            )
2723            .await;
2724
2725        let table_ref = TableReference::full(
2726            &create_table_expr.catalog_name,
2727            &create_table_expr.schema_name,
2728            &create_table_expr.table_name,
2729        );
2730
2731        match res {
2732            Ok(table) => {
2733                validate_trace_table_model(&table.table_info(), ctx)?;
2734                Ok(table)
2735            }
2736            Err(err) => {
2737                error!(err; "Failed to create table {}", table_ref);
2738                Err(err)
2739            }
2740        }
2741    }
2742
2743    async fn create_logical_tables(
2744        &self,
2745        create_table_exprs: Vec<CreateTableExpr>,
2746        ctx: &QueryContextRef,
2747        statement_executor: &StatementExecutor,
2748    ) -> Result<Vec<TableRef>> {
2749        let res = statement_executor
2750            .create_logical_tables(&create_table_exprs, ctx.clone(), TriggerReason::AutoCreate)
2751            .await;
2752
2753        match res {
2754            Ok(res) => Ok(res),
2755            Err(err) => {
2756                let failed_tables = create_table_exprs
2757                    .into_iter()
2758                    .map(|expr| {
2759                        format!(
2760                            "{}.{}.{}",
2761                            expr.catalog_name, expr.schema_name, expr.table_name
2762                        )
2763                    })
2764                    .collect::<Vec<_>>();
2765                error!(
2766                    err;
2767                    "Failed to create logical tables {:?}",
2768                    failed_tables
2769                );
2770                Err(err)
2771            }
2772        }
2773    }
2774
2775    /// Returns the dispatcher shared with batching execution paths.
2776    pub fn write_dispatcher(&self) -> &WriteDispatcherRef {
2777        &self.write_dispatcher
2778    }
2779
2780    pub fn node_manager(&self) -> &NodeManagerRef {
2781        &self.node_manager
2782    }
2783
2784    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
2785        &self.partition_manager
2786    }
2787
2788    pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
2789        &self.table_flownode_set_cache
2790    }
2791}
2792
2793fn request_is_native_histogram(request_schema: &[ColumnSchema]) -> bool {
2794    let mut fields = request_schema
2795        .iter()
2796        .filter(|col| col.semantic_type == SemanticType::Field as i32);
2797    let Some(col) = fields.next() else {
2798        return false;
2799    };
2800
2801    fields.next().is_none()
2802        && api::helper::is_column_type_value_eq(
2803            col.datatype,
2804            col.datatype_extension.clone(),
2805            native_histogram_value_type(),
2806        )
2807}
2808
2809/// Returns the table's time index unit, if any. A metric table without a
2810/// timestamp column is left alone by the unit alignment: the metric engine
2811/// rejects it anyway.
2812fn table_time_index_unit(table: &TableRef) -> Option<TimeUnit> {
2813    table
2814        .table_info()
2815        .meta
2816        .schema
2817        .timestamp_column()
2818        .and_then(|col| col.data_type.as_timestamp().map(|ts| ts.unit()))
2819}
2820
2821fn convert_rows_time_unit(rows: &mut Rows, target_unit: TimeUnit) -> Result<()> {
2822    let Some(ts_index) = rows
2823        .schema
2824        .iter()
2825        .position(|col| col.semantic_type == SemanticType::Timestamp as i32)
2826    else {
2827        return Ok(());
2828    };
2829    let Some(source_unit) = ColumnDataType::try_from(rows.schema[ts_index].datatype)
2830        .ok()
2831        .and_then(api::helper::timestamp_unit)
2832    else {
2833        return Ok(());
2834    };
2835    if source_unit == target_unit {
2836        return Ok(());
2837    }
2838
2839    rows.schema[ts_index].datatype = api::helper::timestamp_datatype(target_unit) as i32;
2840    // Timestamp columns never carry a datatype extension.
2841    rows.schema[ts_index].datatype_extension = None;
2842
2843    // Note: the schema is rewritten before the rows are converted, so an
2844    // overflow error mid-batch leaves this request half-converted. That is
2845    // harmless: the error aborts the whole insert request.
2846    //
2847    // `validate_column_count_match` guarantees every row carries exactly one
2848    // value per schema column, so the time index position is directly in
2849    // bounds; no per-value search is needed.
2850    for row in &mut rows.rows {
2851        debug_assert_eq!(row.values.len(), rows.schema.len());
2852        let value = &mut row.values[ts_index];
2853        let Some(value_data) = value.value_data.take() else {
2854            continue;
2855        };
2856        value.value_data =
2857            convert_timestamp_value_data(value_data, source_unit, target_unit, ts_index)?;
2858    }
2859    Ok(())
2860}
2861
2862fn convert_timestamp_value_data(
2863    value_data: ValueData,
2864    source_unit: TimeUnit,
2865    target_unit: TimeUnit,
2866    column_index: usize,
2867) -> Result<Option<ValueData>> {
2868    let timestamp = match value_data {
2869        ValueData::TimestampSecondValue(v) => Timestamp::new_second(v),
2870        ValueData::TimestampMillisecondValue(v) => Timestamp::new_millisecond(v),
2871        ValueData::TimestampMicrosecondValue(v) => Timestamp::new_microsecond(v),
2872        ValueData::TimestampNanosecondValue(v) => Timestamp::new_nanosecond(v),
2873        // Null or non-timestamp value; nothing to convert.
2874        other => return Ok(Some(other)),
2875    };
2876    let converted = timestamp
2877        .convert_to(target_unit)
2878        .with_context(|| InvalidInsertRequestSnafu {
2879            reason: format!(
2880                "timestamp column {column_index} value {} in unit {source_unit:?} overflows when converting to unit {target_unit:?}",
2881                timestamp.value()
2882            ),
2883        })?;
2884    Ok(api::helper::to_grpc_value(datatypes::value::Value::Timestamp(converted)).value_data)
2885}
2886
2887fn table_is_native_histogram(table: &TableRef) -> bool {
2888    let mut fields = table.field_columns();
2889    let Some(col) = fields.next() else {
2890        return false;
2891    };
2892
2893    fields.next().is_none() && is_native_histogram_value_type(&col.data_type)
2894}
2895
2896fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> {
2897    for request in &requests.inserts {
2898        let rows = request.rows.as_ref().unwrap();
2899        let column_count = rows.schema.len();
2900        rows.rows.iter().try_for_each(|r| {
2901            ensure!(
2902                r.values.len() == column_count,
2903                InvalidInsertRequestSnafu {
2904                    reason: format!(
2905                        "column count mismatch, columns: {}, values: {}",
2906                        column_count,
2907                        r.values.len()
2908                    )
2909                }
2910            );
2911            Ok(())
2912        })?;
2913    }
2914    Ok(())
2915}
2916
2917fn exemplar_source_add_columns(
2918    info: &TableInfo,
2919    tags: &[ColumnSchema],
2920) -> Result<Option<api::v1::AddColumns>> {
2921    for tag in tags {
2922        if let Some(index) = info.meta.schema.column_index_by_name(&tag.column_name) {
2923            let column = &info.meta.schema.column_schemas()[index];
2924            // Existing source defaults may already be part of the normalized series identity.
2925            ensure!(
2926                info.meta.primary_key_indices.contains(&index) && column.data_type.is_string(),
2927                InvalidInsertRequestSnafu {
2928                    reason: format!(
2929                        "exemplar source {} column {} must be a string tag",
2930                        info.name, tag.column_name
2931                    ),
2932                }
2933            );
2934        }
2935    }
2936    expr_helper::extract_add_columns_expr(&info.meta.schema, ColumnExpr::from_column_schemas(tags))
2937}
2938
2939/// Validates the fixed exemplar contract before writing or scanning a shared table.
2940pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> {
2941    let meta = &table.meta;
2942    let options = &meta.options.extra_options;
2943    ensure!(
2944        meta.engine == default_engine()
2945            && options
2946                .get(APPEND_MODE_KEY)
2947                .is_some_and(|v| v.eq_ignore_ascii_case("true"))
2948            && options
2949                .get(store_api::metric_engine_consts::PRIMARY_KEY_ENCODING)
2950                .is_some_and(|v| v.eq_ignore_ascii_case("sparse")),
2951        InvalidInsertRequestSnafu {
2952            reason: format!(
2953                "{METRICS_EXEMPLARS_TABLE} requires Mito, append_mode=true and primary_key_encoding=sparse"
2954            )
2955        }
2956    );
2957    let columns = meta.schema.column_schemas();
2958    let lookup = |name: &str| {
2959        columns
2960            .iter()
2961            .enumerate()
2962            .find(|(_, c)| c.name == name)
2963            .with_context(|| InvalidInsertRequestSnafu {
2964                reason: format!("missing exemplar column {name}"),
2965            })
2966    };
2967    let (_, timestamp) = lookup(greptime_timestamp())?;
2968    for (position, name, id, data_type) in [
2969        (
2970            0,
2971            DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
2972            ReservedColumnId::table_id(),
2973            datatypes::prelude::ConcreteDataType::uint32_datatype(),
2974        ),
2975        (
2976            1,
2977            DATA_SCHEMA_TSID_COLUMN_NAME,
2978            ReservedColumnId::tsid(),
2979            datatypes::prelude::ConcreteDataType::uint64_datatype(),
2980        ),
2981    ] {
2982        let (index, column) = lookup(name)?;
2983        ensure!(
2984            meta.primary_key_indices.get(position) == Some(&index)
2985                && meta.column_ids.get(index) == Some(&id)
2986                && column.data_type == data_type
2987                && !column.is_nullable()
2988                && column.default_constraint().is_none(),
2989            InvalidInsertRequestSnafu {
2990                reason: format!("invalid exemplar source identity column {name}"),
2991            }
2992        );
2993    }
2994    ensure!(
2995        timestamp.is_time_index() && timestamp.data_type.is_timestamp(),
2996        InvalidInsertRequestSnafu {
2997            reason: "invalid exemplar time index"
2998        }
2999    );
3000    let (metric_index, metric) = lookup(EXEMPLAR_METRIC_COLUMN)?;
3001    ensure!(
3002        metric.data_type.is_string() && meta.primary_key_indices.contains(&metric_index),
3003        InvalidInsertRequestSnafu {
3004            reason: "exemplar metric name must be a string tag"
3005        }
3006    );
3007    let (value_index, value) = lookup(greptime_value())?;
3008    ensure!(
3009        value.data_type == datatypes::prelude::ConcreteDataType::float64_datatype()
3010            && !meta.primary_key_indices.contains(&value_index),
3011        InvalidInsertRequestSnafu {
3012            reason: "exemplar value must be a DOUBLE field"
3013        }
3014    );
3015    let (labels_index, labels) = lookup(greptime_exemplar_labels())?;
3016    ensure!(
3017        labels.data_type.is_json2() && !meta.primary_key_indices.contains(&labels_index),
3018        InvalidInsertRequestSnafu {
3019            reason: format!("{} must be a JSON2 field", greptime_exemplar_labels())
3020        }
3021    );
3022    if let Some(extension) = labels
3023        .extension_type::<datatypes::extension::json::Json2ExtensionType>()
3024        .map_err(|error| {
3025            InvalidInsertRequestSnafu {
3026                reason: error.to_string(),
3027            }
3028            .build()
3029        })?
3030    {
3031        ensure!(
3032            extension
3033                .metadata()
3034                .json_settings()
3035                .type_hints()
3036                .iter()
3037                .all(|hint| hint.path.len() == 1 && hint.data_type.is_string()),
3038            InvalidInsertRequestSnafu {
3039                reason: "exemplar JSON2 hints must preserve string labels"
3040            }
3041        );
3042    }
3043    for (index, column) in columns.iter().enumerate() {
3044        if [
3045            greptime_timestamp(),
3046            greptime_value(),
3047            EXEMPLAR_METRIC_COLUMN,
3048            greptime_exemplar_labels(),
3049            DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
3050            DATA_SCHEMA_TSID_COLUMN_NAME,
3051        ]
3052        .contains(&column.name.as_str())
3053        {
3054            continue;
3055        }
3056        ensure!(
3057            meta.primary_key_indices.contains(&index)
3058                && column.data_type.is_string()
3059                && column.is_nullable(),
3060            InvalidInsertRequestSnafu {
3061                reason: "inherited exemplar labels must be nullable string tags"
3062            }
3063        );
3064        // An absent inherited label must remain absent from the source series identity,
3065        // and lets sparse keys prepared before an append-only tag ALTER stay valid.
3066        ensure!(
3067            matches!(
3068                column.default_constraint(),
3069                None | Some(ColumnDefaultConstraint::Value(
3070                    datatypes::value::Value::Null
3071                ))
3072            ),
3073            InvalidInsertRequestSnafu {
3074                reason: "inherited exemplar labels must not have non-NULL defaults"
3075            }
3076        );
3077    }
3078    Ok(())
3079}
3080
3081/// Rejects writes from a different built-in trace model before schema mutation.
3082/// Unstamped, explicitly created tables remain subject to normal schema validation.
3083pub fn validate_trace_table_model(table_info: &TableInfo, ctx: &QueryContextRef) -> Result<()> {
3084    let Some(expected @ (TABLE_DATA_MODEL_TRACE_V1 | TABLE_DATA_MODEL_TRACE_V2)) =
3085        ctx.extension(SEMANTIC_PIPELINE)
3086    else {
3087        return Ok(());
3088    };
3089    if let Some(actual) = table_info.meta.options.data_model() {
3090        ensure!(
3091            actual == expected,
3092            InvalidInsertRequestSnafu {
3093                reason: format!(
3094                    "Trace table `{}` uses {actual}, but the request uses {expected}",
3095                    table_info.name,
3096                ),
3097            }
3098        );
3099    }
3100    Ok(())
3101}
3102
3103/// Copies a retention `ttl` hint onto a physical metric table being created.
3104/// Only `ttl` is copied: other ingest hints must not land on the shared physical
3105/// table, and `ttl=instant` stays on the logical table for flow forwarding.
3106/// Once the physical table exists, the hint has no effect.
3107pub fn apply_retention_ttl_hint(
3108    table_options: &mut std::collections::HashMap<String, String>,
3109    ctx: &QueryContextRef,
3110) {
3111    if let Some(ttl) = ctx.extension(TTL_KEY).filter(|ttl| is_retention_ttl(ttl)) {
3112        table_options.insert(TTL_KEY.to_string(), ttl.to_string());
3113    }
3114}
3115
3116/// Fill table options for a new table by create type.
3117pub fn fill_table_options_for_create(
3118    table_options: &mut std::collections::HashMap<String, String>,
3119    create_type: &AutoCreateTableType,
3120    ctx: &QueryContextRef,
3121) {
3122    for key in VALID_TABLE_OPTION_KEYS {
3123        if let Some(value) = ctx.extension(key) {
3124            table_options.insert(key.to_string(), value.to_string());
3125        }
3126    }
3127
3128    if !matches!(create_type, AutoCreateTableType::Logical(_)) {
3129        let mut has_twcs_option = false;
3130        for key in COMPACTION_OPTION_KEYS {
3131            if let Some(value) = ctx.extension(key) {
3132                has_twcs_option |= key.starts_with(COMPACTION_TWCS_PREFIX);
3133                table_options.insert(key.to_string(), value.to_string());
3134            }
3135        }
3136        if has_twcs_option {
3137            table_options
3138                .entry(COMPACTION_TYPE.to_string())
3139                .or_insert_with(|| COMPACTION_TYPE_TWCS.to_string());
3140        }
3141    }
3142
3143    // Semantic keys use their own vocabulary instead of the fixed option list.
3144    for (key, value) in ctx.extensions() {
3145        if is_semantic_option_key(&key) && validate_semantic_option(&key, &value) {
3146            table_options.insert(key, value);
3147        }
3148    }
3149
3150    match create_type {
3151        AutoCreateTableType::Logical(physical_table) => {
3152            table_options.insert(
3153                LOGICAL_TABLE_METADATA_KEY.to_string(),
3154                physical_table.clone(),
3155            );
3156        }
3157        AutoCreateTableType::Exemplar => {
3158            table_options.retain(|key, _| {
3159                !is_semantic_option_key(key)
3160                    && key != SEMANTIC_PER_TABLE_INDEX_KEY
3161                    && key != LOGICAL_TABLE_METADATA_KEY
3162                    && key != PHYSICAL_TABLE_METADATA_KEY
3163                    && key != MERGE_MODE_KEY
3164                    && key != "otlp_metric_compat"
3165            });
3166            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3167            table_options.insert(
3168                store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
3169                "sparse".to_string(),
3170            );
3171        }
3172        AutoCreateTableType::Physical => {
3173            if let Some(append_mode) = ctx.extension(APPEND_MODE_KEY) {
3174                table_options.insert(APPEND_MODE_KEY.to_string(), append_mode.to_string());
3175            }
3176            if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
3177                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
3178            }
3179        }
3180        // Set append_mode to true for log table.
3181        // because log tables should keep rows with the same ts and tags.
3182        AutoCreateTableType::Log => {
3183            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3184        }
3185        AutoCreateTableType::LastNonNull => {
3186            if ctx
3187                .extension(APPEND_MODE_KEY)
3188                .is_some_and(|value| value.eq_ignore_ascii_case("true"))
3189            {
3190                table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3191                table_options.insert(MERGE_MODE_KEY.to_string(), "last_row".to_string());
3192            } else if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
3193                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
3194            } else {
3195                table_options.insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
3196            }
3197        }
3198        AutoCreateTableType::Trace { .. } => {
3199            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3200        }
3201    }
3202}
3203
3204/// The parsed per-table semantic index: `{schema -> {table -> {key -> value}}}`,
3205/// produced by the OTLP metrics encode path (where one metric can fan out into
3206/// several tables with distinct keys) and the Prometheus remote write v2 path
3207/// (where per-series metadata declares type/unit, and a series may override its
3208/// target schema).
3209pub type PerTableSemanticIndex = BTreeMap<String, BTreeMap<String, BTreeMap<String, String>>>;
3210
3211/// Parses the per-table semantic index off the context extension. Call once per
3212/// create-planning round: a first write creating N tables would otherwise
3213/// re-parse the whole index N times. `None` when the request carries no index
3214/// (logs, traces, Prom RW v1) or it fails to parse.
3215pub fn parse_per_table_semantic_index(ctx: &QueryContextRef) -> Option<PerTableSemanticIndex> {
3216    let raw = ctx.extension(SEMANTIC_PER_TABLE_INDEX_KEY)?;
3217    match serde_json::from_str(raw) {
3218        Ok(index) => Some(index),
3219        Err(_) => {
3220            warn!("failed to parse semantic per-table index, skipping per-table options");
3221            None
3222        }
3223    }
3224}
3225
3226/// Folds the semantic keys of the table being created into `table_options`.
3227///
3228/// Common keys shared by every table in a request travel as plain semantic
3229/// extensions and are handled by [`fill_table_options_for_create`]; this
3230/// carries only the per-table tail and is applied after it, so a per-table
3231/// value (e.g. `declared` quality) wins. Keys are re-checked against the
3232/// vocabulary defensively.
3233pub fn apply_per_table_semantic_options(
3234    table_options: &mut std::collections::HashMap<String, String>,
3235    index: Option<&PerTableSemanticIndex>,
3236    schema: &str,
3237    table_name: &str,
3238) {
3239    let Some(entry) = index
3240        .and_then(|index| index.get(schema))
3241        .and_then(|tables| tables.get(table_name))
3242    else {
3243        return;
3244    };
3245    for (key, value) in entry {
3246        if is_semantic_option_key(key) && validate_semantic_option(key, value) {
3247            table_options.insert(key.clone(), value.clone());
3248        }
3249    }
3250}
3251
3252pub fn build_create_table_expr(
3253    table: &TableReference,
3254    request_schema: &[ColumnSchema],
3255    engine: &str,
3256) -> Result<CreateTableExpr> {
3257    expr_helper::create_table_expr_by_column_schemas(table, request_schema, engine, None)
3258}
3259
3260/// `QueryContext` extension key the Splunk HEC handler sets (to `"true"`) on its identity
3261/// path to request metadata-first primary-key ordering at table creation. It is absent for
3262/// user-supplied pipelines, so their primary-key order is left untouched.
3263pub const SPLUNK_PK_METADATA_ORDER_KEY: &str = "splunk_pk_metadata_order";
3264
3265/// Moves Splunk's metadata tags (`host`, `source`, `sourcetype`) to the front of the
3266/// primary key, keeping the relative order of the remaining tags.
3267fn reorder_splunk_primary_keys(primary_keys: &mut [String]) {
3268    const LEAD: [&str; 3] = ["host", "source", "sourcetype"];
3269    // Stable sort: `LEAD` columns move to the front in `host`/`source`/`sourcetype` order;
3270    // every other column keeps its existing relative position.
3271    primary_keys.sort_by_key(|name| {
3272        LEAD.iter()
3273            .position(|&lead| lead == name.as_str())
3274            .unwrap_or(LEAD.len())
3275    });
3276}
3277
3278/// Result of `create_or_alter_tables_on_demand`.
3279struct CreateAlterTableResult {
3280    /// table ids of ttl=instant tables.
3281    instant_table_ids: HashSet<TableId>,
3282    /// Table Info of the created tables.
3283    table_infos: HashMap<TableId, Arc<TableInfo>>,
3284}
3285
3286/// Upper bound of rows buffered by detached flow mirror tasks on this frontend.
3287///
3288/// Rows retained by in-flight mirror RPCs count against this bound. If ordinary
3289/// persisted source-table mirroring exceeds it, that mirror batch is best-effort
3290/// dropped while its datanode write continues. Instant-TTL batches fail retryably
3291/// on temporary saturation; oversized batches fail non-retryably so the client
3292/// can reduce the batch size.
3293const MAX_MIRROR_PENDING_ROWS: usize = 1_000_000;
3294
3295/// How often at most each mirror event is reported.
3296const MIRROR_LOG_INTERVAL: Duration = Duration::from_secs(10);
3297const MIRROR_LOG_NEVER_REPORTED: u64 = u64::MAX;
3298
3299struct MirrorLog {
3300    last_log_millis: AtomicU64,
3301    events: AtomicU64,
3302}
3303
3304impl MirrorLog {
3305    const fn new() -> Self {
3306        Self {
3307            last_log_millis: AtomicU64::new(MIRROR_LOG_NEVER_REPORTED),
3308            events: AtomicU64::new(0),
3309        }
3310    }
3311
3312    /// Returns the count since the previous report, including this event, to
3313    /// the single caller that claims the interval.
3314    fn claim_report(&self, now_millis: u64) -> Option<u64> {
3315        self.events.fetch_add(1, Ordering::Relaxed);
3316        let last = self.last_log_millis.load(Ordering::Relaxed);
3317        if last != MIRROR_LOG_NEVER_REPORTED
3318            && now_millis.saturating_sub(last) < MIRROR_LOG_INTERVAL.as_millis() as u64
3319        {
3320            return None;
3321        }
3322        if self
3323            .last_log_millis
3324            .compare_exchange(last, now_millis, Ordering::Relaxed, Ordering::Relaxed)
3325            .is_err()
3326        {
3327            return None;
3328        }
3329        Some(self.events.swap(0, Ordering::Relaxed))
3330    }
3331}
3332
3333static MIRROR_DROP_LOG: MirrorLog = MirrorLog::new();
3334static MIRROR_FAILURE_LOG: MirrorLog = MirrorLog::new();
3335
3336/// Milliseconds since the first call, so the drop log is rate limited on a
3337/// monotonic clock instead of the wall clock, which can jump.
3338fn mirror_drop_log_millis() -> u64 {
3339    static START: LazyLock<Instant> = LazyLock::new(Instant::now);
3340    START.elapsed().as_millis() as u64
3341}
3342
3343// A cold table needs a prefix scan to discover its flow partitions.
3344const MAX_CONCURRENT_FLOW_LOOKUPS: usize = 8;
3345
3346struct FlowMirrorTask {
3347    requests: HashMap<Peer, RegionInsertRequests>,
3348}
3349
3350impl FlowMirrorTask {
3351    async fn new(
3352        cache: &TableFlownodeSetCacheRef,
3353        requests: impl Iterator<Item = &RegionInsertRequest>,
3354    ) -> Result<Self> {
3355        let mut by_table: HashMap<TableId, Vec<&RegionInsertRequest>> = HashMap::new();
3356        for req in requests {
3357            let table_id = RegionId::from_u64(req.region_id).table_id();
3358            by_table.entry(table_id).or_default().push(req);
3359        }
3360
3361        let table_ids: Vec<_> = by_table.keys().copied().collect();
3362        let mut lookups = stream::iter(table_ids)
3363            .map(|id| async move { cache.get(id).await.map(|flows| (id, flows)) })
3364            .buffer_unordered(MAX_CONCURRENT_FLOW_LOOKUPS);
3365        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
3366        while let Some((id, flows)) = lookups.try_next().await.context(RequestInsertsSnafu)? {
3367            if let Some(flows) = flows {
3368                for peer in flows.values().collect::<HashSet<_>>() {
3369                    inserts
3370                        .entry(peer.clone())
3371                        .or_default()
3372                        .requests
3373                        .extend(by_table[&id].iter().copied().cloned());
3374                }
3375            }
3376        }
3377
3378        Ok(Self { requests: inserts })
3379    }
3380
3381    /// Rows of row data this task keeps alive once detached: the payload it
3382    /// spawns per peer, not the source requests it was built from.
3383    ///
3384    /// A source table mapped to several flownodes clones its requests per peer
3385    /// and every clone owns its own copy of the rows, so reserving from
3386    /// `self.requests` is what the per-peer shares released by [`Self::detach`]
3387    /// sum to. Counting the source requests instead under-reserves whenever a
3388    /// batch holds several requests for the same source table.
3389    fn pending_rows(&self) -> u64 {
3390        self.requests.values().map(region_inserts_rows).sum()
3391    }
3392
3393    fn detach(
3394        self,
3395        node_manager: NodeManagerRef,
3396        mirror_pending_rows: Arc<AtomicU64>,
3397        has_instant_rows: bool,
3398    ) -> Result<()> {
3399        // Reserve the cloned per-peer payload before spawning. A full budget
3400        // drops normal mirrors or rejects instant writes before datanode dispatch.
3401        let num_rows = self.pending_rows();
3402        if num_rows == 0 {
3403            return Ok(());
3404        }
3405        if has_instant_rows && num_rows > MAX_MIRROR_PENDING_ROWS as u64 {
3406            return InvalidInsertRequestSnafu {
3407                reason: format!(
3408                    "flow mirror batch has {num_rows} peer-fan-out rows, exceeding the limit of {}; reduce the batch size",
3409                    MAX_MIRROR_PENDING_ROWS
3410                ),
3411            }
3412            .fail();
3413        }
3414
3415        let pending = reserve_mirror_pending_rows(&mirror_pending_rows, num_rows);
3416        if pending > MAX_MIRROR_PENDING_ROWS as u64 {
3417            release_mirror_pending_rows(&mirror_pending_rows, num_rows);
3418            if has_instant_rows {
3419                return Err(meter_core::collect::WriteRejected::new(
3420                    "flow mirror pending rows limit exceeded for instant-TTL insert",
3421                ))
3422                .context(WriteRejectedSnafu);
3423            }
3424            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.inc_by(num_rows);
3425            if let Some(events) = MIRROR_DROP_LOG.claim_report(mirror_drop_log_millis()) {
3426                warn!(
3427                    "Flow mirror write dropped: {} pending rows exceeds limit {}, {} drop events since last report",
3428                    pending, MAX_MIRROR_PENDING_ROWS, events
3429                );
3430            }
3431            return Ok(());
3432        }
3433
3434        for (peer, inserts) in self.requests {
3435            // Each spawned task releases exactly its own share of the
3436            // reservation. The shares are computed over the same per-peer
3437            // payload as `pending_rows`, so they sum to the reservation.
3438            let peer_rows = region_inserts_rows(&inserts);
3439            let node_manager = node_manager.clone();
3440            let mirror_pending_rows = mirror_pending_rows.clone();
3441            common_runtime::spawn_global(async move {
3442                let result = node_manager
3443                    .flownode(&peer)
3444                    .await
3445                    .handle_inserts(inserts)
3446                    .await
3447                    .context(RequestInsertsSnafu);
3448
3449                match result {
3450                    Ok(resp) => {
3451                        let affected_rows = resp.affected_rows;
3452                        crate::metrics::DIST_MIRROR_ROW_COUNT.inc_by(affected_rows);
3453                    }
3454                    Err(err) => {
3455                        if let Some(events) =
3456                            MIRROR_FAILURE_LOG.claim_report(mirror_drop_log_millis())
3457                        {
3458                            error!(err; flownode_id = peer.id, flownode_addr = %peer.addr, "Failed to insert data into flownode ({} total mirror failures across peers since last report)", events);
3459                        }
3460                    }
3461                }
3462                // Release the reservation on both the success and the failure
3463                // path, otherwise a broken flownode would fill the budget forever.
3464                release_mirror_pending_rows(&mirror_pending_rows, peer_rows);
3465            });
3466        }
3467
3468        Ok(())
3469    }
3470}
3471
3472/// Rows of row data carried by `inserts`. A request without a `rows` payload
3473/// carries nothing to keep buffered and contributes zero.
3474fn region_inserts_rows(inserts: &RegionInsertRequests) -> u64 {
3475    inserts
3476        .requests
3477        .iter()
3478        .filter_map(|req| req.rows.as_ref())
3479        .map(|rows| rows.rows.len() as u64)
3480        .sum()
3481}
3482
3483/// Reserves `rows` of the pending mirror budget and returns the resulting
3484/// pending row count. The caller must [`release_mirror_pending_rows`] exactly
3485/// these rows once they are no longer buffered, whether it spawns the batch or
3486/// drops it.
3487fn reserve_mirror_pending_rows(mirror_pending_rows: &AtomicU64, rows: u64) -> u64 {
3488    let pending = mirror_pending_rows.fetch_add(rows, Ordering::Relaxed) + rows;
3489    // Keep the gauge in step by applying the same increment, never by setting an
3490    // absolute value: another task may move the budget in between.
3491    crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(rows as i64);
3492    pending
3493}
3494
3495/// Releases `rows` of the pending mirror budget.
3496///
3497/// Every release mirrors the reservation it hands back, so a well-behaved
3498/// release never subtracts more than is pending; the saturating update only
3499/// keeps a duplicated release from wrapping the shared budget around.
3500fn release_mirror_pending_rows(mirror_pending_rows: &AtomicU64, rows: u64) {
3501    let prev = mirror_pending_rows
3502        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |pending| {
3503            Some(pending.saturating_sub(rows))
3504        })
3505        .unwrap_or_else(|prev| prev);
3506    // Subtract from the gauge with the opposite sign of
3507    // [`reserve_mirror_pending_rows`]; reading the budget here and `set`-ting it
3508    // would publish a stale value whenever another task releases concurrently.
3509    let released = rows.min(prev);
3510    if released > 0 {
3511        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(released as i64);
3512    }
3513}
3514
3515#[cfg(test)]
3516mod tests {
3517    use std::future::Future;
3518    use std::sync::Arc;
3519    use std::sync::atomic::{AtomicU64, Ordering};
3520    use std::task::Poll;
3521
3522    use api::helper::ColumnDataTypeWrapper;
3523    use api::region::RegionResponse;
3524    use api::v1::flow::FlowResponse;
3525    use api::v1::helper::{field_column_schema, time_index_column_schema};
3526    use api::v1::{Row, RowInsertRequest, Rows, Value};
3527    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
3528    use common_error::ext::{ErrorExt, RetryHint};
3529    use common_error::mock::MockError;
3530    use common_error::status_code::StatusCode;
3531    use common_meta::cache::new_table_flownode_set_cache;
3532    use common_meta::cache_invalidator::DummyCacheInvalidator;
3533    use common_meta::ddl::test_util::datanode_handler::NaiveDatanodeHandler;
3534    use common_meta::instruction::{CacheIdent, CreateFlow};
3535    use common_meta::node_manager::{
3536        Datanode, DatanodeManager, DatanodeRef, FlownodeManager, FlownodeRef,
3537    };
3538    use common_meta::test_util::{MockDatanodeManager, MockFlownodeHandler, MockFlownodeManager};
3539    use common_query::native_histogram::NATIVE_HISTOGRAM_FIELD;
3540    use common_query::prelude::{greptime_native_histogram, set_default_prefix};
3541    use datatypes::data_type::ConcreteDataType;
3542    use datatypes::schema::ColumnSchema;
3543    use moka::future::Cache;
3544    use session::context::QueryContext;
3545    use table::TableRef;
3546    use table::dist_table::DummyDataSource;
3547    use table::metadata::{TableInfoBuilder, TableMetaBuilder, TableType};
3548    use tokio::sync::{Semaphore, mpsc};
3549
3550    use crate::insert::*;
3551    use crate::test_util::{
3552        create_partition_rule_manager, new_test_table_info, prepare_mocked_backend,
3553    };
3554    use crate::write_dispatcher::{TrackedWrite, WriteRetryOptions};
3555
3556    async fn cache_test_flow(cache: &TableFlownodeSetCacheRef, flow: CreateFlow) {
3557        cache.get_many(&flow.source_table_ids).await.unwrap();
3558        cache
3559            .invalidate(&[CacheIdent::CreateFlow(flow)])
3560            .await
3561            .unwrap();
3562    }
3563
3564    fn make_table_ref_with_schema(
3565        ts_name: &str,
3566        field_name: &str,
3567        field_type: ConcreteDataType,
3568    ) -> TableRef {
3569        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
3570            ColumnSchema::new(
3571                ts_name,
3572                ConcreteDataType::timestamp_millisecond_datatype(),
3573                false,
3574            )
3575            .with_time_index(true),
3576            ColumnSchema::new(field_name, field_type, true),
3577        ])
3578        .unwrap()
3579        .build()
3580        .unwrap();
3581        let meta = TableMetaBuilder::empty()
3582            .schema(Arc::new(schema))
3583            .primary_key_indices(vec![])
3584            .value_indices(vec![1])
3585            .engine("mito")
3586            .next_column_id(0)
3587            .options(Default::default())
3588            .created_on(Default::default())
3589            .build()
3590            .unwrap();
3591        let info = Arc::new(
3592            TableInfoBuilder::default()
3593                .table_id(1)
3594                .table_version(0)
3595                .name("test_table")
3596                .schema_name(DEFAULT_SCHEMA_NAME)
3597                .catalog_name(DEFAULT_CATALOG_NAME)
3598                .desc(None)
3599                .table_type(TableType::Base)
3600                .meta(meta)
3601                .build()
3602                .unwrap(),
3603        );
3604        Arc::new(table::Table::new(
3605            info,
3606            table::metadata::FilterPushDownType::Unsupported,
3607            Arc::new(DummyDataSource),
3608        ))
3609    }
3610
3611    fn make_metric_physical_table_ref_with_time_unit(unit: TimeUnit) -> TableRef {
3612        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
3613            ColumnSchema::new(
3614                greptime_timestamp(),
3615                ConcreteDataType::timestamp_datatype(unit),
3616                false,
3617            )
3618            .with_time_index(true),
3619            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
3620        ])
3621        .unwrap()
3622        .build()
3623        .unwrap();
3624        let meta = TableMetaBuilder::empty()
3625            .schema(Arc::new(schema))
3626            .primary_key_indices(vec![])
3627            .value_indices(vec![1])
3628            .engine("metric")
3629            .next_column_id(0)
3630            .options(Default::default())
3631            .created_on(Default::default())
3632            .build()
3633            .unwrap();
3634        let info = Arc::new(
3635            TableInfoBuilder::default()
3636                .table_id(1)
3637                .table_version(0)
3638                .name("greptime_physical_table")
3639                .schema_name(DEFAULT_SCHEMA_NAME)
3640                .catalog_name(DEFAULT_CATALOG_NAME)
3641                .desc(None)
3642                .table_type(TableType::Base)
3643                .meta(meta)
3644                .build()
3645                .unwrap(),
3646        );
3647        Arc::new(table::Table::new(
3648            info,
3649            table::metadata::FilterPushDownType::Unsupported,
3650            Arc::new(DummyDataSource),
3651        ))
3652    }
3653
3654    fn ms_row_insert_request(timestamp_ms: i64) -> RowInsertRequest {
3655        ms_row_insert_request_named("my_metric", timestamp_ms)
3656    }
3657
3658    fn ms_row_insert_request_named(table: &str, timestamp_ms: i64) -> RowInsertRequest {
3659        RowInsertRequest {
3660            table_name: table.to_string(),
3661            rows: Some(Rows {
3662                schema: vec![
3663                    time_index_column_schema(
3664                        greptime_timestamp(),
3665                        ColumnDataType::TimestampMillisecond,
3666                    ),
3667                    field_column_schema(greptime_value(), ColumnDataType::Float64),
3668                ],
3669                rows: vec![Row {
3670                    values: vec![
3671                        Value {
3672                            value_data: Some(ValueData::TimestampMillisecondValue(timestamp_ms)),
3673                        },
3674                        Value {
3675                            value_data: Some(ValueData::F64Value(1.0)),
3676                        },
3677                    ],
3678                }],
3679            }),
3680        }
3681    }
3682
3683    /// Converts the time index column of each request to `target_unit`.
3684    fn convert_row_insert_requests_time_unit(
3685        requests: &mut RowInsertRequests,
3686        target_unit: TimeUnit,
3687    ) -> Result<()> {
3688        for request in &mut requests.inserts {
3689            let Some(rows) = request.rows.as_mut() else {
3690                continue;
3691            };
3692            convert_rows_time_unit(rows, target_unit)?;
3693        }
3694        Ok(())
3695    }
3696
3697    #[test]
3698    fn test_convert_row_insert_requests_time_unit_noop_when_matching() {
3699        let mut requests = RowInsertRequests {
3700            inserts: vec![ms_row_insert_request(123)],
3701        };
3702        convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Millisecond).unwrap();
3703        let rows = requests.inserts[0].rows.as_ref().unwrap();
3704        assert_eq!(
3705            rows.schema[0].datatype,
3706            ColumnDataType::TimestampMillisecond as i32
3707        );
3708        assert!(matches!(
3709            rows.rows[0].values[0].value_data,
3710            Some(ValueData::TimestampMillisecondValue(123))
3711        ));
3712    }
3713
3714    #[test]
3715    fn test_convert_row_insert_requests_time_unit_widens_losslessly() {
3716        let mut requests = RowInsertRequests {
3717            inserts: vec![ms_row_insert_request(123)],
3718        };
3719        convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Microsecond).unwrap();
3720        let rows = requests.inserts[0].rows.as_ref().unwrap();
3721        assert_eq!(
3722            rows.schema[0].datatype,
3723            ColumnDataType::TimestampMicrosecond as i32
3724        );
3725        assert!(matches!(
3726            rows.rows[0].values[0].value_data,
3727            Some(ValueData::TimestampMicrosecondValue(123_000))
3728        ));
3729    }
3730
3731    #[test]
3732    fn test_convert_row_insert_requests_time_unit_truncates_on_narrowing() {
3733        // 123_456_789 ns floors to 123_456 us and 123 ms; negative values
3734        // floor towards negative infinity, matching `Timestamp::convert_to`.
3735        let requests = |value_ns: i64| RowInsertRequests {
3736            inserts: vec![RowInsertRequest {
3737                table_name: "my_metric".to_string(),
3738                rows: Some(Rows {
3739                    schema: vec![
3740                        time_index_column_schema(
3741                            greptime_timestamp(),
3742                            ColumnDataType::TimestampNanosecond,
3743                        ),
3744                        field_column_schema(greptime_value(), ColumnDataType::Float64),
3745                    ],
3746                    rows: vec![Row {
3747                        values: vec![
3748                            Value {
3749                                value_data: Some(ValueData::TimestampNanosecondValue(value_ns)),
3750                            },
3751                            Value {
3752                                value_data: Some(ValueData::F64Value(1.0)),
3753                            },
3754                        ],
3755                    }],
3756                }),
3757            }],
3758        };
3759
3760        let mut reqs = requests(123_456_789);
3761        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Microsecond).unwrap();
3762        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3763        assert!(matches!(
3764            rows.rows[0].values[0].value_data,
3765            Some(ValueData::TimestampMicrosecondValue(123_456))
3766        ));
3767
3768        let mut reqs = requests(123_456_789);
3769        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Millisecond).unwrap();
3770        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3771        assert!(matches!(
3772            rows.rows[0].values[0].value_data,
3773            Some(ValueData::TimestampMillisecondValue(123))
3774        ));
3775
3776        let mut reqs = requests(-123_456_789);
3777        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Microsecond).unwrap();
3778        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3779        assert!(matches!(
3780            rows.rows[0].values[0].value_data,
3781            Some(ValueData::TimestampMicrosecondValue(-123_457))
3782        ));
3783    }
3784
3785    #[test]
3786    fn test_convert_row_insert_requests_time_unit_overflow() {
3787        let mut requests = RowInsertRequests {
3788            inserts: vec![ms_row_insert_request(i64::MAX)],
3789        };
3790        let err =
3791            convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Nanosecond).unwrap_err();
3792        assert!(err.to_string().contains("overflows"), "{err}");
3793    }
3794
3795    #[test]
3796    fn test_table_time_index_unit() {
3797        assert_eq!(
3798            table_time_index_unit(&make_metric_physical_table_ref_with_time_unit(
3799                TimeUnit::Microsecond
3800            )),
3801            Some(TimeUnit::Microsecond)
3802        );
3803        assert_eq!(
3804            table_time_index_unit(&make_metric_physical_table_ref_with_time_unit(
3805                TimeUnit::Millisecond
3806            )),
3807            Some(TimeUnit::Millisecond)
3808        );
3809    }
3810
3811    #[tokio::test]
3812    async fn test_accommodate_existing_schema_and_reject_kind_changes() {
3813        let ts_name = "my_ts";
3814        let field_name = "my_field";
3815        let table =
3816            make_table_ref_with_schema(ts_name, field_name, ConcreteDataType::float64_datatype());
3817
3818        // The request uses different names for timestamp and field columns
3819        let mut req = RowInsertRequest {
3820            table_name: "test_table".to_string(),
3821            rows: Some(Rows {
3822                schema: vec![
3823                    time_index_column_schema("ts_wrong", ColumnDataType::TimestampMillisecond),
3824                    field_column_schema("field_wrong", ColumnDataType::Float64),
3825                ],
3826                rows: vec![api::v1::Row {
3827                    values: vec![Value::default(), Value::default()],
3828                }],
3829            }),
3830        };
3831        let ctx = Arc::new(QueryContext::with(
3832            DEFAULT_CATALOG_NAME,
3833            DEFAULT_SCHEMA_NAME,
3834        ));
3835
3836        let kv_backend = prepare_mocked_backend().await;
3837        let inserter = Inserter::new(
3838            catalog::memory::MemoryCatalogManager::new(),
3839            create_partition_rule_manager(kv_backend.clone()).await,
3840            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
3841            Arc::new(new_table_flownode_set_cache(
3842                String::new(),
3843                Cache::new(100),
3844                kv_backend.clone(),
3845            )),
3846            true,
3847        );
3848        // Do not apply an absent-table plan to a table that appeared concurrently.
3849        assert!(
3850            inserter
3851                .get_alter_table_expr_on_demand(&mut req, &table, &ctx, false, false, false)
3852                .unwrap()
3853                .is_none()
3854        );
3855        let alter_expr = inserter
3856            .get_alter_table_expr_on_demand(&mut req, &table, &ctx, true, true, true)
3857            .unwrap();
3858        assert!(alter_expr.is_none());
3859
3860        // The request's schema should have updated names for timestamp and field columns
3861        let req_schema = req.rows.as_ref().unwrap().schema.clone();
3862        assert_eq!(req_schema[0].column_name, ts_name);
3863        assert_eq!(req_schema[1].column_name, field_name);
3864
3865        let (datatype, datatype_extension) =
3866            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
3867                .unwrap()
3868                .into_parts();
3869        let mut histogram_req = RowInsertRequest {
3870            table_name: "test_table".to_string(),
3871            rows: Some(Rows {
3872                schema: vec![
3873                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
3874                    api::v1::ColumnSchema {
3875                        column_name: greptime_native_histogram().to_string(),
3876                        datatype: datatype as i32,
3877                        semantic_type: SemanticType::Field as i32,
3878                        datatype_extension,
3879                        options: None,
3880                    },
3881                ],
3882                rows: vec![],
3883            }),
3884        };
3885        let error = inserter
3886            .get_alter_table_expr_on_demand(&mut histogram_req, &table, &ctx, false, true, true)
3887            .unwrap_err();
3888        assert!(
3889            error
3890                .to_string()
3891                .contains("cannot mix native histogram and float sample fields")
3892        );
3893
3894        let histogram_table = make_table_ref_with_schema(
3895            "ts",
3896            greptime_native_histogram(),
3897            native_histogram_value_type().clone(),
3898        );
3899        let mut sample_req = RowInsertRequest {
3900            table_name: "test_table".to_string(),
3901            rows: Some(Rows {
3902                schema: vec![
3903                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
3904                    field_column_schema(greptime_value(), ColumnDataType::Float64),
3905                ],
3906                rows: vec![],
3907            }),
3908        };
3909        let error = inserter
3910            .get_alter_table_expr_on_demand(
3911                &mut sample_req,
3912                &histogram_table,
3913                &ctx,
3914                false,
3915                true,
3916                true,
3917            )
3918            .unwrap_err();
3919        assert!(
3920            error
3921                .to_string()
3922                .contains("cannot mix native histogram and float sample fields")
3923        );
3924    }
3925
3926    #[test]
3927    fn test_native_histogram_detection_survives_prefix_change() {
3928        set_default_prefix(Some("custom")).unwrap();
3929        let table = make_table_ref_with_schema(
3930            "custom_timestamp",
3931            NATIVE_HISTOGRAM_FIELD,
3932            native_histogram_value_type().clone(),
3933        );
3934        let (datatype, datatype_extension) =
3935            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
3936                .unwrap()
3937                .into_parts();
3938        let request_schema = [api::v1::ColumnSchema {
3939            column_name: greptime_native_histogram().to_string(),
3940            datatype: datatype as i32,
3941            semantic_type: SemanticType::Field as i32,
3942            datatype_extension,
3943            options: None,
3944        }];
3945
3946        assert!(request_is_native_histogram(&request_schema));
3947        assert!(table_is_native_histogram(&table));
3948    }
3949
3950    #[derive(Clone)]
3951    struct GatedDatanodeHandler {
3952        started: mpsc::UnboundedSender<u32>,
3953        completed: mpsc::UnboundedSender<u32>,
3954        release: Arc<Semaphore>,
3955    }
3956
3957    #[async_trait::async_trait]
3958    impl Datanode for GatedDatanodeHandler {
3959        async fn handle_request(
3960            &self,
3961            request: Arc<api::v1::region::RegionRequest>,
3962        ) -> common_meta::error::Result<RegionResponse> {
3963            let Some(api::v1::region::region_request::Body::Inserts(requests)) = &request.body
3964            else {
3965                panic!("expected inserts");
3966            };
3967            let region = RegionId::from(requests.requests[0].region_id).region_number();
3968            self.started.send(region).unwrap();
3969            self.release.acquire().await.unwrap().forget();
3970            self.completed.send(region).unwrap();
3971            if region == 2 {
3972                Err(common_meta::error::Error::retry_later(MockError::new(
3973                    StatusCode::RegionBusy,
3974                )))
3975            } else {
3976                Ok(RegionResponse::new(1))
3977            }
3978        }
3979
3980        async fn handle_query(
3981            &self,
3982            _request: common_query::request::QueryRequest,
3983        ) -> common_meta::error::Result<common_recordbatch::SendableRecordBatchStream> {
3984            unreachable!()
3985        }
3986    }
3987
3988    #[async_trait::async_trait]
3989    impl DatanodeManager for GatedDatanodeHandler {
3990        async fn datanode(&self, _peer: &Peer) -> DatanodeRef {
3991            Arc::new(self.clone())
3992        }
3993    }
3994
3995    #[async_trait::async_trait]
3996    impl FlownodeManager for GatedDatanodeHandler {
3997        async fn flownode(&self, _peer: &Peer) -> FlownodeRef {
3998            unreachable!()
3999        }
4000    }
4001
4002    #[tokio::test]
4003    async fn test_insert_cancellation_drains_inflight_writes() {
4004        for confirmed in [false, true] {
4005            for max_retries in [0, 2] {
4006                let mut inserter = batcher_test_inserter().await;
4007                let (started, mut starts) = mpsc::unbounded_channel();
4008                let (completed, mut completions) = mpsc::unbounded_channel();
4009                let release = Arc::new(Semaphore::new(0));
4010                let node_manager = Arc::new(GatedDatanodeHandler {
4011                    started,
4012                    completed,
4013                    release: release.clone(),
4014                });
4015                inserter.node_manager = node_manager.clone();
4016                let dispatcher = Arc::new(
4017                    WriteDispatcher::new(node_manager, inserter.partition_manager.clone())
4018                        .with_retry(
4019                            WriteRetryOptions {
4020                                max_retries,
4021                                initial_backoff: Duration::ZERO,
4022                                max_backoff: Duration::ZERO,
4023                                ..Default::default()
4024                            },
4025                            inserter.catalog_manager.clone(),
4026                            Arc::new(DummyCacheInvalidator),
4027                        ),
4028                );
4029                let inserter = inserter.with_write_dispatcher(dispatcher);
4030                let table_infos = HashMap::from_iter([(
4031                    1,
4032                    Arc::new(new_test_table_info(1, "table_1", [1].into_iter())),
4033                )]);
4034                let counter = Arc::new(session::write_progress::WriteProgress::default());
4035                let mut ctx = QueryContext::arc().fork();
4036                ctx.set_write_progress(counter.clone());
4037                let ctx = Arc::new(ctx);
4038                let ctx = if confirmed {
4039                    Arc::new(ctx.with_confirmed_writes())
4040                } else {
4041                    ctx
4042                };
4043                let requests = InstantAndNormalInsertRequests {
4044                    normal_requests: RegionInsertRequests {
4045                        requests: [1, 2]
4046                            .map(|region| RegionInsertRequest {
4047                                region_id: RegionId::new(1, region).as_u64(),
4048                                rows: Some(Rows {
4049                                    schema: vec![],
4050                                    rows: vec![Row { values: vec![] }],
4051                                }),
4052                                ..Default::default()
4053                            })
4054                            .to_vec(),
4055                    },
4056                    instant_requests: RegionInsertRequests::default(),
4057                };
4058                let caller =
4059                    tokio::spawn(
4060                        async move { inserter.do_request(requests, &table_infos, &ctx).await },
4061                    );
4062                for _ in 0..2 {
4063                    tokio::time::timeout(Duration::from_secs(5), starts.recv())
4064                        .await
4065                        .unwrap()
4066                        .unwrap();
4067                }
4068                caller.abort();
4069                assert!(caller.await.unwrap_err().is_cancelled());
4070                release.add_permits(2);
4071                // Closing the channel proves the detached dispatcher has finished.
4072                let mut completed = tokio::time::timeout(Duration::from_secs(5), async {
4073                    let mut regions = Vec::new();
4074                    while let Some(region) = completions.recv().await {
4075                        regions.push(region);
4076                    }
4077                    regions
4078                })
4079                .await
4080                .unwrap();
4081                completed.sort_unstable();
4082                assert_eq!(
4083                    completed,
4084                    vec![1, 2],
4085                    "confirmed={confirmed}, retries={max_retries}"
4086                );
4087                assert!(
4088                    starts.try_recv().is_err(),
4089                    "cancelled caller started another retry"
4090                );
4091                assert_eq!(counter.written(), 1);
4092            }
4093        }
4094    }
4095
4096    #[tokio::test]
4097    async fn test_tracked_cancellation_stops_backoff() {
4098        let inserter = batcher_test_inserter().await;
4099        let (started, mut starts) = mpsc::unbounded_channel();
4100        let (completed, mut completions) = mpsc::unbounded_channel();
4101        let node_manager = Arc::new(GatedDatanodeHandler {
4102            started,
4103            completed,
4104            release: Arc::new(Semaphore::new(2)),
4105        });
4106        let dispatcher = WriteDispatcher::new(node_manager, inserter.partition_manager.clone())
4107            .with_retry(
4108                WriteRetryOptions {
4109                    max_retries: 2,
4110                    initial_backoff: Duration::from_secs(60),
4111                    max_backoff: Duration::from_secs(60),
4112                    ..Default::default()
4113                },
4114                inserter.catalog_manager.clone(),
4115                Arc::new(DummyCacheInvalidator),
4116            );
4117        let factory = RegionRequestFactory::new(RegionRequestHeader::default());
4118        let requests = [1, 2]
4119            .into_iter()
4120            .map(|region| TrackedWrite {
4121                request: factory.build_insert(RegionInsertRequests {
4122                    requests: vec![RegionInsertRequest {
4123                        region_id: RegionId::new(1, region).as_u64(),
4124                        ..Default::default()
4125                    }],
4126                }),
4127                owners: vec![(region - 1) as usize],
4128            })
4129            .collect();
4130        let (writes, progress) = dispatcher.prepare_tracked(requests, 2).await;
4131        let cancellation = CancellationToken::new();
4132        let execute = dispatcher.execute_tracked(writes, progress, None, Some(&cancellation));
4133        tokio::pin!(execute);
4134        // Wait for both sends to complete before cancelling the backoff.
4135        tokio::time::timeout(
4136            Duration::from_secs(1),
4137            future::poll_fn(|cx| {
4138                assert!(execute.as_mut().poll(cx).is_pending());
4139                if completions.len() == 2 {
4140                    Poll::Ready(())
4141                } else {
4142                    Poll::Pending
4143                }
4144            }),
4145        )
4146        .await
4147        .unwrap();
4148        for region in [1, 2] {
4149            assert_eq!(starts.try_recv().unwrap(), region);
4150            assert_eq!(completions.try_recv().unwrap(), region);
4151        }
4152        cancellation.cancel();
4153        let progress = tokio::time::timeout(Duration::from_secs(1), execute)
4154            .await
4155            .unwrap();
4156        assert_eq!(progress[0].affected_rows, 1);
4157        assert!(progress[0].error.is_none());
4158        assert_eq!(progress[1].affected_rows, 0);
4159        assert_eq!(
4160            progress[1].error.as_ref().unwrap().retry_hint(),
4161            RetryHint::Retryable
4162        );
4163        assert!(starts.try_recv().is_err());
4164    }
4165
4166    fn test_exemplar_table_info(
4167        id: TableId,
4168        catalog: &str,
4169        schema: &str,
4170        extra_tags: &[&str],
4171        instant: bool,
4172    ) -> TableInfoRef {
4173        use common_query::prelude::greptime_exemplar_labels;
4174        use common_time::ttl::TimeToLive;
4175        use datatypes::schema::{ColumnSchema, Schema};
4176        use table::metadata::{TableInfoBuilder, TableMetaBuilder};
4177
4178        let mut labels_col = ColumnSchema::new(
4179            greptime_exemplar_labels(),
4180            datatypes::data_type::ConcreteDataType::json2(
4181                datatypes::types::json_type::JsonNativeType::Null,
4182            ),
4183            true,
4184        );
4185        labels_col.with_extension_type(&datatypes::extension::json::Json2ExtensionType::new(
4186            Arc::new(datatypes::extension::json::JsonMetadata::new(
4187                datatypes::json::JsonSettings::new_v2(),
4188            )),
4189        ));
4190        let mut columns = vec![
4191            ColumnSchema::new(
4192                DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4193                datatypes::data_type::ConcreteDataType::uint32_datatype(),
4194                false,
4195            ),
4196            ColumnSchema::new(
4197                DATA_SCHEMA_TSID_COLUMN_NAME,
4198                datatypes::data_type::ConcreteDataType::uint64_datatype(),
4199                false,
4200            ),
4201            ColumnSchema::new(
4202                EXEMPLAR_METRIC_COLUMN,
4203                datatypes::data_type::ConcreteDataType::string_datatype(),
4204                true,
4205            ),
4206        ];
4207        for &tag in extra_tags {
4208            columns.push(ColumnSchema::new(
4209                tag,
4210                datatypes::data_type::ConcreteDataType::string_datatype(),
4211                true,
4212            ));
4213        }
4214        let pk_len = columns.len();
4215        columns.push(
4216            ColumnSchema::new(
4217                greptime_timestamp(),
4218                datatypes::data_type::ConcreteDataType::timestamp_nanosecond_datatype(),
4219                false,
4220            )
4221            .with_time_index(true),
4222        );
4223        columns.push(ColumnSchema::new(
4224            greptime_value(),
4225            datatypes::data_type::ConcreteDataType::float64_datatype(),
4226            true,
4227        ));
4228        columns.push(labels_col);
4229        let column_ids: Vec<u32> = std::iter::once(ReservedColumnId::table_id())
4230            .chain(std::iter::once(ReservedColumnId::tsid()))
4231            .chain(10..10 + (columns.len() as u32 - 2))
4232            .collect();
4233        let next_column_id = *column_ids.last().unwrap() + 1;
4234        let mut info = TableInfoBuilder::default()
4235            .table_id(id)
4236            .table_version(0)
4237            .name(METRICS_EXEMPLARS_TABLE)
4238            .catalog_name(catalog)
4239            .schema_name(schema)
4240            .meta(
4241                TableMetaBuilder::empty()
4242                    .schema(Arc::new(Schema::new(columns)))
4243                    .primary_key_indices((0..pk_len).collect())
4244                    .column_ids(column_ids)
4245                    .next_column_id(next_column_id)
4246                    .engine("mito")
4247                    .build()
4248                    .unwrap(),
4249            )
4250            .build()
4251            .unwrap();
4252        info.meta
4253            .options
4254            .extra_options
4255            .insert(APPEND_MODE_KEY.to_string(), "true".to_string());
4256        info.meta.options.extra_options.insert(
4257            store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
4258            "sparse".to_string(),
4259        );
4260        if instant {
4261            info.meta.options.ttl = Some(TimeToLive::Instant);
4262        }
4263        Arc::new(info)
4264    }
4265
4266    async fn register_unpartitioned_table_route(
4267        kv_backend: &common_meta::kv_backend::KvBackendRef,
4268        table_info: &TableInfo,
4269    ) {
4270        common_meta::key::TableMetadataManager::new(kv_backend.clone())
4271            .create_table_metadata(
4272                table_info.clone(),
4273                common_meta::key::table_route::TableRouteValue::physical(vec![
4274                    common_meta::rpc::router::RegionRoute {
4275                        region: common_meta::rpc::router::Region {
4276                            id: RegionId::new(table_info.table_id(), 1),
4277                            name: "r0".to_string(),
4278                            attrs: BTreeMap::new(),
4279                            partition_expr: String::new(),
4280                        },
4281                        leader_peer: Some(common_meta::peer::Peer::new(1, "")),
4282                        follower_peers: vec![],
4283                        leader_state: None,
4284                        leader_down_since: None,
4285                        write_route_policy: None,
4286                    },
4287                ]),
4288                std::collections::HashMap::new(),
4289            )
4290            .await
4291            .unwrap();
4292    }
4293
4294    // Keep global meter registration in one test, isolated by nextest's per-test process.
4295    #[tokio::test]
4296    async fn test_write_meter_admission() {
4297        use std::cell::Cell;
4298        use std::sync::Mutex;
4299        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4300
4301        use api::region::RegionResponse;
4302        use api::v1::region::region_request::Body;
4303        use arrow::array::{Int32Array, TimestampMillisecondArray};
4304        use arrow::record_batch::RecordBatch;
4305        use bytes::Bytes;
4306        use common_error::ext::{ErrorExt, RetryHint};
4307        use common_error::status_code::StatusCode;
4308        use common_grpc::flight::{FlightEncoder, FlightMessage};
4309        use common_meta::ddl::test_util::datanode_handler::DatanodeWatcher;
4310        use futures::future::BoxFuture;
4311        use meter_core::ItemCalculator;
4312        use meter_core::collect::{Collect, WriteRejected};
4313        use meter_core::data::MeterRecord;
4314        use meter_core::global::global_registry;
4315        use session::context::Channel;
4316
4317        const CATALOG: &str = "write_meter_test";
4318
4319        #[derive(Default)]
4320        struct Meter {
4321            reject: AtomicBool,
4322            attempts: Mutex<Vec<MeterRecord>>,
4323            accepted_value: AtomicU64,
4324        }
4325
4326        impl Collect for Meter {
4327            fn on_write(
4328                &self,
4329                record: MeterRecord,
4330            ) -> BoxFuture<'_, std::result::Result<(), WriteRejected>> {
4331                Box::pin(async move {
4332                    if record.catalog != CATALOG {
4333                        return Ok(());
4334                    }
4335                    let value = record.value;
4336                    self.attempts.lock().unwrap().push(record);
4337                    if self.reject.load(Ordering::Relaxed) {
4338                        return Err(WriteRejected::new("database row quota exhausted"));
4339                    }
4340                    self.accepted_value.fetch_add(value, Ordering::Relaxed);
4341                    Ok(())
4342                })
4343            }
4344
4345            fn on_read(&self, _: MeterRecord) {}
4346        }
4347
4348        impl ItemCalculator<InstantAndNormalInsertRequests> for Meter {
4349            fn calc(&self, _: &InstantAndNormalInsertRequests) -> u64 {
4350                17
4351            }
4352        }
4353
4354        let kv_backend = prepare_mocked_backend().await;
4355        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
4356        let (sender, mut dispatched) = tokio::sync::mpsc::channel(16);
4357        let watcher = DatanodeWatcher::new(sender).with_handler(|_, request| {
4358            let rows = match request.body.unwrap() {
4359                Body::Inserts(requests) => requests
4360                    .requests
4361                    .iter()
4362                    .filter_map(|request| request.rows.as_ref())
4363                    .map(|rows| rows.rows.len())
4364                    .sum(),
4365                // The bulk batches below each contain two rows.
4366                Body::BulkInsert(_) => 2,
4367                body => panic!("unexpected request: {body:?}"),
4368            };
4369            Ok(RegionResponse::new(rows))
4370        });
4371        let inserter = Inserter::new(
4372            catalog::memory::MemoryCatalogManager::new(),
4373            partition_manager,
4374            Arc::new(MockDatanodeManager::new(watcher)),
4375            Arc::new(new_table_flownode_set_cache(
4376                String::new(),
4377                Cache::new(100),
4378                kv_backend.clone(),
4379            )),
4380            true,
4381        );
4382        let mut table_info = new_test_table_info(1, "table_1", [1].into_iter());
4383        table_info.catalog_name = CATALOG.to_string();
4384        table_info.schema_name = "target_db".to_string();
4385        let table_info = Arc::new(table_info);
4386        let table_infos = HashMap::from_iter([(1, table_info.clone())]);
4387        let ctx = Arc::new(QueryContext::with_channel(
4388            DEFAULT_CATALOG_NAME,
4389            DEFAULT_SCHEMA_NAME,
4390            Channel::Postgres,
4391        ));
4392        let rows_request = || {
4393            let build = |num_rows| RegionInsertRequests {
4394                requests: vec![RegionInsertRequest {
4395                    region_id: RegionId::new(1, 1).as_u64(),
4396                    rows: Some(Rows {
4397                        schema: vec![],
4398                        rows: vec![api::v1::Row { values: vec![] }; num_rows],
4399                    }),
4400                    ..Default::default()
4401                }],
4402            };
4403            InstantAndNormalInsertRequests {
4404                normal_requests: build(3),
4405                instant_requests: build(2),
4406            }
4407        };
4408
4409        // No collector or calculator: ordinary OSS insertion still succeeds.
4410        let output = inserter
4411            .do_request(rows_request(), &table_infos, &ctx)
4412            .await
4413            .unwrap();
4414        assert_eq!(output.meta.cost, 0);
4415        assert!(matches!(output.data, OutputData::AffectedRows(3)));
4416        dispatched.try_recv().unwrap();
4417
4418        let meter = Arc::new(Meter::default());
4419        global_registry().set_collector(meter.clone());
4420        global_registry().register_calculator(meter.clone());
4421        // The dependency controls noop mode; exercise both builds with this test.
4422        let enabled = Cell::new(false);
4423        write_meter!({
4424            enabled.set(true);
4425            MeterRecord::new("probe".into(), "probe".into(), 0, 0, 0)
4426        })
4427        .await
4428        .unwrap();
4429        let enabled = enabled.get();
4430
4431        let output = inserter
4432            .do_request(rows_request(), &table_infos, &ctx)
4433            .await
4434            .unwrap();
4435        assert_eq!(output.meta.cost, if enabled { 17 } else { 0 });
4436        assert!(matches!(output.data, OutputData::AffectedRows(3)));
4437        dispatched.try_recv().unwrap();
4438        let flow_cache = inserter.table_flownode_set_cache();
4439        assert!(flow_cache.contains_key(&1));
4440        common_meta::cache_invalidator::CacheInvalidator::invalidate_all(flow_cache.as_ref())
4441            .unwrap();
4442        meter.reject.store(true, Ordering::Relaxed);
4443        let result = inserter
4444            .do_request(rows_request(), &table_infos, &ctx)
4445            .await;
4446        if enabled {
4447            let error = result.unwrap_err();
4448            assert_eq!(error.status_code(), StatusCode::RateLimited);
4449            assert_eq!(error.retry_hint(), RetryHint::Retryable);
4450            assert!(error.to_string().contains("database row quota exhausted"));
4451            assert!(dispatched.try_recv().is_err());
4452            assert!(
4453                !flow_cache.contains_key(&1),
4454                "rejected write reached flow mirroring"
4455            );
4456            assert_eq!(meter.accepted_value.load(Ordering::Relaxed), 17);
4457            let attempts = meter.attempts.lock().unwrap();
4458            assert_eq!(attempts.len(), 2);
4459            for record in attempts.iter() {
4460                assert_eq!(record.catalog, CATALOG);
4461                assert_eq!(record.schema, "target_db");
4462                assert_eq!(
4463                    (record.rows, record.value, record.source),
4464                    (5, 17, Channel::Postgres as u8)
4465                );
4466            }
4467        } else {
4468            assert_eq!(result.unwrap().meta.cost, 0);
4469            dispatched.try_recv().unwrap();
4470            assert!(meter.attempts.lock().unwrap().is_empty());
4471        }
4472        meter.attempts.lock().unwrap().clear();
4473
4474        // Rejection must precede queue submission, but conversion memory is reserved first.
4475        if enabled {
4476            let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher {
4477                allow_acquire: true,
4478            });
4479            let rows = Rows {
4480                schema: vec![
4481                    api::v1::helper::tag_column_schema("a", ColumnDataType::Int32),
4482                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
4483                    field_column_schema("b", ColumnDataType::Int32),
4484                ],
4485                rows: vec![api::v1::Row {
4486                    values: vec![
4487                        api::v1::value::ValueData::I32Value(60).into(),
4488                        Value {
4489                            value_data: Some(api::v1::value::ValueData::TimestampMillisecondValue(
4490                                0,
4491                            )),
4492                        },
4493                        api::v1::value::ValueData::I32Value(0).into(),
4494                    ],
4495                }],
4496            };
4497            let error = inserter
4498                .submit_table_rows(
4499                    rows,
4500                    table_info.clone(),
4501                    ctx.skip_wal(),
4502                    ctx.clone(),
4503                    &batcher,
4504                )
4505                .await
4506                .unwrap_err();
4507            assert_eq!(error.status_code(), StatusCode::RateLimited);
4508            let mut attempts = meter.attempts.lock().unwrap();
4509            assert_eq!(attempts.len(), 1);
4510            assert_eq!(attempts[0].catalog, CATALOG);
4511            assert_eq!(attempts[0].schema, "target_db");
4512            assert_eq!(attempts[0].rows, 1);
4513            attempts.clear();
4514        }
4515
4516        let table = Arc::new(table::Table::new(
4517            table_info.clone(),
4518            table::metadata::FilterPushDownType::Unsupported,
4519            Arc::new(DummyDataSource),
4520        ));
4521        let batch = RecordBatch::try_new(
4522            table_info.meta.schema.arrow_schema().clone(),
4523            vec![
4524                Arc::new(Int32Array::from(vec![60, 70])),
4525                Arc::new(TimestampMillisecondArray::from(vec![0, 1])),
4526                Arc::new(Int32Array::from(vec![0, 0])),
4527            ],
4528        )
4529        .unwrap();
4530        let bulk_insert = |batch: RecordBatch| {
4531            let flight_data = FlightEncoder::default()
4532                .encode(FlightMessage::RecordBatch(batch.clone()))
4533                .into_iter()
4534                .next()
4535                .unwrap();
4536            inserter.handle_bulk_insert(
4537                table.clone(),
4538                flight_data,
4539                batch,
4540                Bytes::new(),
4541                false,
4542                Channel::Grpc,
4543            )
4544        };
4545        // Empty batches bypass admission even while the collector rejects.
4546        assert_eq!(bulk_insert(batch.slice(0, 0)).await.unwrap(), 0);
4547        assert!(meter.attempts.lock().unwrap().is_empty());
4548        assert!(dispatched.try_recv().is_err());
4549
4550        // A collector change between batches takes effect on the very next batch.
4551        for reject in [false, true, false] {
4552            meter.reject.store(reject, Ordering::Relaxed);
4553            let result = bulk_insert(batch.clone()).await;
4554            if enabled && reject {
4555                let error = result.unwrap_err();
4556                assert_eq!(error.status_code(), StatusCode::RateLimited);
4557                assert_eq!(error.retry_hint(), RetryHint::Retryable);
4558                assert!(dispatched.try_recv().is_err());
4559            } else {
4560                assert_eq!(result.unwrap(), 2);
4561                dispatched.try_recv().unwrap();
4562            }
4563        }
4564        {
4565            let attempts = meter.attempts.lock().unwrap();
4566            assert_eq!(attempts.len(), if enabled { 3 } else { 0 });
4567            for record in attempts.iter() {
4568                assert_eq!(record.catalog, CATALOG);
4569                assert_eq!(record.schema, "target_db");
4570                assert_eq!(
4571                    (record.rows, record.value, record.source),
4572                    (2, 0, Channel::Grpc as u8)
4573                );
4574            }
4575        }
4576        assert_eq!(
4577            meter.accepted_value.load(Ordering::Relaxed),
4578            if enabled { 17 } else { 0 }
4579        );
4580
4581        // Aggregate repeated database targets and retain admission across nested
4582        // batching without changing the caller's reusable context.
4583        meter.attempts.lock().unwrap().clear();
4584        let original = Arc::new(QueryContext::with_channel(
4585            CATALOG,
4586            "a",
4587            Channel::Prometheus,
4588        ));
4589        let mut batches = ["a", "b", "a"].map(|schema| {
4590            let ctx = if schema == "a" {
4591                original.clone()
4592            } else {
4593                Arc::new(QueryContext::with_channel(
4594                    CATALOG,
4595                    schema,
4596                    Channel::Prometheus,
4597                ))
4598            };
4599            (
4600                ctx,
4601                RowInsertRequests {
4602                    inserts: vec![RowInsertRequest {
4603                        table_name: "data".into(),
4604                        rows: Some(Rows {
4605                            schema: vec![],
4606                            rows: vec![api::v1::Row::default(); 2],
4607                        }),
4608                    }],
4609                },
4610            )
4611        });
4612        admit_row_insert_batches(&mut batches).await.unwrap();
4613        admit_row_insert_batches(&mut batches).await.unwrap();
4614        assert_eq!(original.write_rows_to_admit(CATALOG, "a", 4), 4);
4615        for (ctx, _) in &batches {
4616            assert_eq!(
4617                ctx.write_rows_to_admit(CATALOG, &ctx.current_schema(), 2),
4618                0
4619            );
4620            assert_eq!(ctx.channel(), Channel::Prometheus);
4621        }
4622        {
4623            let attempts = meter.attempts.lock().unwrap();
4624            let totals = attempts
4625                .iter()
4626                .map(|r| (r.schema.as_str(), r.rows, r.value))
4627                .collect::<Vec<_>>();
4628            assert_eq!(
4629                totals,
4630                if enabled {
4631                    vec![("a", 4, 0), ("b", 2, 0)]
4632                } else {
4633                    vec![]
4634                }
4635            );
4636        }
4637        meter.attempts.lock().unwrap().clear();
4638        meter.reject.store(false, Ordering::Relaxed);
4639        let ctx = Arc::new(QueryContext::with_channel(
4640            CATALOG,
4641            "logical",
4642            Channel::Otlp,
4643        ));
4644        let admitted = admit_write(2, &ctx).await.unwrap();
4645        let mut requests = RowInsertRequests {
4646            inserts: vec![RowInsertRequest {
4647                table_name: "metric".to_string(),
4648                rows: Some(Rows {
4649                    schema: vec![],
4650                    rows: vec![api::v1::Row::default(); 2],
4651                }),
4652            }],
4653        };
4654        let original = requests.clone();
4655        let cost = Inserter::meter_row_inserts(&mut requests, &admitted)
4656            .await
4657            .unwrap();
4658        assert_eq!(cost, if enabled { 17 } else { 0 });
4659        assert_eq!(requests, original);
4660        let records = meter
4661            .attempts
4662            .lock()
4663            .unwrap()
4664            .iter()
4665            .map(|record| (record.rows, record.value))
4666            .collect::<Vec<_>>();
4667        assert_eq!(
4668            records,
4669            if enabled {
4670                vec![(2, 0), (0, 17)]
4671            } else {
4672                vec![]
4673            }
4674        );
4675        meter.reject.store(true, Ordering::Relaxed);
4676        let result = Inserter::meter_row_inserts(&mut requests, &admitted).await;
4677        if enabled {
4678            assert_eq!(result.unwrap_err().status_code(), StatusCode::RateLimited);
4679        } else {
4680            assert_eq!(result.unwrap(), 0);
4681        }
4682        assert_eq!(requests, original);
4683
4684        // Verify direct sparse writes and exemplar writes meter through `InstantAndNormalInsertRequests`.
4685        {
4686            use datatypes::schema::{ColumnSchema, Schema};
4687
4688            meter.attempts.lock().unwrap().clear();
4689            meter.reject.store(false, Ordering::Relaxed);
4690
4691            let mut sparse_info = new_test_table_info(10, "table_10", [1].into_iter());
4692            sparse_info.catalog_name = CATALOG.to_string();
4693            sparse_info.schema_name = "target_db".to_string();
4694            sparse_info.meta.engine = default_engine().to_string();
4695            sparse_info.meta.schema = Arc::new(Schema::new(vec![
4696                ColumnSchema::new(
4697                    DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4698                    datatypes::data_type::ConcreteDataType::uint32_datatype(),
4699                    false,
4700                ),
4701                ColumnSchema::new(
4702                    DATA_SCHEMA_TSID_COLUMN_NAME,
4703                    datatypes::data_type::ConcreteDataType::uint64_datatype(),
4704                    false,
4705                ),
4706                ColumnSchema::new(
4707                    "ts",
4708                    datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(),
4709                    false,
4710                )
4711                .with_time_index(true),
4712                ColumnSchema::new(
4713                    "val",
4714                    datatypes::data_type::ConcreteDataType::float64_datatype(),
4715                    true,
4716                ),
4717            ]));
4718            sparse_info.meta.primary_key_indices = vec![0, 1];
4719            sparse_info.meta.column_ids =
4720                vec![ReservedColumnId::table_id(), ReservedColumnId::tsid(), 2, 3];
4721            sparse_info.meta.options.extra_options.insert(
4722                store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
4723                "sparse".to_string(),
4724            );
4725            let sparse_info = Arc::new(sparse_info);
4726            register_unpartitioned_table_route(&kv_backend, &sparse_info).await;
4727            let sparse_rows = Rows {
4728                schema: vec![
4729                    api::v1::helper::tag_column_schema(
4730                        DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4731                        ColumnDataType::Uint32,
4732                    ),
4733                    api::v1::helper::tag_column_schema(
4734                        DATA_SCHEMA_TSID_COLUMN_NAME,
4735                        ColumnDataType::Uint64,
4736                    ),
4737                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
4738                    field_column_schema("val", ColumnDataType::Float64),
4739                ],
4740                rows: vec![
4741                    api::v1::Row {
4742                        values: vec![
4743                            ValueData::U32Value(10).into(),
4744                            ValueData::U64Value(20).into(),
4745                            ValueData::TimestampMillisecondValue(1).into(),
4746                            ValueData::F64Value(1.5).into(),
4747                        ],
4748                    },
4749                    api::v1::Row {
4750                        values: vec![
4751                            ValueData::U32Value(10).into(),
4752                            ValueData::U64Value(21).into(),
4753                            ValueData::TimestampMillisecondValue(2).into(),
4754                            ValueData::F64Value(2.5).into(),
4755                        ],
4756                    },
4757                ],
4758            };
4759            let sparse_ctx = Arc::new(QueryContext::with_channel(
4760                CATALOG,
4761                "target_db",
4762                Channel::Postgres,
4763            ));
4764            let mixed = RowInsertRequests {
4765                inserts: vec![
4766                    RowInsertRequest {
4767                        table_name: sparse_info.name.clone(),
4768                        rows: Some(sparse_rows.clone()),
4769                    },
4770                    RowInsertRequest {
4771                        table_name: table_info.name.clone(),
4772                        rows: Some(Rows {
4773                            schema: vec![api::v1::helper::tag_column_schema(
4774                                "a",
4775                                ColumnDataType::Int32,
4776                            )],
4777                            rows: [1, 11, 101]
4778                                .into_iter()
4779                                .map(|a| Row {
4780                                    values: vec![ValueData::I32Value(a).into()],
4781                                })
4782                                .collect(),
4783                        }),
4784                    },
4785                ],
4786            };
4787            let infos = HashMap::from_iter([
4788                (sparse_info.table_id(), sparse_info.clone()),
4789                (table_info.table_id(), table_info.clone()),
4790            ]);
4791            for confirmed in [false, true] {
4792                for skip_wal in [false, true] {
4793                    let ctx = Arc::new(if confirmed {
4794                        sparse_ctx.with_confirmed_writes()
4795                    } else {
4796                        sparse_ctx.fork()
4797                    });
4798                    ctx.set_skip_wal(!skip_wal);
4799                    let out = inserter
4800                        .dispatch_direct_sparse_row_inserts(
4801                            mixed.clone(),
4802                            infos.clone(),
4803                            HashSet::new(),
4804                            skip_wal,
4805                            &ctx,
4806                        )
4807                        .await
4808                        .unwrap();
4809                    assert!(matches!(out.data, OutputData::AffectedRows(5)));
4810                    assert_eq!(out.meta.cost, if enabled { 17 } else { 0 });
4811                    let records = std::mem::take(&mut *meter.attempts.lock().unwrap());
4812                    assert_eq!(records.len(), usize::from(enabled));
4813                    if enabled {
4814                        assert_eq!((records[0].rows, records[0].value), (5, 17));
4815                    }
4816
4817                    let mut bulk_requests = 0;
4818                    let mut dense_rows = 0;
4819                    while let Ok((_, request)) = dispatched.try_recv() {
4820                        match request.body.unwrap() {
4821                            Body::BulkInsert(bulk) => {
4822                                assert_eq!(
4823                                    RegionId::from_u64(bulk.region_id).table_id(),
4824                                    sparse_info.table_id()
4825                                );
4826                                assert_eq!(bulk.skip_wal, skip_wal);
4827                                bulk_requests += 1;
4828                            }
4829                            Body::Inserts(inserts) => {
4830                                for insert in inserts.requests {
4831                                    assert_eq!(
4832                                        RegionId::from_u64(insert.region_id).table_id(),
4833                                        table_info.table_id()
4834                                    );
4835                                    assert_eq!(insert.skip_wal, skip_wal);
4836                                    dense_rows += insert.rows.unwrap().rows.len();
4837                                }
4838                            }
4839                            body => panic!("unexpected request: {body:?}"),
4840                        }
4841                    }
4842                    assert_eq!((bulk_requests, dense_rows), (1, 3));
4843                }
4844            }
4845
4846            meter.reject.store(true, Ordering::Relaxed);
4847            let err_or_ok = inserter
4848                .dispatch_single_sparse_table_rows(sparse_rows, sparse_info, false, &sparse_ctx)
4849                .await;
4850            if enabled {
4851                assert_eq!(
4852                    err_or_ok.unwrap_err().status_code(),
4853                    StatusCode::RateLimited
4854                );
4855                assert!(dispatched.try_recv().is_err());
4856            } else {
4857                assert_eq!(err_or_ok.unwrap().meta.cost, 0);
4858                dispatched.try_recv().unwrap();
4859            }
4860
4861            // Exemplar batch WCU metering.
4862            meter.attempts.lock().unwrap().clear();
4863            meter.reject.store(false, Ordering::Relaxed);
4864            let exemplar_info = test_exemplar_table_info(11, CATALOG, "target_db", &[], false);
4865            register_unpartitioned_table_route(&kv_backend, &exemplar_info).await;
4866            let ex_batch = ExemplarBatch::try_new(vec![
4867                Exemplar {
4868                    metric: "cpu".into(),
4869                    series_labels: BTreeMap::new().into(),
4870                    timestamp: 1_000,
4871                    value: 1.0,
4872                    labels: BTreeMap::new(),
4873                },
4874                Exemplar {
4875                    metric: "cpu".into(),
4876                    series_labels: BTreeMap::new().into(),
4877                    timestamp: 2_000,
4878                    value: 2.0,
4879                    labels: BTreeMap::new(),
4880                },
4881            ])
4882            .unwrap();
4883            let resolved = HashMap::from_iter([("cpu".to_string(), 100)]);
4884            let ex_ctx = Arc::new(QueryContext::with_channel(
4885                CATALOG,
4886                "target_db",
4887                Channel::Otlp,
4888            ));
4889            let ex_out = inserter
4890                .execute_exemplar_write(
4891                    ex_batch.clone(),
4892                    resolved.clone(),
4893                    exemplar_info.clone(),
4894                    false,
4895                    ex_ctx.clone(),
4896                )
4897                .await
4898                .unwrap();
4899            assert_eq!(ex_out.meta.cost, if enabled { 17 } else { 0 });
4900            dispatched.try_recv().unwrap();
4901            {
4902                let attempts = meter.attempts.lock().unwrap();
4903                assert_eq!(attempts.len(), if enabled { 1 } else { 0 });
4904                if enabled {
4905                    assert_eq!((attempts[0].rows, attempts[0].value), (2, 17));
4906                }
4907            }
4908            meter.reject.store(true, Ordering::Relaxed);
4909            let rejected = inserter
4910                .execute_exemplar_write(ex_batch, resolved, exemplar_info, false, ex_ctx)
4911                .await;
4912            if enabled {
4913                assert_eq!(rejected.unwrap_err().status_code(), StatusCode::RateLimited);
4914                assert!(dispatched.try_recv().is_err());
4915            } else {
4916                assert_eq!(rejected.unwrap().meta.cost, 0);
4917                dispatched.try_recv().unwrap();
4918            }
4919        }
4920    }
4921
4922    #[test]
4923    fn test_trace_create_options_copy_compaction_hints() {
4924        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
4925        ctx.set_extension("compaction.twcs.time_window", "1h");
4926        ctx.set_extension("compaction.twcs.max_output_file_size", "256MB");
4927        ctx.set_extension("compaction.twcs.remote_compaction", "true");
4928        ctx.set_extension("compaction.unknown", "ignored");
4929        let ctx = Arc::new(ctx);
4930        let mut table_options = Default::default();
4931
4932        fill_table_options_for_create(
4933            &mut table_options,
4934            &AutoCreateTableType::Trace {
4935                alter_existing: true,
4936            },
4937            &ctx,
4938        );
4939
4940        assert_eq!(
4941            Some("twcs"),
4942            table_options.get(COMPACTION_TYPE).map(String::as_str)
4943        );
4944        assert_eq!(
4945            Some("1h"),
4946            table_options
4947                .get("compaction.twcs.time_window")
4948                .map(String::as_str)
4949        );
4950        assert_eq!(
4951            Some("256MB"),
4952            table_options
4953                .get("compaction.twcs.max_output_file_size")
4954                .map(String::as_str)
4955        );
4956        assert_eq!(
4957            Some("true"),
4958            table_options
4959                .get("compaction.twcs.remote_compaction")
4960                .map(String::as_str)
4961        );
4962        assert!(!table_options.contains_key("compaction.unknown"));
4963    }
4964
4965    #[test]
4966    fn test_exemplar_create_options_isolate_metric_context() {
4967        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
4968        for (key, value) in [
4969            (APPEND_MODE_KEY, "false"),
4970            (MERGE_MODE_KEY, "last_non_null"),
4971            (PHYSICAL_TABLE_METADATA_KEY, "true"),
4972            (LOGICAL_TABLE_METADATA_KEY, "physical_metrics"),
4973            ("otlp_metric_compat", "prometheus"),
4974            (table::requests::SEMANTIC_SIGNAL_TYPE, "metric"),
4975            (SEMANTIC_PER_TABLE_INDEX_KEY, "{}"),
4976            ("ttl", "7d"),
4977            ("compaction.twcs.time_window", "1h"),
4978        ] {
4979            ctx.set_extension(key, value);
4980        }
4981        let mut options = Default::default();
4982        fill_table_options_for_create(&mut options, &AutoCreateTableType::Exemplar, &Arc::new(ctx));
4983        assert_eq!(
4984            options,
4985            std::collections::HashMap::from([
4986                (APPEND_MODE_KEY.into(), "true".into()),
4987                (
4988                    store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.into(),
4989                    "sparse".into()
4990                ),
4991                ("ttl".into(), "7d".into()),
4992                (COMPACTION_TYPE.into(), "twcs".into()),
4993                ("compaction.twcs.time_window".into(), "1h".into()),
4994            ])
4995        );
4996    }
4997
4998    #[test]
4999    fn test_skip_wal_does_not_change_table_options() {
5000        check_skip_wal_does_not_change_table_options(false);
5001        check_skip_wal_does_not_change_table_options(true);
5002    }
5003
5004    fn check_skip_wal_does_not_change_table_options(skip_wal: bool) {
5005        let ctx = Arc::new(QueryContext::with(
5006            DEFAULT_CATALOG_NAME,
5007            DEFAULT_SCHEMA_NAME,
5008        ));
5009        ctx.set_skip_wal(skip_wal);
5010        let mut options = Default::default();
5011        fill_table_options_for_create(&mut options, &AutoCreateTableType::Physical, &ctx);
5012        assert!(!options.contains_key(session::hints::INSERT_SKIP_WAL_HINT));
5013        assert!(!options.contains_key("skip_wal"));
5014    }
5015
5016    #[test]
5017    fn test_last_non_null_create_options_preserve_default_without_append_mode() {
5018        let ctx = Arc::new(QueryContext::with(
5019            DEFAULT_CATALOG_NAME,
5020            DEFAULT_SCHEMA_NAME,
5021        ));
5022        let mut table_options = Default::default();
5023
5024        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5025
5026        assert_eq!(
5027            Some("last_non_null"),
5028            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5029        );
5030        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5031    }
5032
5033    #[test]
5034    fn test_fill_table_options_copies_semantic_extensions() {
5035        use table::requests::{
5036            SEMANTIC_METRIC_TYPE, SEMANTIC_PER_TABLE_INDEX_KEY, SEMANTIC_SIGNAL_TYPE,
5037            SEMANTIC_SOURCE, SEMANTIC_SOURCE_VERSION, SIGNAL_TYPE_METRIC, SOURCE_OPENTELEMETRY,
5038        };
5039
5040        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5041        ctx.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC);
5042        ctx.set_extension(SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY);
5043        ctx.set_extension(SEMANTIC_SOURCE_VERSION, "2.0");
5044        ctx.set_extension(SEMANTIC_METRIC_TYPE, "bogus");
5045        // The internal transport key must NOT be copied into table options.
5046        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, "{}");
5047        let ctx = Arc::new(ctx);
5048        let mut table_options = Default::default();
5049
5050        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::Physical, &ctx);
5051
5052        assert_eq!(
5053            Some(SIGNAL_TYPE_METRIC),
5054            table_options.get(SEMANTIC_SIGNAL_TYPE).map(String::as_str)
5055        );
5056        assert_eq!(
5057            Some(SOURCE_OPENTELEMETRY),
5058            table_options.get(SEMANTIC_SOURCE).map(String::as_str)
5059        );
5060        assert_eq!(
5061            Some("2.0"),
5062            table_options
5063                .get(SEMANTIC_SOURCE_VERSION)
5064                .map(String::as_str)
5065        );
5066        assert!(!table_options.contains_key(SEMANTIC_METRIC_TYPE));
5067        assert!(!table_options.contains_key(SEMANTIC_PER_TABLE_INDEX_KEY));
5068    }
5069
5070    #[test]
5071    fn test_apply_retention_ttl_hint_copies_only_retention_ttl() {
5072        let mut instant_ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5073        instant_ctx.set_extension(TTL_KEY, "instant");
5074        instant_ctx.set_extension(APPEND_MODE_KEY, "true");
5075        let instant_ctx = Arc::new(instant_ctx);
5076        let mut instant_options = std::collections::HashMap::new();
5077        apply_retention_ttl_hint(&mut instant_options, &instant_ctx);
5078        assert!(instant_options.is_empty());
5079
5080        let mut retention_ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5081        retention_ctx.set_extension(TTL_KEY, "7d");
5082        retention_ctx.set_extension(APPEND_MODE_KEY, "true");
5083        let retention_ctx = Arc::new(retention_ctx);
5084        let mut retention_options = std::collections::HashMap::new();
5085        apply_retention_ttl_hint(&mut retention_options, &retention_ctx);
5086        assert_eq!(
5087            retention_options.get(TTL_KEY).map(String::as_str),
5088            Some("7d")
5089        );
5090        assert!(!retention_options.contains_key(APPEND_MODE_KEY));
5091    }
5092
5093    #[test]
5094    fn test_apply_per_table_semantic_options() {
5095        use table::requests::{
5096            SEMANTIC_METRIC_TYPE, SEMANTIC_METRIC_UNIT, SEMANTIC_PER_TABLE_INDEX_KEY,
5097        };
5098
5099        let index = format!(
5100            r#"{{
5101            "{DEFAULT_SCHEMA_NAME}": {{
5102                "http_requests_total": {{
5103                    "greptime.semantic.metric.type": "counter",
5104                    "greptime.semantic.metric.unit": "By",
5105                    "greptime.semantic.metric.type_BOGUS": "x"
5106                }},
5107                "other_table": {{
5108                    "greptime.semantic.metric.type": "gauge"
5109                }}
5110            }},
5111            "other_schema": {{
5112                "http_requests_total": {{
5113                    "greptime.semantic.metric.type": "gauge"
5114                }}
5115            }}
5116        }}"#
5117        );
5118        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5119        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, index);
5120        let ctx = Arc::new(ctx);
5121
5122        let index = parse_per_table_semantic_index(&ctx);
5123        assert!(index.is_some());
5124        let index = index.as_ref();
5125
5126        let mut table_options = std::collections::HashMap::new();
5127        apply_per_table_semantic_options(
5128            &mut table_options,
5129            index,
5130            DEFAULT_SCHEMA_NAME,
5131            "http_requests_total",
5132        );
5133        // The write schema's entry applies — not other_schema's `gauge`.
5134        assert_eq!(
5135            table_options.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
5136            Some("counter")
5137        );
5138        assert_eq!(
5139            table_options.get(SEMANTIC_METRIC_UNIT).map(String::as_str),
5140            Some("By")
5141        );
5142        // The unknown key is rejected by the vocabulary check; other tables' keys
5143        // never appear.
5144        assert!(!table_options.contains_key("greptime.semantic.metric.type_BOGUS"));
5145        assert_eq!(table_options.len(), 2);
5146
5147        let mut empty = std::collections::HashMap::new();
5148        apply_per_table_semantic_options(&mut empty, index, DEFAULT_SCHEMA_NAME, "not_in_index");
5149        assert!(empty.is_empty());
5150
5151        // A schema with no entry is a no-op even when the table name matches
5152        // elsewhere.
5153        let mut opts = std::collections::HashMap::new();
5154        apply_per_table_semantic_options(
5155            &mut opts,
5156            index,
5157            "schema_without_entry",
5158            "http_requests_total",
5159        );
5160        assert!(opts.is_empty());
5161
5162        // No extension at all parses to no index (e.g. logs / Prom RW v1).
5163        let bare = Arc::new(QueryContext::with(
5164            DEFAULT_CATALOG_NAME,
5165            DEFAULT_SCHEMA_NAME,
5166        ));
5167        assert!(parse_per_table_semantic_index(&bare).is_none());
5168        let mut opts = std::collections::HashMap::new();
5169        apply_per_table_semantic_options(
5170            &mut opts,
5171            None,
5172            DEFAULT_SCHEMA_NAME,
5173            "http_requests_total",
5174        );
5175        assert!(opts.is_empty());
5176    }
5177
5178    #[test]
5179    fn test_last_non_null_create_options_preserve_default_with_append_mode_false() {
5180        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5181        ctx.set_extension(APPEND_MODE_KEY, "false");
5182        let ctx = Arc::new(ctx);
5183        let mut table_options = Default::default();
5184
5185        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5186
5187        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5188        assert_eq!(
5189            Some("last_non_null"),
5190            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5191        );
5192    }
5193
5194    #[test]
5195    fn test_last_non_null_create_options_use_configured_merge_mode() {
5196        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5197        ctx.set_extension(MERGE_MODE_KEY, "last_row");
5198        let ctx = Arc::new(ctx);
5199        let mut table_options = Default::default();
5200
5201        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5202
5203        assert_eq!(
5204            Some("last_row"),
5205            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5206        );
5207        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5208    }
5209
5210    #[test]
5211    fn test_last_non_null_create_options_use_last_row_with_append_mode_true() {
5212        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5213        ctx.set_extension(APPEND_MODE_KEY, "true");
5214        let ctx = Arc::new(ctx);
5215        let mut table_options = Default::default();
5216
5217        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5218
5219        assert_eq!(
5220            Some("true"),
5221            table_options.get(APPEND_MODE_KEY).map(String::as_str)
5222        );
5223        assert_eq!(
5224            Some("last_row"),
5225            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5226        );
5227    }
5228
5229    #[derive(Default)]
5230    struct UnexpectedBatcher {
5231        allow_acquire: bool,
5232    }
5233
5234    #[async_trait::async_trait]
5235    impl PendingRowsBatcher for UnexpectedBatcher {
5236        async fn acquire(&self, _: usize, _: u64) -> Result<crate::batcher::PendingRowsPermit> {
5237            assert!(
5238                self.allow_acquire,
5239                "empty writes must not acquire batch admission"
5240            );
5241            Ok(Arc::new(()))
5242        }
5243
5244        async fn submit(
5245            &self,
5246            _table_info: TableInfoRef,
5247            _batch: arrow::record_batch::RecordBatch,
5248            _ctx: QueryContextRef,
5249            _permit: crate::batcher::PendingRowsPermit,
5250        ) -> Result<Output> {
5251            panic!("writes must not submit a batch")
5252        }
5253    }
5254
5255    async fn batcher_test_inserter() -> Inserter {
5256        let kv_backend = prepare_mocked_backend().await;
5257        Inserter::new(
5258            catalog::memory::MemoryCatalogManager::new(),
5259            create_partition_rule_manager(kv_backend.clone()).await,
5260            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5261            Arc::new(new_table_flownode_set_cache(
5262                String::new(),
5263                Cache::new(100),
5264                kv_backend,
5265            )),
5266            true,
5267        )
5268    }
5269
5270    #[tokio::test]
5271    async fn test_logical_batcher_eligibility() {
5272        use catalog::RegisterTableRequest;
5273        use catalog::memory::MemoryCatalogManager;
5274        use common_meta::kv_backend::KvBackendRef;
5275        use common_meta::kv_backend::memory::MemoryKvBackend;
5276        use datatypes::schema::{ColumnDefaultConstraint, SchemaBuilder};
5277        let requests = RowInsertRequests {
5278            inserts: vec![RowInsertRequest {
5279                table_name: "test_table".to_string(),
5280                rows: None,
5281            }],
5282        };
5283        let original =
5284            make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5285                .table_info();
5286        for case in [
5287            "eligible",
5288            "physical",
5289            "ordinary",
5290            "instant",
5291            "disabled",
5292            "hint",
5293            "flow",
5294            "required_tag",
5295            "default",
5296        ] {
5297            let mut info = (*original).clone();
5298            info.meta.engine = METRIC_ENGINE_NAME.to_string();
5299            info.meta.options.extra_options.insert(
5300                LOGICAL_TABLE_METADATA_KEY.to_string(),
5301                "physical".to_string(),
5302            );
5303            let mut ctx = QueryContext::arc().fork();
5304            match case {
5305                "physical" => {
5306                    info.meta
5307                        .options
5308                        .extra_options
5309                        .insert(LOGICAL_TABLE_METADATA_KEY.to_string(), "other".to_string());
5310                }
5311                "ordinary" => info.meta.engine = "mito".to_string(),
5312                "instant" => info.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant),
5313                "hint" => ctx.set_extension(AUTO_CREATE_TABLE_KEY, "false"),
5314                "required_tag" | "default" => {
5315                    let mut columns = info.meta.schema.column_schemas().to_vec();
5316                    let mut tag = ColumnSchema::new(
5317                        "tag",
5318                        ConcreteDataType::string_datatype(),
5319                        case != "required_tag",
5320                    );
5321                    if case == "default" {
5322                        tag = tag
5323                            .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
5324                            .unwrap();
5325                    }
5326                    columns.push(tag);
5327                    info.meta.schema = Arc::new(
5328                        SchemaBuilder::try_from_columns(columns)
5329                            .unwrap()
5330                            .build()
5331                            .unwrap(),
5332                    );
5333                    info.meta.primary_key_indices = vec![2];
5334                }
5335                _ => {}
5336            }
5337            let catalog = MemoryCatalogManager::with_default_setup();
5338            let table = Arc::new(table::Table::new(
5339                Arc::new(info),
5340                table::metadata::FilterPushDownType::Unsupported,
5341                Arc::new(DummyDataSource),
5342            ));
5343            catalog
5344                .register_table_sync(RegisterTableRequest {
5345                    catalog: DEFAULT_CATALOG_NAME.to_string(),
5346                    schema: DEFAULT_SCHEMA_NAME.to_string(),
5347                    table_name: "test_table".to_string(),
5348                    table_id: 1,
5349                    table,
5350                })
5351                .unwrap();
5352            let mut inserter = batcher_test_inserter().await;
5353            inserter.catalog_manager = catalog;
5354            inserter.auto_create_table = case != "disabled";
5355            let kv_backend: KvBackendRef = Arc::new(MemoryKvBackend::default());
5356            inserter.table_flownode_set_cache = Arc::new(new_table_flownode_set_cache(
5357                String::new(),
5358                Cache::new(10),
5359                kv_backend,
5360            ));
5361            if case == "flow" {
5362                cache_test_flow(
5363                    &inserter.table_flownode_set_cache,
5364                    CreateFlow {
5365                        flow_id: 1,
5366                        source_table_ids: vec![1],
5367                        partition_to_peer_mapping: vec![(0, Peer::empty(1))],
5368                    },
5369                )
5370                .await;
5371            }
5372            assert_eq!(
5373                inserter
5374                    .can_batch_metric_rows(&requests, &Arc::new(ctx), "physical")
5375                    .await
5376                    .unwrap(),
5377                case == "eligible",
5378                "{case}"
5379            );
5380        }
5381    }
5382
5383    #[tokio::test]
5384    async fn test_batcher_meter_preserves_request() {
5385        let mut requests = RowInsertRequests {
5386            inserts: vec![RowInsertRequest {
5387                table_name: "sample".to_string(),
5388                rows: Some(Rows {
5389                    schema: vec![],
5390                    rows: vec![api::v1::Row {
5391                        values: vec![Value {
5392                            value_data: Some(api::v1::value::ValueData::F64Value(1.5)),
5393                        }],
5394                    }],
5395                }),
5396            }],
5397        };
5398        let expected = requests.clone();
5399        Inserter::meter_row_inserts(&mut requests, &QueryContext::arc())
5400            .await
5401            .unwrap();
5402        assert_eq!(requests, expected);
5403    }
5404
5405    #[tokio::test]
5406    async fn test_instant_table_bypasses_batcher() {
5407        let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher::default());
5408        let inserter = batcher_test_inserter()
5409            .await
5410            .with_pending_rows_batcher(Some(batcher));
5411        let mut ctx = session::context::QueryContextBuilder::default().build();
5412        ctx.set_batching_enabled(true);
5413        let ctx = Arc::new(ctx);
5414        let table = make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5415            .table_info();
5416        assert!(inserter.table_batcher(&table, &ctx).is_some());
5417        let mut instant = (*table).clone();
5418        instant.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant);
5419        assert!(inserter.table_batcher(&Arc::new(instant), &ctx).is_none());
5420    }
5421
5422    #[tokio::test]
5423    async fn test_empty_prepared_rows_skip_batcher() {
5424        let inserter = batcher_test_inserter().await;
5425        let table = make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5426            .table_info();
5427        let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher::default());
5428        let ctx = QueryContext::arc();
5429        let output = inserter
5430            .submit_table_rows(
5431                Rows {
5432                    schema: vec![],
5433                    rows: vec![],
5434                },
5435                table.clone(),
5436                ctx.skip_wal(),
5437                ctx.clone(),
5438                &batcher,
5439            )
5440            .await
5441            .unwrap();
5442        assert!(matches!(output.data, OutputData::AffectedRows(0)));
5443        let output = inserter
5444            .submit_pending_rows(
5445                RowInsertRequests {
5446                    inserts: vec![RowInsertRequest {
5447                        table_name: table.name.clone(),
5448                        rows: None,
5449                    }],
5450                },
5451                HashMap::from_iter([(table.table_id(), table)]),
5452                ctx.skip_wal(),
5453                ctx,
5454                &batcher,
5455            )
5456            .await
5457            .unwrap();
5458        assert!(matches!(output.data, OutputData::AffectedRows(0)));
5459    }
5460
5461    /// Flownode handler that keeps mirror inserts in flight until the test
5462    /// releases the gate, so the pending mirror budget can be observed
5463    /// deterministically.
5464    #[derive(Clone)]
5465    struct GatedFlownodeHandler {
5466        gate: Arc<tokio::sync::Semaphore>,
5467        affected_rows: u64,
5468    }
5469
5470    #[async_trait::async_trait]
5471    impl MockFlownodeHandler for GatedFlownodeHandler {
5472        async fn handle_inserts(
5473            &self,
5474            _peer: &Peer,
5475            _requests: api::v1::region::InsertRequests,
5476        ) -> common_meta::error::Result<FlowResponse> {
5477            let _permit = self.gate.acquire().await.unwrap();
5478            Ok(FlowResponse {
5479                affected_rows: self.affected_rows,
5480                ..Default::default()
5481            })
5482        }
5483    }
5484
5485    fn flownode_peer() -> Peer {
5486        Peer {
5487            id: 1,
5488            addr: "127.0.0.1:4001".to_string(),
5489        }
5490    }
5491
5492    #[derive(Clone)]
5493    struct RecordingNodeManager {
5494        datanode_dispatch: tokio::sync::mpsc::UnboundedSender<usize>,
5495        flownode_dispatch: mpsc::UnboundedSender<(Peer, RegionInsertRequests)>,
5496        gates: Arc<std::sync::Mutex<HashMap<u64, Arc<tokio::sync::Semaphore>>>>,
5497        fail_flownode: bool,
5498    }
5499
5500    #[async_trait::async_trait]
5501    impl common_meta::node_manager::DatanodeManager for RecordingNodeManager {
5502        async fn datanode(&self, peer: &Peer) -> common_meta::node_manager::DatanodeRef {
5503            Arc::new(RecordingNode {
5504                peer: peer.clone(),
5505                manager: self.clone(),
5506            })
5507        }
5508    }
5509
5510    #[async_trait::async_trait]
5511    impl common_meta::node_manager::FlownodeManager for RecordingNodeManager {
5512        async fn flownode(&self, peer: &Peer) -> common_meta::node_manager::FlownodeRef {
5513            Arc::new(RecordingNode {
5514                peer: peer.clone(),
5515                manager: self.clone(),
5516            })
5517        }
5518    }
5519
5520    struct RecordingNode {
5521        peer: Peer,
5522        manager: RecordingNodeManager,
5523    }
5524
5525    #[async_trait::async_trait]
5526    impl common_meta::node_manager::Datanode for RecordingNode {
5527        async fn handle_request(
5528            &self,
5529            _request: Arc<api::v1::region::RegionRequest>,
5530        ) -> common_meta::error::Result<api::region::RegionResponse> {
5531            let rows = match _request.body.as_ref() {
5532                Some(api::v1::region::region_request::Body::Inserts(requests)) => requests
5533                    .requests
5534                    .iter()
5535                    .filter_map(|request| request.rows.as_ref())
5536                    .map(|rows| rows.rows.len())
5537                    .sum(),
5538                Some(api::v1::region::region_request::Body::BulkInsert(bulk)) => {
5539                    let Some(api::v1::region::bulk_insert_request::Body::ArrowIpc(ipc)) =
5540                        bulk.body.as_ref()
5541                    else {
5542                        return Ok(api::region::RegionResponse::new(0));
5543                    };
5544                    common_grpc::flight::FlightDecoder::try_from_schema_bytes(&ipc.schema)
5545                        .and_then(|mut decoder| {
5546                            decoder.try_decode_record_batch(&ipc.data_header, &ipc.payload)
5547                        })
5548                        .map(|batch| batch.num_rows())
5549                        .unwrap_or(0)
5550                }
5551                _ => 0,
5552            };
5553            let _ = self.manager.datanode_dispatch.send(rows);
5554            Ok(api::region::RegionResponse::new(rows))
5555        }
5556
5557        async fn handle_query(
5558            &self,
5559            _request: common_query::request::QueryRequest,
5560        ) -> common_meta::error::Result<common_recordbatch::SendableRecordBatchStream> {
5561            unreachable!()
5562        }
5563    }
5564
5565    #[async_trait::async_trait]
5566    impl common_meta::node_manager::Flownode for RecordingNode {
5567        async fn handle(
5568            &self,
5569            _request: api::v1::flow::FlowRequest,
5570        ) -> common_meta::error::Result<FlowResponse> {
5571            unreachable!()
5572        }
5573
5574        async fn handle_inserts(
5575            &self,
5576            request: api::v1::region::InsertRequests,
5577        ) -> common_meta::error::Result<FlowResponse> {
5578            let _ = self
5579                .manager
5580                .flownode_dispatch
5581                .send((self.peer.clone(), request));
5582            if self.manager.fail_flownode {
5583                return Err(common_meta::error::UnexpectedSnafu {
5584                    err_msg: "test flownode failure".to_string(),
5585                }
5586                .build());
5587            }
5588            let gate = self
5589                .manager
5590                .gates
5591                .lock()
5592                .unwrap()
5593                .get(&self.peer.id)
5594                .cloned();
5595            if let Some(gate) = gate {
5596                let _permit = gate.acquire().await.unwrap();
5597            }
5598            Ok(FlowResponse::default())
5599        }
5600
5601        async fn handle_mark_window_dirty(
5602            &self,
5603            _request: api::v1::flow::DirtyWindowRequests,
5604        ) -> common_meta::error::Result<FlowResponse> {
5605            unreachable!()
5606        }
5607    }
5608
5609    fn mirror_requests(peer: &Peer, num_rows: usize) -> HashMap<Peer, RegionInsertRequests> {
5610        HashMap::from_iter([(
5611            peer.clone(),
5612            RegionInsertRequests {
5613                requests: vec![RegionInsertRequest {
5614                    region_id: RegionId::new(1, 1).as_u64(),
5615                    rows: Some(Rows {
5616                        schema: vec![],
5617                        rows: vec![api::v1::Row { values: vec![] }; num_rows],
5618                    }),
5619                    ..Default::default()
5620                }],
5621            },
5622        )])
5623    }
5624
5625    /// Serializes the mirror metric tests below: the metrics are process-wide
5626    /// singletons, so these tests would otherwise observe each other's updates
5627    /// when the test binary runs tests in parallel (they are isolated per
5628    /// process only under nextest).
5629    static MIRROR_METRIC_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
5630
5631    async fn lock_mirror_metrics() -> tokio::sync::MutexGuard<'static, ()> {
5632        MIRROR_METRIC_TEST_LOCK.lock().await
5633    }
5634
5635    // The tests below share the process-wide mirror metrics, so they take
5636    // `MIRROR_METRIC_TEST_LOCK` and assert on the difference their own budget
5637    // publishes instead of on absolute values.
5638    #[tokio::test]
5639    async fn flow_mirror_saturation_preserves_instant_and_normal_contracts() {
5640        use common_error::ext::{ErrorExt, RetryHint};
5641        use common_error::status_code::StatusCode;
5642
5643        let _guard = lock_mirror_metrics().await;
5644        let kv_backend = prepare_mocked_backend().await;
5645        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
5646        let (datanode_tx, mut datanode_rx) = tokio::sync::mpsc::unbounded_channel();
5647        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
5648        let node_manager = Arc::new(RecordingNodeManager {
5649            datanode_dispatch: datanode_tx,
5650            flownode_dispatch: flownode_tx,
5651            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
5652            fail_flownode: false,
5653        });
5654        let flow_cache = Cache::new(10);
5655        let flow_cache_backend = prepare_mocked_backend().await;
5656        let inserter = Inserter::new(
5657            catalog::memory::MemoryCatalogManager::new(),
5658            partition_manager,
5659            node_manager,
5660            Arc::new(new_table_flownode_set_cache(
5661                String::new(),
5662                flow_cache.clone(),
5663                flow_cache_backend,
5664            )),
5665            true,
5666        );
5667        let peer = flownode_peer();
5668        cache_test_flow(
5669            &inserter.table_flownode_set_cache,
5670            CreateFlow {
5671                flow_id: 1,
5672                source_table_ids: vec![1, 2],
5673                partition_to_peer_mapping: vec![(0, peer)],
5674            },
5675        )
5676        .await;
5677        let mut normal_info = new_test_table_info(1, "normal_table", [1].into_iter());
5678        normal_info.catalog_name = DEFAULT_CATALOG_NAME.to_string();
5679        normal_info.schema_name = DEFAULT_SCHEMA_NAME.to_string();
5680        let mut instant_info = new_test_table_info(2, "instant_table", [1].into_iter());
5681        instant_info.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant);
5682        let table_infos =
5683            HashMap::from_iter([(1, Arc::new(normal_info)), (2, Arc::new(instant_info))]);
5684        let ctx = Arc::new(QueryContext::with(
5685            DEFAULT_CATALOG_NAME,
5686            DEFAULT_SCHEMA_NAME,
5687        ));
5688        let insert = |table_id, num_rows| RegionInsertRequests {
5689            requests: vec![RegionInsertRequest {
5690                region_id: RegionId::new(table_id, 1).as_u64(),
5691                rows: Some(Rows {
5692                    schema: vec![],
5693                    rows: vec![api::v1::Row::default(); num_rows],
5694                }),
5695                ..Default::default()
5696            }],
5697        };
5698        let make_request = |normal, instant| InstantAndNormalInsertRequests {
5699            normal_requests: if normal == 0 {
5700                RegionInsertRequests::default()
5701            } else {
5702                insert(1, normal)
5703            },
5704            instant_requests: if instant == 0 {
5705                RegionInsertRequests::default()
5706            } else {
5707                insert(2, instant)
5708            },
5709        };
5710
5711        let pending = inserter.mirror_pending_rows.clone();
5712        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
5713        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(MAX_MIRROR_PENDING_ROWS as i64);
5714        pending.store(MAX_MIRROR_PENDING_ROWS as u64, Ordering::Relaxed);
5715        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
5716        for request in [make_request(0, 1), make_request(1, 1)] {
5717            let error = inserter
5718                .do_request(request, &table_infos, &ctx)
5719                .await
5720                .unwrap_err();
5721            assert_eq!(error.status_code(), StatusCode::RateLimited);
5722            assert_eq!(error.retry_hint(), RetryHint::Retryable);
5723            assert!(datanode_rx.try_recv().is_err());
5724            assert!(flownode_rx.try_recv().is_err());
5725            assert_eq!(
5726                pending.load(Ordering::Relaxed),
5727                MAX_MIRROR_PENDING_ROWS as u64
5728            );
5729        }
5730        assert_eq!(
5731            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5732            dropped_before
5733        );
5734
5735        for pending_before in [0, MAX_MIRROR_PENDING_ROWS as u64] {
5736            if pending_before == 0 {
5737                pending.store(0, Ordering::Relaxed);
5738                crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(MAX_MIRROR_PENDING_ROWS as i64);
5739            }
5740            let gauge_before_rejection = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
5741            for (normal, instant) in [
5742                (0, MAX_MIRROR_PENDING_ROWS + 1),
5743                (MAX_MIRROR_PENDING_ROWS / 2, MAX_MIRROR_PENDING_ROWS / 2 + 1),
5744            ] {
5745                let error = inserter
5746                    .do_request(make_request(normal, instant), &table_infos, &ctx)
5747                    .await
5748                    .unwrap_err();
5749                assert_eq!(error.status_code(), StatusCode::InvalidArguments);
5750                assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
5751                let message = error.to_string();
5752                assert!(message.contains("1000001"), "{message}");
5753                assert!(message.contains("1000000"), "{message}");
5754                assert!(message.contains("reduce the batch size"), "{message}");
5755                assert!(datanode_rx.try_recv().is_err());
5756                assert!(flownode_rx.try_recv().is_err());
5757                assert_eq!(pending.load(Ordering::Relaxed), pending_before);
5758                assert_eq!(
5759                    crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
5760                    gauge_before_rejection
5761                );
5762                assert_eq!(
5763                    crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5764                    dropped_before
5765                );
5766            }
5767            if pending_before == 0 {
5768                crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(MAX_MIRROR_PENDING_ROWS as i64);
5769                pending.store(MAX_MIRROR_PENDING_ROWS as u64, Ordering::Relaxed);
5770            }
5771        }
5772
5773        let result = inserter
5774            .do_request(make_request(1, 0), &table_infos, &ctx)
5775            .await
5776            .unwrap();
5777        assert!(matches!(result.data, OutputData::AffectedRows(1)));
5778        assert_eq!(1, datanode_rx.try_recv().unwrap());
5779        assert!(flownode_rx.try_recv().is_err());
5780        assert_eq!(
5781            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5782            dropped_before + 1
5783        );
5784        pending.store(0, Ordering::Relaxed);
5785        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(MAX_MIRROR_PENDING_ROWS as i64);
5786        assert_eq!(
5787            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
5788            gauge_before
5789        );
5790    }
5791
5792    #[tokio::test]
5793    async fn flow_mirror_new_counts_regions_and_peer_clones() {
5794        let peer1 = flownode_peer();
5795        let peer2 = Peer {
5796            id: 2,
5797            addr: "127.0.0.1:4002".to_string(),
5798        };
5799        let cache_backend = prepare_mocked_backend().await;
5800        let cache = Arc::new(new_table_flownode_set_cache(
5801            String::new(),
5802            Cache::new(10),
5803            cache_backend,
5804        ));
5805        cache_test_flow(
5806            &cache,
5807            CreateFlow {
5808                flow_id: 1,
5809                source_table_ids: vec![1],
5810                partition_to_peer_mapping: vec![(0, peer1), (1, peer2)],
5811            },
5812        )
5813        .await;
5814        let request = |region_id| RegionInsertRequest {
5815            region_id,
5816            rows: Some(Rows {
5817                schema: vec![],
5818                rows: vec![api::v1::Row { values: vec![] }; 3],
5819            }),
5820            ..Default::default()
5821        };
5822        let requests = [
5823            request(RegionId::new(1, 0).as_u64()),
5824            request(RegionId::new(1, 1).as_u64()),
5825        ];
5826        let task = FlowMirrorTask::new(&cache, requests.iter()).await.unwrap();
5827        assert_eq!(12, task.pending_rows());
5828        assert_eq!(2, task.requests.len());
5829        for mirrored in task.requests.values() {
5830            assert_eq!(mirrored.requests.as_slice(), requests.as_slice());
5831        }
5832    }
5833
5834    #[tokio::test]
5835    async fn flow_mirror_bounds_and_deduplicates_cold_lookups() {
5836        let (started, mut loads) = tokio::sync::mpsc::unbounded_channel();
5837        let cache = Arc::new(common_meta::cache::CacheContainer::new(
5838            "test".into(),
5839            Cache::new(32),
5840            Arc::new(move |&id| {
5841                let (resume, gate) = tokio::sync::oneshot::channel();
5842                started.send((id, resume)).unwrap();
5843                Box::pin(async move {
5844                    gate.await.unwrap();
5845                    Ok(Some(Default::default()))
5846                })
5847            }),
5848            common_meta::instruction::CacheIdent::table_id_key,
5849        ));
5850        let requests: Vec<_> = (1..=12)
5851            .flat_map(|id| {
5852                (0..2).map(move |region| RegionInsertRequest {
5853                    region_id: RegionId::new(id, region).as_u64(),
5854                    ..Default::default()
5855                })
5856            })
5857            .collect();
5858        let mut task = Box::pin(FlowMirrorTask::new(&cache, requests.iter()));
5859        let mut seen = BTreeSet::new();
5860        // Every table occurs twice. Only eight distinct misses may start before one completes.
5861        for expected in [8, 4] {
5862            assert!(futures_util::poll!(&mut task).is_pending());
5863            let mut gates = Vec::new();
5864            while let Ok((id, resume)) = loads.try_recv() {
5865                assert!(seen.insert(id));
5866                gates.push(resume);
5867            }
5868            assert_eq!(gates.len(), expected);
5869            for gate in gates {
5870                gate.send(()).unwrap();
5871            }
5872        }
5873        assert!(task.await.unwrap().requests.is_empty());
5874        assert_eq!(seen.len(), 12);
5875    }
5876
5877    #[tokio::test]
5878    async fn batch_eligibility_checks_flows_and_fails_closed() {
5879        let kv_backend = prepare_mocked_backend().await;
5880        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
5881        let inserter_with_cache = |flow_cache| {
5882            Inserter::new(
5883                catalog::memory::MemoryCatalogManager::new(),
5884                partition_manager.clone(),
5885                Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5886                flow_cache,
5887                true,
5888            )
5889        };
5890
5891        // Subscribed flow source forces batching bypass.
5892        let subscribed_cache = Arc::new(new_table_flownode_set_cache(
5893            String::new(),
5894            Cache::new(32),
5895            kv_backend,
5896        ));
5897        assert!(
5898            !inserter_with_cache(subscribed_cache.clone())
5899                .any_table_has_flow(1..=4)
5900                .await
5901        );
5902        cache_test_flow(
5903            &subscribed_cache,
5904            CreateFlow {
5905                flow_id: 1,
5906                source_table_ids: vec![2],
5907                partition_to_peer_mapping: vec![(0, flownode_peer())],
5908            },
5909        )
5910        .await;
5911        assert!(
5912            inserter_with_cache(subscribed_cache)
5913                .any_table_has_flow(1..=4)
5914                .await
5915        );
5916
5917        // Lookup error fails closed and bypasses batching.
5918        let failing_cache = Arc::new(common_meta::cache::CacheContainer::new(
5919            "test_failing".into(),
5920            Cache::new(32),
5921            Arc::new(move |&id| {
5922                Box::pin(async move {
5923                    if id == 2 {
5924                        common_meta::error::UnexpectedSnafu { err_msg: "kv down" }.fail()
5925                    } else {
5926                        Ok(None)
5927                    }
5928                })
5929            }),
5930            common_meta::instruction::CacheIdent::table_id_key,
5931        ));
5932        assert!(
5933            inserter_with_cache(failing_cache)
5934                .any_table_has_flow(1..=4)
5935                .await
5936        );
5937    }
5938
5939    #[tokio::test]
5940    async fn flow_mirror_dropped_when_pending_exceeds_limit() {
5941        let _guard = lock_mirror_metrics().await;
5942        let pending = Arc::new(AtomicU64::new(MAX_MIRROR_PENDING_ROWS as u64));
5943        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
5944        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
5945        let num_rows = 100;
5946
5947        let task = FlowMirrorTask {
5948            requests: mirror_requests(&flownode_peer(), num_rows),
5949        };
5950        // The budget is already full, so nothing may be spawned for this batch.
5951        task.detach(
5952            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5953            pending.clone(),
5954            false,
5955        )
5956        .unwrap();
5957
5958        assert_eq!(
5959            num_rows as u64,
5960            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get() - dropped_before
5961        );
5962        // The dropped batch must not leak its reservation.
5963        assert_eq!(
5964            MAX_MIRROR_PENDING_ROWS as u64,
5965            pending.load(Ordering::Relaxed)
5966        );
5967        // The reservation taken before the limit check is released again, so the
5968        // gauge nets out and keeps matching the pending budget.
5969        assert_eq!(
5970            gauge_before,
5971            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
5972            "a dropped batch must not change the pending gauge"
5973        );
5974
5975        let task = FlowMirrorTask {
5976            requests: mirror_requests(&flownode_peer(), num_rows),
5977        };
5978        let error = task
5979            .detach(
5980                Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5981                pending.clone(),
5982                true,
5983            )
5984            .err()
5985            .unwrap();
5986        use common_error::ext::{ErrorExt, RetryHint};
5987        use common_error::status_code::StatusCode;
5988        assert_eq!(error.status_code(), StatusCode::RateLimited);
5989        assert_eq!(error.retry_hint(), RetryHint::Retryable);
5990        assert_eq!(
5991            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5992            dropped_before + num_rows as u64,
5993            "rejected instant rows are not successful best-effort drops"
5994        );
5995        assert_eq!(
5996            MAX_MIRROR_PENDING_ROWS as u64,
5997            pending.load(Ordering::Relaxed)
5998        );
5999        assert_eq!(
6000            gauge_before,
6001            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get()
6002        );
6003    }
6004
6005    /// A source table mapped to several flownodes clones its requests per peer,
6006    /// so the reservation must cover every clone and each spawned task must hand
6007    /// back exactly its own share; otherwise the shared budget drifts.
6008    #[tokio::test]
6009    async fn flow_mirror_reserves_and_releases_per_peer_shares() {
6010        let _guard = lock_mirror_metrics().await;
6011        let per_peer_rows = 10;
6012        let total_rows = (2 * per_peer_rows) as u64;
6013        // Exactly enough room for the whole batch, cloned rows included.
6014        let start = MAX_MIRROR_PENDING_ROWS as u64 - total_rows;
6015        let pending = Arc::new(AtomicU64::new(start));
6016        let gate = Arc::new(tokio::sync::Semaphore::new(0));
6017        let node_manager = Arc::new(MockFlownodeManager::new(GatedFlownodeHandler {
6018            gate: gate.clone(),
6019            affected_rows: per_peer_rows as u64,
6020        }));
6021
6022        let mut requests = mirror_requests(&flownode_peer(), per_peer_rows);
6023        requests.extend(mirror_requests(
6024            &Peer {
6025                id: 2,
6026                addr: "127.0.0.1:4002".to_string(),
6027            },
6028            per_peer_rows,
6029        ));
6030
6031        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6032        FlowMirrorTask { requests }
6033            .detach(node_manager, pending.clone(), false)
6034            .unwrap();
6035
6036        // Both per-peer payloads are counted, so the budget is exactly full
6037        // instead of over-reserved by the duplicated rows.
6038        assert_eq!(
6039            MAX_MIRROR_PENDING_ROWS as u64,
6040            pending.load(Ordering::Relaxed)
6041        );
6042
6043        // Let both tasks finish and check that the budget lands back on its
6044        // starting value: over-releasing a shared reservation would saturate it.
6045        // The gauge is checked too because `release_mirror_pending_rows` moves
6046        // the budget before the gauge; exiting on the budget alone could leak a
6047        // pending `gauge.sub` into the next test holding the metrics lock.
6048        gate.add_permits(2);
6049        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
6050        while pending.load(Ordering::Relaxed) != start
6051            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6052        {
6053            assert!(
6054                std::time::Instant::now() < deadline,
6055                "the mirror tasks must release exactly their own shares"
6056            );
6057            std::thread::sleep(std::time::Duration::from_millis(1));
6058        }
6059    }
6060
6061    #[tokio::test]
6062    async fn flow_mirror_fast_peer_releases_only_its_share_before_drop() {
6063        let _guard = lock_mirror_metrics().await;
6064        let peer1 = flownode_peer();
6065        let peer2 = Peer {
6066            id: 2,
6067            addr: "127.0.0.1:4002".to_string(),
6068        };
6069        let gate1 = Arc::new(tokio::sync::Semaphore::new(0));
6070        let gate2 = Arc::new(tokio::sync::Semaphore::new(0));
6071        let gates = Arc::new(std::sync::Mutex::new(HashMap::from_iter([
6072            (peer1.id, gate1.clone()),
6073            (peer2.id, gate2.clone()),
6074        ])));
6075        let (datanode_tx, _datanode_rx) = tokio::sync::mpsc::unbounded_channel();
6076        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
6077        let node_manager = Arc::new(RecordingNodeManager {
6078            datanode_dispatch: datanode_tx,
6079            flownode_dispatch: flownode_tx,
6080            gates,
6081            fail_flownode: false,
6082        });
6083        let pending = Arc::new(AtomicU64::new(MAX_MIRROR_PENDING_ROWS as u64 - 20));
6084        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6085        let mut requests = mirror_requests(&peer1, 10);
6086        requests.extend(mirror_requests(&peer2, 10));
6087        let task = FlowMirrorTask { requests };
6088        task.detach(node_manager.clone(), pending.clone(), false)
6089            .unwrap();
6090        let (first, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6091            .await
6092            .unwrap()
6093            .unwrap();
6094        let (second, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6095            .await
6096            .unwrap()
6097            .unwrap();
6098        assert_ne!(first.id, second.id);
6099        let fast_gate = if first.id == peer1.id {
6100            gate1.clone()
6101        } else {
6102            gate2.clone()
6103        };
6104        let slow_gate = if first.id == peer1.id {
6105            gate2.clone()
6106        } else {
6107            gate1.clone()
6108        };
6109        fast_gate.add_permits(1);
6110        let deadline = std::time::Instant::now() + Duration::from_secs(10);
6111        while pending.load(Ordering::Relaxed) != MAX_MIRROR_PENDING_ROWS as u64 - 10 {
6112            assert!(
6113                std::time::Instant::now() < deadline,
6114                "fast peer did not release"
6115            );
6116            std::thread::sleep(Duration::from_millis(1));
6117        }
6118        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
6119        FlowMirrorTask {
6120            requests: mirror_requests(&peer1, 11),
6121        }
6122        .detach(node_manager, pending.clone(), false)
6123        .unwrap();
6124        assert_eq!(
6125            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
6126            dropped_before + 11
6127        );
6128        assert!(flownode_rx.try_recv().is_err());
6129        slow_gate.add_permits(1);
6130        while pending.load(Ordering::Relaxed) != MAX_MIRROR_PENDING_ROWS as u64 - 20
6131            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6132        {
6133            assert!(
6134                std::time::Instant::now() < deadline,
6135                "slow peer did not release"
6136            );
6137            std::thread::sleep(Duration::from_millis(1));
6138        }
6139    }
6140
6141    #[tokio::test]
6142    async fn flow_mirror_failure_releases_budget_and_gauge() {
6143        let _guard = lock_mirror_metrics().await;
6144        let (datanode_tx, _datanode_rx) = tokio::sync::mpsc::unbounded_channel();
6145        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
6146        let node_manager = Arc::new(RecordingNodeManager {
6147            datanode_dispatch: datanode_tx,
6148            flownode_dispatch: flownode_tx,
6149            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
6150            fail_flownode: true,
6151        });
6152        let pending = Arc::new(AtomicU64::new(0));
6153        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6154        FlowMirrorTask {
6155            requests: mirror_requests(&flownode_peer(), 5),
6156        }
6157        .detach(node_manager, pending.clone(), false)
6158        .unwrap();
6159        let (peer, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6160            .await
6161            .unwrap()
6162            .unwrap();
6163        assert_eq!(peer.id, flownode_peer().id);
6164        let deadline = std::time::Instant::now() + Duration::from_secs(10);
6165        while pending.load(Ordering::Relaxed) != 0
6166            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6167        {
6168            assert!(
6169                std::time::Instant::now() < deadline,
6170                "failed task leaked reservation"
6171            );
6172            std::thread::sleep(Duration::from_millis(1));
6173        }
6174    }
6175
6176    #[tokio::test]
6177    async fn flow_mirror_pending_counter_consistent() {
6178        let _guard = lock_mirror_metrics().await;
6179        let pending = Arc::new(AtomicU64::new(0));
6180        let gate = Arc::new(tokio::sync::Semaphore::new(0));
6181        let node_manager = Arc::new(MockFlownodeManager::new(GatedFlownodeHandler {
6182            gate: gate.clone(),
6183            affected_rows: 7,
6184        }));
6185
6186        // A batch without rows short-circuits and leaves the budget untouched.
6187        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6188        FlowMirrorTask {
6189            requests: HashMap::new(),
6190        }
6191        .detach(node_manager.clone(), pending.clone(), false)
6192        .unwrap();
6193        assert_eq!(0, pending.load(Ordering::Relaxed));
6194        assert_eq!(
6195            gauge_before,
6196            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
6197            "an empty batch must not touch the pending gauge"
6198        );
6199
6200        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
6201        let num_rows = 7;
6202
6203        FlowMirrorTask {
6204            requests: mirror_requests(&flownode_peer(), num_rows),
6205        }
6206        .detach(node_manager, pending.clone(), false)
6207        .unwrap();
6208
6209        // The spawned task is still waiting on the gated flownode, so the
6210        // reservation made by `detach` is the value observable here.
6211        assert_eq!(num_rows as u64, pending.load(Ordering::Relaxed));
6212        assert_eq!(
6213            num_rows as i64,
6214            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() - gauge_before,
6215            "the pending gauge must track the pending rows"
6216        );
6217        assert_eq!(
6218            dropped_before,
6219            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
6220            "a batch within the limit must not be counted as dropped"
6221        );
6222
6223        // Release the in-flight task and wait for it to hand its reservation
6224        // back, so no task is left holding the shared metrics after this test.
6225        gate.add_permits(1);
6226        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
6227        while pending.load(Ordering::Relaxed) != 0
6228            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6229        {
6230            assert!(
6231                std::time::Instant::now() < deadline,
6232                "the mirror task did not release its pending reservation"
6233            );
6234            std::thread::sleep(std::time::Duration::from_millis(1));
6235        }
6236    }
6237
6238    #[test]
6239    fn mirror_logs_are_rate_limited() {
6240        let log = Arc::new(MirrorLog::new());
6241        assert_eq!(Some(1), log.claim_report(1_000));
6242        assert_eq!(None, log.claim_report(1_500));
6243        assert_eq!(None, log.claim_report(10_999));
6244        assert_eq!(Some(3), log.claim_report(11_000));
6245        assert_eq!(None, log.claim_report(11_001));
6246        assert_eq!(Some(2), log.claim_report(21_000));
6247
6248        let concurrent = Arc::new(MirrorLog::new());
6249        assert_eq!(Some(1), concurrent.claim_report(50_000));
6250        let barrier = Arc::new(std::sync::Barrier::new(8));
6251        let threads = (0..8)
6252            .map(|_| {
6253                let log = concurrent.clone();
6254                let barrier = barrier.clone();
6255                std::thread::spawn(move || {
6256                    barrier.wait();
6257                    log.claim_report(60_000)
6258                })
6259            })
6260            .collect::<Vec<_>>();
6261        let winners = threads
6262            .into_iter()
6263            .filter_map(|thread| thread.join().unwrap())
6264            .collect::<Vec<_>>();
6265        assert_eq!(winners.len(), 1);
6266        assert!(concurrent.events.swap(0, Ordering::Relaxed) + winners[0] == 8);
6267    }
6268
6269    async fn recording_inserter(
6270        kv_backend: &common_meta::kv_backend::KvBackendRef,
6271    ) -> (
6272        Inserter,
6273        mpsc::UnboundedReceiver<usize>,
6274        mpsc::UnboundedReceiver<(Peer, RegionInsertRequests)>,
6275    ) {
6276        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
6277        let (datanode_tx, datanode_rx) = mpsc::unbounded_channel();
6278        let (flownode_tx, flownode_rx) = mpsc::unbounded_channel();
6279        let node_manager = Arc::new(RecordingNodeManager {
6280            datanode_dispatch: datanode_tx,
6281            flownode_dispatch: flownode_tx,
6282            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
6283            fail_flownode: false,
6284        });
6285        let inserter = Inserter::new(
6286            catalog::memory::MemoryCatalogManager::new(),
6287            partition_manager,
6288            node_manager,
6289            Arc::new(new_table_flownode_set_cache(
6290                String::new(),
6291                Cache::new(10),
6292                kv_backend.clone(),
6293            )),
6294            true,
6295        );
6296        cache_test_flow(
6297            &inserter.table_flownode_set_cache,
6298            CreateFlow {
6299                flow_id: 1,
6300                source_table_ids: vec![10, 11],
6301                partition_to_peer_mapping: vec![(0, flownode_peer())],
6302            },
6303        )
6304        .await;
6305        (inserter, datanode_rx, flownode_rx)
6306    }
6307
6308    #[tokio::test]
6309    async fn test_mixed_sparse_write_preserves_instant_flow_default() {
6310        use api::v1::helper::tag_column_schema;
6311        use common_time::ttl::TimeToLive;
6312        use datatypes::schema::{ColumnDefaultConstraint, Schema};
6313
6314        let _guard = lock_mirror_metrics().await;
6315        let kv_backend = prepare_mocked_backend().await;
6316        let (inserter, mut datanode_rx, mut flownode_rx) = recording_inserter(&kv_backend).await;
6317        let mut stored = new_test_table_info(10, "stored", std::iter::empty());
6318        stored.meta.engine = default_engine().into();
6319        stored.meta.schema = Arc::new(Schema::new(vec![
6320            ColumnSchema::new(
6321                DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
6322                ConcreteDataType::uint32_datatype(),
6323                false,
6324            ),
6325            ColumnSchema::new(
6326                DATA_SCHEMA_TSID_COLUMN_NAME,
6327                ConcreteDataType::uint64_datatype(),
6328                false,
6329            ),
6330            ColumnSchema::new(
6331                "ts",
6332                ConcreteDataType::timestamp_millisecond_datatype(),
6333                false,
6334            )
6335            .with_time_index(true)
6336            .with_default_constraint(Some(ColumnDefaultConstraint::Function("now()".into())))
6337            .unwrap(),
6338        ]));
6339        stored.meta.column_ids = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid(), 2];
6340        stored.meta.primary_key_indices = vec![0, 1];
6341        stored.meta.partition_key_indices.clear();
6342        let mut instant = stored.clone();
6343        instant.ident.table_id = 11;
6344        instant.name = "instant".into();
6345        instant.meta.options.ttl = Some(TimeToLive::Instant);
6346        stored.meta.options.extra_options.insert(
6347            store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.into(),
6348            "sparse".into(),
6349        );
6350        let mut infos = HashMap::new();
6351        let mut requests = RowInsertRequests::default();
6352        for table in [stored, instant] {
6353            register_unpartitioned_table_route(&kv_backend, &table).await;
6354            requests.inserts.push(RowInsertRequest {
6355                table_name: table.name.clone(),
6356                rows: Some(Rows {
6357                    schema: vec![
6358                        tag_column_schema(DATA_SCHEMA_TABLE_ID_COLUMN_NAME, ColumnDataType::Uint32),
6359                        tag_column_schema(DATA_SCHEMA_TSID_COLUMN_NAME, ColumnDataType::Uint64),
6360                    ],
6361                    rows: vec![Row {
6362                        values: vec![ValueData::U32Value(1).into(), ValueData::U64Value(2).into()],
6363                    }],
6364                }),
6365            });
6366            infos.insert(table.table_id(), Arc::new(table));
6367        }
6368        let output = inserter
6369            .dispatch_direct_sparse_row_inserts(
6370                requests,
6371                infos,
6372                HashSet::new(),
6373                false,
6374                &QueryContext::arc(),
6375            )
6376            .await
6377            .unwrap();
6378        assert!(matches!(output.data, OutputData::AffectedRows(1)));
6379        assert_eq!(datanode_rx.try_recv().unwrap(), 1);
6380        let (_, mirrored) = tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6381            .await
6382            .unwrap()
6383            .unwrap();
6384        let timestamps = mirrored
6385            .requests
6386            .into_iter()
6387            .map(|request| {
6388                let table_id = RegionId::from(request.region_id).table_id();
6389                let rows = request.rows.unwrap();
6390                let has_timestamp = rows.schema.iter().any(|column| column.column_name == "ts");
6391                (table_id, has_timestamp)
6392            })
6393            .collect::<BTreeMap<_, _>>();
6394        assert_eq!(timestamps, BTreeMap::from([(10, true), (11, false)]));
6395        drop(inserter);
6396        assert!(
6397            tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6398                .await
6399                .unwrap()
6400                .is_none()
6401        );
6402    }
6403
6404    #[tokio::test]
6405    async fn test_exemplar_flow_mirror_and_instant_ttl_bypass() {
6406        let _guard = lock_mirror_metrics().await;
6407        let kv_backend = prepare_mocked_backend().await;
6408        let (inserter, mut datanode_rx, mut flownode_rx) = recording_inserter(&kv_backend).await;
6409        let inserter = inserter.with_pending_rows_batcher(Some(Arc::new(UnexpectedBatcher {
6410            allow_acquire: false,
6411        })));
6412
6413        let make_exemplar_table = |id: TableId, instant: bool| {
6414            test_exemplar_table_info(
6415                id,
6416                DEFAULT_CATALOG_NAME,
6417                DEFAULT_SCHEMA_NAME,
6418                &["job"],
6419                instant,
6420            )
6421        };
6422
6423        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
6424        ctx.set_batching_enabled(true);
6425        let ctx = Arc::new(ctx);
6426        let resolved = HashMap::from_iter([("cpu".to_string(), 100)]);
6427        let batch = |tag: &str| {
6428            ExemplarBatch::try_new(vec![Exemplar {
6429                metric: "cpu".into(),
6430                series_labels: BTreeMap::from([(tag.into(), "api".into())]).into(),
6431                timestamp: 1_000,
6432                value: 1.5,
6433                labels: BTreeMap::from([("trace_id".into(), "abc".into())]),
6434            }])
6435            .unwrap()
6436        };
6437
6438        // An unreconciled destination rejects the same missing tag with and without a Flow.
6439        for id in [11, 12] {
6440            let error = inserter
6441                .execute_exemplar_write(
6442                    batch("host"),
6443                    resolved.clone(),
6444                    make_exemplar_table(id, true),
6445                    true,
6446                    ctx.clone(),
6447                )
6448                .await
6449                .unwrap_err();
6450            assert!(error.to_string().contains("is missing tag host"), "{error}");
6451        }
6452        assert!(flownode_rx.try_recv().is_err());
6453
6454        // Normal subscribed exemplar table bypasses batcher, mirrors to flownode, and writes datanode.
6455        let normal_dest = make_exemplar_table(10, false);
6456        register_unpartitioned_table_route(&kv_backend, &normal_dest).await;
6457        let output = inserter
6458            .execute_exemplar_write(
6459                batch("job"),
6460                resolved.clone(),
6461                normal_dest,
6462                false,
6463                ctx.clone(),
6464            )
6465            .await
6466            .unwrap();
6467        assert!(matches!(output.data, OutputData::AffectedRows(1)));
6468        assert_eq!(datanode_rx.try_recv().unwrap(), 1);
6469        tokio::time::timeout(std::time::Duration::from_secs(5), flownode_rx.recv())
6470            .await
6471            .unwrap()
6472            .unwrap();
6473
6474        // Instant-TTL exemplar table mirrors to flownode and skips datanode storage.
6475        let instant_dest = make_exemplar_table(11, true);
6476        register_unpartitioned_table_route(&kv_backend, &instant_dest).await;
6477        let output = inserter
6478            .execute_exemplar_write(batch("job"), resolved, instant_dest, true, ctx)
6479            .await
6480            .unwrap();
6481        assert!(matches!(output.data, OutputData::AffectedRows(0)));
6482        assert!(datanode_rx.try_recv().is_err());
6483        tokio::time::timeout(std::time::Duration::from_secs(5), flownode_rx.recv())
6484            .await
6485            .unwrap()
6486            .unwrap();
6487
6488        drop(inserter);
6489        assert!(
6490            tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6491                .await
6492                .unwrap()
6493                .is_none()
6494        );
6495    }
6496}