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 from the first request for it,
1984    ///   then check every request for it against the table that exists after the CREATE, which a
1985    ///   concurrent writer may have created with other columns
1986    /// - if table exist, check if schema matches. If any new column found, alter table by inferred `AlterExpr`
1987    ///
1988    /// Each altered table gets one `AlterExpr` with the new columns of all its requests.
1989    ///
1990    /// Returns a mapping from table name to table id, where table name is the table name involved in the requests.
1991    /// This mapping is used in the conversion of RowToRegion.
1992    ///
1993    /// `accommodate_existing_schema` is used to determine if the existing schema should override the new schema.
1994    /// It only works for TIME_INDEX and single VALUE columns. This is for the case where the user creates a table with
1995    /// custom schema, and then inserts data with endpoints that have default schema setting, like prometheus
1996    /// remote write. This will modify the `RowInsertRequests` in place.
1997    /// `is_single_value` indicates whether the default schema only contains single value column so we can accommodate it.
1998    ///
1999    /// `align_time_index_unit` supplies the selected physical table's time-index
2000    /// unit for new logical tables. Existing logical targets always use their
2001    /// own unit, even when this argument is `None` because no new target needs
2002    /// the selected backing table. Rows for a new table keep their unit until
2003    /// the CREATE returns, and are then converted once to the unit of the table
2004    /// that exists.
2005    #[allow(clippy::too_many_arguments)]
2006    async fn create_or_alter_tables_on_demand(
2007        &self,
2008        requests: &mut RowInsertRequests,
2009        ctx: &QueryContextRef,
2010        auto_create_table_type: AutoCreateTableType,
2011        statement_executor: &StatementExecutor,
2012        accommodate_existing_schema: bool,
2013        is_single_value: bool,
2014        align_time_index_unit: Option<TimeUnit>,
2015    ) -> Result<CreateAlterTableResult> {
2016        let is_exemplar = matches!(&auto_create_table_type, AutoCreateTableType::Exemplar);
2017        let _timer = crate::metrics::CREATE_ALTER_ON_DEMAND
2018            .with_label_values(&[auto_create_table_type.as_str()])
2019            .start_timer();
2020        let catalog = ctx.current_catalog();
2021        let schema = ctx.current_schema();
2022
2023        let auto_create_disabled_reason = self.auto_create_disabled_reason(ctx)?;
2024        // Enabled batches permit every table, so only disabled batches need a whitelist scan.
2025        let has_auto_create_exempt_table = auto_create_disabled_reason.is_some()
2026            && requests
2027                .inserts
2028                .iter()
2029                .any(|req| Self::is_auto_create_exempt_private_table(&schema, &req.table_name));
2030        let mut table_infos = HashMap::new();
2031        // Without exempt tables, verify existing tables and reject missing ones without inferring schemas.
2032        if let Some(disabled_reason) = auto_create_disabled_reason
2033            && !has_auto_create_exempt_table
2034        {
2035            let mut instant_table_ids = HashSet::new();
2036            for req in &mut requests.inserts {
2037                let table = match self.get_table(catalog, &schema, &req.table_name).await? {
2038                    Some(table) => table,
2039                    // System-defined table: created canonically by the system,
2040                    // so the auto-create config/hint does not apply.
2041                    None if is_ddl_reserved_table(&schema, &req.table_name) => {
2042                        statement_executor
2043                            .create_declared_relationships_table(catalog, ctx.clone())
2044                            .await?
2045                    }
2046                    None => {
2047                        return InvalidInsertRequestSnafu {
2048                            reason: format!(
2049                                "Table `{}` does not exist, and {}",
2050                                req.table_name, disabled_reason
2051                            ),
2052                        }
2053                        .fail();
2054                    }
2055                };
2056                // Existing metric and exemplar destinations keep their time index unit.
2057                if matches!(
2058                    auto_create_table_type,
2059                    AutoCreateTableType::Logical(_) | AutoCreateTableType::Exemplar
2060                ) && let Some(rows) = req.rows.as_mut()
2061                    && let Some(target_unit) = table_time_index_unit(&table)
2062                {
2063                    convert_rows_time_unit(rows, target_unit)?;
2064                }
2065                let table_info = table.table_info();
2066                if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) {
2067                    validate_exemplar_table(&table_info)?;
2068                }
2069                if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) {
2070                    validate_trace_table_model(&table_info, ctx)?;
2071                }
2072                if table_info.is_ttl_instant_table() {
2073                    instant_table_ids.insert(table_info.table_id());
2074                }
2075                table_infos.insert(table_info.table_id(), table.table_info());
2076            }
2077            let ret = CreateAlterTableResult {
2078                instant_table_ids,
2079                table_infos,
2080            };
2081            return Ok(ret);
2082        }
2083
2084        let mut create_tables = vec![];
2085        let mut alter_tables = vec![];
2086        let mut need_refresh_table_infos = HashSet::new();
2087        let mut instant_table_ids = HashSet::new();
2088        let mut per_table_semantics: Option<Option<PerTableSemanticIndex>> = None;
2089        // Requests whose tables are created below, by index. They are checked
2090        // against the table that exists after the CREATE.
2091        let mut created_table_requests = vec![];
2092
2093        for (index, req) in requests.inserts.iter_mut().enumerate() {
2094            // Mixed batches need a per-table decision so an exempt table cannot authorize others.
2095            let auto_create_allowed = auto_create_disabled_reason.is_none()
2096                || Self::is_auto_create_exempt_private_table(&schema, &req.table_name);
2097            match self.get_table(catalog, &schema, &req.table_name).await? {
2098                Some(table) => {
2099                    let table_info = table.table_info();
2100                    if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) {
2101                        validate_exemplar_table(&table_info)?;
2102                    }
2103                    if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) {
2104                        validate_trace_table_model(&table_info, ctx)?;
2105                    }
2106                    if table_info.is_ttl_instant_table() {
2107                        instant_table_ids.insert(table_info.table_id());
2108                    }
2109                    // Metric path: an existing destination table keeps its
2110                    // own time index unit (it may be bound to another
2111                    // physical table than the one selected by this request).
2112                    if matches!(auto_create_table_type, AutoCreateTableType::Logical(_))
2113                        && let Some(rows) = req.rows.as_mut()
2114                        && let Some(target_unit) = table_time_index_unit(&table)
2115                    {
2116                        convert_rows_time_unit(rows, target_unit)?;
2117                    }
2118                    if auto_create_allowed
2119                        && let Some(alter_expr) = self.get_alter_table_expr_on_demand(
2120                            req,
2121                            &table,
2122                            ctx,
2123                            accommodate_existing_schema,
2124                            is_single_value,
2125                            auto_create_table_type.alter_existing(),
2126                        )?
2127                    {
2128                        merge_alter_table_expr(&mut alter_tables, alter_expr);
2129                        need_refresh_table_infos.insert((
2130                            catalog.to_string(),
2131                            schema.clone(),
2132                            req.table_name.clone(),
2133                        ));
2134                    } else {
2135                        table_infos.insert(table_info.table_id(), table.table_info());
2136                    }
2137                }
2138                // A DDL-reserved table's definition never derives from the
2139                // write request; the system creates it canonically, below the
2140                // user-DDL guard that rejects the generic create path.
2141                None if is_ddl_reserved_table(&schema, &req.table_name) => {
2142                    let table = statement_executor
2143                        .create_declared_relationships_table(catalog, ctx.clone())
2144                        .await?;
2145                    let table_info = table.table_info();
2146                    if table_info.is_ttl_instant_table() {
2147                        instant_table_ids.insert(table_info.table_id());
2148                    }
2149                    table_infos.insert(table_info.table_id(), table_info);
2150                }
2151                None if !auto_create_allowed
2152                    && let Some(disabled_reason) = auto_create_disabled_reason =>
2153                {
2154                    return InvalidInsertRequestSnafu {
2155                        reason: format!(
2156                            "Table `{}` does not exist, and {}",
2157                            req.table_name, disabled_reason,
2158                        ),
2159                    }
2160                    .fail();
2161                }
2162                None => {
2163                    // The first request for a missing table defines its CREATE.
2164                    if !create_tables
2165                        .iter()
2166                        .any(|expr: &CreateTableExpr| expr.table_name == req.table_name)
2167                    {
2168                        let semantic_index = per_table_semantics
2169                            .get_or_insert_with(|| parse_per_table_semantic_index(ctx))
2170                            .as_ref();
2171                        let mut create_expr = self.get_create_table_expr_on_demand(
2172                            req,
2173                            &auto_create_table_type,
2174                            ctx,
2175                            semantic_index,
2176                        )?;
2177                        // Metric path: a new table uses the selected physical
2178                        // table's unit. The rows keep their own unit until the
2179                        // table that exists after the CREATE is known.
2180                        if let Some(physical_unit) = align_time_index_unit {
2181                            set_time_index_unit(&mut create_expr, physical_unit);
2182                        }
2183                        create_tables.push(create_expr);
2184                    }
2185                    created_table_requests.push(index);
2186                }
2187            }
2188        }
2189
2190        let mut created_tables = HashMap::with_capacity(create_tables.len());
2191        match auto_create_table_type {
2192            AutoCreateTableType::Logical(_) => {
2193                if !create_tables.is_empty() {
2194                    // Creates logical tables in batch. They are read back from the
2195                    // catalog, so a table that a concurrent writer created comes
2196                    // with its actual schema.
2197                    let tables = self
2198                        .create_logical_tables(create_tables, ctx, statement_executor)
2199                        .await?;
2200                    for table in tables {
2201                        created_tables.insert(table.table_info().name.clone(), table);
2202                    }
2203                }
2204            }
2205            AutoCreateTableType::Physical
2206            | AutoCreateTableType::Exemplar
2207            | AutoCreateTableType::Log
2208            | AutoCreateTableType::LastNonNull => {
2209                // note that auto create table shouldn't be ttl instant table
2210                // for it's a very unexpected behavior and should be set by user explicitly
2211                for create_table in create_tables {
2212                    let table = self
2213                        .create_physical_table(create_table, None, ctx, statement_executor)
2214                        .await?;
2215                    if is_exemplar {
2216                        validate_exemplar_table(&table.table_info())?;
2217                    }
2218                    created_tables.insert(table.table_info().name.clone(), table);
2219                }
2220            }
2221
2222            AutoCreateTableType::Trace { .. } => {
2223                let trace_table_name = ctx
2224                    .extension(TRACE_TABLE_NAME_SESSION_KEY)
2225                    .unwrap_or(TRACE_TABLE_NAME);
2226
2227                let trace_table_partitions = if let Some(trace_table_partitions) =
2228                    ctx.extension(TRACE_TABLE_PARTITIONS_HINT_KEY)
2229                {
2230                    let p = trace_table_partitions.parse::<u32>().map_err(|_| {
2231                        InvalidInsertRequestSnafu {
2232                            reason: format!(
2233                                "Failed to parse trace_table_partitions: {}",
2234                                trace_table_partitions
2235                            ),
2236                        }
2237                        .build()
2238                    })?;
2239                    Some(p)
2240                } else {
2241                    None
2242                };
2243
2244                // note that auto create table shouldn't be ttl instant table
2245                // for it's a very unexpected behavior and should be set by user explicitly
2246                for mut create_table in create_tables {
2247                    if create_table.table_name == trace_services_table_name(trace_table_name)
2248                        || create_table.table_name == trace_operations_table_name(trace_table_name)
2249                    {
2250                        // Disable append mode for auxiliary tables (services/operations) since they require upsert behavior.
2251                        create_table
2252                            .table_options
2253                            .insert(APPEND_MODE_KEY.to_string(), "false".to_string());
2254                        // Remove `ttl` key from table options if it exists
2255                        create_table.table_options.remove(TTL_KEY);
2256
2257                        let table = self
2258                            .create_physical_table(create_table, None, ctx, statement_executor)
2259                            .await?;
2260                        created_tables.insert(table.table_info().name.clone(), table);
2261                    } else {
2262                        // prebuilt partition rules for uuid data: see the function
2263                        // for more information
2264                        let partitions = if matches!(trace_table_partitions, Some(0) | Some(1)) {
2265                            // disable partitions
2266                            None
2267                        } else {
2268                            let p = partition_rule_for_hexstring(
2269                                TRACE_ID_COLUMN,
2270                                trace_table_partitions,
2271                            )
2272                            .context(CreatePartitionRulesSnafu)?;
2273                            Some(p)
2274                        };
2275
2276                        // add skip index to
2277                        // - trace_id: when searching by trace id
2278                        // - parent_span_id: when searching root span
2279                        // - span_name: when searching certain types of span
2280                        let index_columns =
2281                            [TRACE_ID_COLUMN, PARENT_SPAN_ID_COLUMN, SERVICE_NAME_COLUMN];
2282                        for index_column in index_columns {
2283                            if let Some(col) = create_table
2284                                .column_defs
2285                                .iter_mut()
2286                                .find(|c| c.name == index_column)
2287                            {
2288                                col.options =
2289                                    options_from_skipping(&SkippingIndexOptions::default())
2290                                        .context(ColumnOptionsSnafu)?;
2291                            } else {
2292                                warn!(
2293                                    "Column {} not found when creating index for trace table: {}.",
2294                                    index_column, create_table.table_name
2295                                );
2296                            }
2297                        }
2298
2299                        // Span ids and end timestamps rarely repeat within an SST, so a
2300                        // dictionary costs more than it saves. Small span id pages let
2301                        // lookups by trace id decode only the pages holding matched rows.
2302                        let id_compression = CompressionOptions {
2303                            encoding: Some(ColumnEncoding::Plain),
2304                            page_size: Some(ReadableSize::kb(64)),
2305                            ..Default::default()
2306                        };
2307                        let compressed_columns = [
2308                            (SPAN_ID_COLUMN, id_compression),
2309                            (PARENT_SPAN_ID_COLUMN, id_compression),
2310                            (
2311                                TIMESTAMP_END_COLUMN,
2312                                CompressionOptions {
2313                                    encoding: Some(ColumnEncoding::DeltaBinaryPacked),
2314                                    ..Default::default()
2315                                },
2316                            ),
2317                        ];
2318                        for (name, compression) in compressed_columns {
2319                            if let Some(col) =
2320                                create_table.column_defs.iter_mut().find(|c| c.name == name)
2321                            {
2322                                let compression = options_from_compression(&compression)
2323                                    .context(ColumnOptionsSnafu)?;
2324                                col.options
2325                                    .get_or_insert_with(Default::default)
2326                                    .options
2327                                    .extend(compression.options);
2328                            }
2329                        }
2330
2331                        // use table_options to mark table model version
2332                        create_table.table_options.insert(
2333                            TABLE_DATA_MODEL.to_string(),
2334                            ctx.extension(SEMANTIC_PIPELINE)
2335                                .unwrap_or(TABLE_DATA_MODEL_TRACE_V1)
2336                                .to_string(),
2337                        );
2338
2339                        let table = self
2340                            .create_physical_table(
2341                                create_table,
2342                                partitions,
2343                                ctx,
2344                                statement_executor,
2345                            )
2346                            .await?;
2347                        created_tables.insert(table.table_info().name.clone(), table);
2348                    }
2349                }
2350            }
2351        }
2352
2353        for index in created_table_requests {
2354            let req = &mut requests.inserts[index];
2355            let table = created_tables
2356                .get(&req.table_name)
2357                .context(TableNotFoundSnafu {
2358                    table_name: &req.table_name,
2359                })?;
2360            // Metric path: convert the rows once, to the unit of the table that
2361            // exists after the CREATE.
2362            if matches!(auto_create_table_type, AutoCreateTableType::Logical(_))
2363                && let Some(rows) = req.rows.as_mut()
2364                && let Some(target_unit) = table_time_index_unit(table)
2365            {
2366                convert_rows_time_unit(rows, target_unit)?;
2367            }
2368            if let Some(alter_expr) = self.get_alter_table_expr_on_demand(
2369                req,
2370                table,
2371                ctx,
2372                accommodate_existing_schema,
2373                is_single_value,
2374                auto_create_table_type.alter_existing(),
2375            )? {
2376                merge_alter_table_expr(&mut alter_tables, alter_expr);
2377                need_refresh_table_infos.insert((
2378                    catalog.to_string(),
2379                    schema.clone(),
2380                    req.table_name.clone(),
2381                ));
2382            }
2383        }
2384        for table in created_tables.into_values() {
2385            let table_info = table.table_info();
2386            if table_info.is_ttl_instant_table() {
2387                instant_table_ids.insert(table_info.table_id());
2388            }
2389            table_infos.insert(table_info.table_id(), table_info);
2390        }
2391
2392        if !alter_tables.is_empty() {
2393            if matches!(auto_create_table_type, AutoCreateTableType::Logical(_)) {
2394                // Alter logical tables in batch.
2395                statement_executor
2396                    .alter_logical_tables(alter_tables, ctx.clone(), TriggerReason::AutoAlter)
2397                    .await?;
2398            } else {
2399                for alter_expr in alter_tables {
2400                    statement_executor
2401                        .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
2402                        .await?;
2403                }
2404            }
2405        }
2406
2407        // refresh table infos for altered tables
2408        for (catalog, schema, table_name) in need_refresh_table_infos {
2409            let table = self
2410                .get_table(&catalog, &schema, &table_name)
2411                .await?
2412                .context(TableNotFoundSnafu {
2413                    table_name: common_catalog::format_full_table_name(
2414                        &catalog,
2415                        &schema,
2416                        &table_name,
2417                    ),
2418                })?;
2419            let table_info = table.table_info();
2420            if is_exemplar {
2421                validate_exemplar_table(&table_info)?;
2422            }
2423            table_infos.insert(table_info.table_id(), table.table_info());
2424        }
2425
2426        if is_exemplar {
2427            for info in table_infos.values() {
2428                if let Some(unit) = info
2429                    .meta
2430                    .schema
2431                    .timestamp_column()
2432                    .and_then(|column| column.data_type.as_timestamp())
2433                    .map(|timestamp| timestamp.unit())
2434                {
2435                    for request in &mut requests.inserts {
2436                        if request.table_name == info.name
2437                            && let Some(rows) = request.rows.as_mut()
2438                        {
2439                            convert_rows_time_unit(rows, unit)?;
2440                        }
2441                    }
2442                }
2443            }
2444        }
2445
2446        Ok(CreateAlterTableResult {
2447            instant_table_ids,
2448            table_infos,
2449        })
2450    }
2451
2452    async fn create_physical_table_on_demand(
2453        &self,
2454        ctx: &QueryContextRef,
2455        physical_table: String,
2456        statement_executor: &StatementExecutor,
2457    ) -> Result<TableRef> {
2458        let catalog_name = ctx.current_catalog();
2459        let schema_name = ctx.current_schema();
2460
2461        // check if exist
2462        if let Some(table) = self
2463            .get_table(catalog_name, &schema_name, &physical_table)
2464            .await?
2465        {
2466            return Ok(table);
2467        }
2468
2469        // Gate here too, otherwise a disabled switch would still leak the physical table.
2470        if let Some(disabled_reason) = self.auto_create_disabled_reason(ctx)? {
2471            return InvalidInsertRequestSnafu {
2472                reason: format!(
2473                    "Physical table `{physical_table}` does not exist, and {disabled_reason}"
2474                ),
2475            }
2476            .fail();
2477        }
2478
2479        let table_reference = TableReference::full(catalog_name, &schema_name, &physical_table);
2480        debug!("Ensuring physical metric table `{table_reference}` exists for insert");
2481
2482        // schema with timestamp and field column
2483        let default_schema = vec![
2484            ColumnSchema {
2485                column_name: greptime_timestamp().to_string(),
2486                datatype: api::helper::timestamp_datatype(
2487                    self.auto_create_physical_table_timestamp_unit,
2488                ) as _,
2489                semantic_type: SemanticType::Timestamp as _,
2490                datatype_extension: None,
2491                options: None,
2492            },
2493            ColumnSchema {
2494                column_name: greptime_value().to_string(),
2495                datatype: ColumnDataType::Float64 as _,
2496                semantic_type: SemanticType::Field as _,
2497                datatype_extension: None,
2498                options: None,
2499            },
2500        ];
2501        let create_table_expr =
2502            &mut build_create_table_expr(&table_reference, &default_schema, default_engine())?;
2503
2504        create_table_expr.engine = METRIC_ENGINE_NAME.to_string();
2505        create_table_expr
2506            .table_options
2507            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), "true".to_string());
2508        apply_retention_ttl_hint(&mut create_table_expr.table_options, ctx);
2509
2510        // create physical table
2511        let res = statement_executor
2512            .create_table_inner(
2513                create_table_expr,
2514                None,
2515                ctx.clone(),
2516                TriggerReason::AutoCreate,
2517            )
2518            .await;
2519
2520        match res {
2521            Ok(table) => Ok(table),
2522            Err(err) => {
2523                error!(err; "Failed to create table {table_reference}");
2524                Err(err)
2525            }
2526        }
2527    }
2528
2529    async fn get_table(
2530        &self,
2531        catalog: &str,
2532        schema: &str,
2533        table: &str,
2534    ) -> Result<Option<TableRef>> {
2535        self.catalog_manager
2536            .table(catalog, schema, table, None)
2537            .await
2538            .context(CatalogSnafu)
2539    }
2540
2541    fn get_create_table_expr_on_demand(
2542        &self,
2543        req: &RowInsertRequest,
2544        create_type: &AutoCreateTableType,
2545        ctx: &QueryContextRef,
2546        semantic_index: Option<&PerTableSemanticIndex>,
2547    ) -> Result<CreateTableExpr> {
2548        let schema = ctx.current_schema();
2549        let mut table_options = std::collections::HashMap::with_capacity(4);
2550        fill_table_options_for_create(&mut table_options, create_type, ctx);
2551        if !matches!(create_type, AutoCreateTableType::Exemplar) {
2552            apply_per_table_semantic_options(
2553                &mut table_options,
2554                semantic_index,
2555                ctx.current_schema().as_str(),
2556                &req.table_name,
2557            );
2558        }
2559
2560        let engine_name = if let AutoCreateTableType::Logical(_) = create_type {
2561            // engine should be metric engine when creating logical tables.
2562            METRIC_ENGINE_NAME
2563        } else {
2564            default_engine()
2565        };
2566
2567        let table_ref = TableReference::full(ctx.current_catalog(), &schema, &req.table_name);
2568        // SAFETY: `req.rows` is guaranteed to be `Some` by `handle_row_inserts_with_create_type()`.
2569        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
2570        let mut create_table_expr =
2571            build_create_table_expr(&table_ref, request_schema, engine_name)?;
2572
2573        if matches!(create_type, AutoCreateTableType::Exemplar) {
2574            // Preserve the stored schema order without shifting every incoming row.
2575            create_table_expr
2576                .column_defs
2577                .sort_by_key(|column| column.name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
2578            create_table_expr
2579                .primary_keys
2580                .sort_by_key(|name| name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
2581            for column in &mut create_table_expr.column_defs {
2582                if [
2583                    DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
2584                    DATA_SCHEMA_TSID_COLUMN_NAME,
2585                ]
2586                .contains(&column.name.as_str())
2587                {
2588                    column.is_nullable = false;
2589                }
2590            }
2591        }
2592
2593        // extension set by the Splunk HEC handler for identity path
2594        if ctx.extension(SPLUNK_PK_METADATA_ORDER_KEY).is_some() {
2595            reorder_splunk_primary_keys(&mut create_table_expr.primary_keys);
2596        }
2597
2598        debug!("Ensuring table `{table_ref}` exists for insert");
2599        create_table_expr.table_options.extend(table_options);
2600        Ok(create_table_expr)
2601    }
2602
2603    /// Returns an alter table expression if it finds new columns in the request.
2604    /// When `accommodate_existing_schema` is false, it always adds columns if not exist.
2605    /// When `accommodate_existing_schema` is true, it may modify the input `req` to
2606    /// accommodate it with existing schema. See [`create_or_alter_tables_on_demand`](Self::create_or_alter_tables_on_demand)
2607    /// for more details.
2608    /// When `is_single_value` is true, it also rejects native-histogram/float kind
2609    /// changes even when no columns need adding.
2610    /// When both options are true, it considers fields when modifying the input `req`.
2611    fn get_alter_table_expr_on_demand(
2612        &self,
2613        req: &mut RowInsertRequest,
2614        table: &TableRef,
2615        ctx: &QueryContextRef,
2616        accommodate_existing_schema: bool,
2617        is_single_value: bool,
2618        alter_existing: bool,
2619    ) -> Result<Option<AlterTableExpr>> {
2620        if !alter_existing {
2621            return Ok(None);
2622        }
2623
2624        let catalog_name = ctx.current_catalog();
2625        let schema_name = ctx.current_schema();
2626        let table_name = table.table_info().name.clone();
2627
2628        // Never auto-alter a system-defined table to fit a write; a request
2629        // with unknown columns fails instead.
2630        if is_ddl_reserved_table(&schema_name, &table_name) {
2631            return Ok(None);
2632        }
2633
2634        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
2635        let request_field_count = request_schema
2636            .iter()
2637            .filter(|col| col.semantic_type == SemanticType::Field as i32)
2638            .count();
2639        if is_single_value {
2640            let request_is_native_histogram = request_is_native_histogram(request_schema);
2641            let table_is_native_histogram = table_is_native_histogram(table);
2642            ensure!(
2643                request_is_native_histogram == table_is_native_histogram,
2644                InvalidInsertRequestSnafu {
2645                    reason: format!(
2646                        "Table `{table_name}` cannot mix native histogram and float sample fields"
2647                    ),
2648                }
2649            );
2650        }
2651
2652        let column_exprs = ColumnExpr::from_column_schemas(request_schema);
2653        let add_columns = expr_helper::extract_add_columns_expr(&table.schema(), column_exprs)?;
2654        let Some(mut add_columns) = add_columns else {
2655            return Ok(None);
2656        };
2657
2658        // If accommodate_existing_schema is true, update request schema for Timestamp/Field columns
2659        if accommodate_existing_schema {
2660            let table_schema = table.schema();
2661            // Find timestamp column name
2662            let ts_col_name = table_schema.timestamp_column().map(|c| c.name.clone());
2663            // Find field column name if there is only one and `is_single_value` is true.
2664            let mut field_col_name = None;
2665            if is_single_value && request_field_count <= 1 {
2666                let mut multiple_field_cols = false;
2667                table.field_columns().for_each(|col| {
2668                    if field_col_name.is_none() {
2669                        field_col_name = Some(col.name.clone());
2670                    } else {
2671                        multiple_field_cols = true;
2672                    }
2673                });
2674                if multiple_field_cols {
2675                    field_col_name = None;
2676                }
2677            }
2678
2679            // Update column name in request schema for Timestamp/Field columns
2680            if let Some(rows) = req.rows.as_mut() {
2681                for col in &mut rows.schema {
2682                    match col.semantic_type {
2683                        x if x == SemanticType::Timestamp as i32 => {
2684                            if let Some(ref ts_name) = ts_col_name
2685                                && col.column_name != *ts_name
2686                            {
2687                                col.column_name = ts_name.clone();
2688                            }
2689                        }
2690                        x if x == SemanticType::Field as i32 => {
2691                            if let Some(ref field_name) = field_col_name
2692                                && col.column_name != *field_name
2693                            {
2694                                col.column_name = field_name.clone();
2695                            }
2696                        }
2697                        _ => {}
2698                    }
2699                }
2700            }
2701
2702            // Only keep columns that are tags or non-single field.
2703            add_columns.add_columns.retain(|col| {
2704                let def = col.column_def.as_ref().unwrap();
2705                def.semantic_type == SemanticType::Tag as i32
2706                    || (def.semantic_type == SemanticType::Field as i32 && field_col_name.is_none())
2707            });
2708
2709            if add_columns.add_columns.is_empty() {
2710                return Ok(None);
2711            }
2712        }
2713
2714        Ok(Some(AlterTableExpr {
2715            catalog_name: catalog_name.to_string(),
2716            schema_name: schema_name.clone(),
2717            table_name: table_name.clone(),
2718            kind: Some(Kind::AddColumns(add_columns)),
2719        }))
2720    }
2721
2722    /// Creates a table with options.
2723    ///
2724    /// Returns the table read back from the catalog: a CREATE that loses to a
2725    /// concurrent writer returns its own schema with the winner's table ID.
2726    async fn create_physical_table(
2727        &self,
2728        mut create_table_expr: CreateTableExpr,
2729        partitions: Option<Partitions>,
2730        ctx: &QueryContextRef,
2731        statement_executor: &StatementExecutor,
2732    ) -> Result<TableRef> {
2733        let res = statement_executor
2734            .create_table_inner(
2735                &mut create_table_expr,
2736                partitions,
2737                ctx.clone(),
2738                TriggerReason::AutoCreate,
2739            )
2740            .await;
2741
2742        let table_ref = TableReference::full(
2743            &create_table_expr.catalog_name,
2744            &create_table_expr.schema_name,
2745            &create_table_expr.table_name,
2746        );
2747
2748        match res {
2749            Ok(_) => {
2750                let table = self
2751                    .get_table(table_ref.catalog, table_ref.schema, table_ref.table)
2752                    .await?
2753                    .with_context(|| TableNotFoundSnafu {
2754                        table_name: table_ref.to_string(),
2755                    })?;
2756                validate_trace_table_model(&table.table_info(), ctx)?;
2757                Ok(table)
2758            }
2759            Err(err) => {
2760                error!(err; "Failed to create table {}", table_ref);
2761                Err(err)
2762            }
2763        }
2764    }
2765
2766    async fn create_logical_tables(
2767        &self,
2768        create_table_exprs: Vec<CreateTableExpr>,
2769        ctx: &QueryContextRef,
2770        statement_executor: &StatementExecutor,
2771    ) -> Result<Vec<TableRef>> {
2772        let res = statement_executor
2773            .create_logical_tables(&create_table_exprs, ctx.clone(), TriggerReason::AutoCreate)
2774            .await;
2775
2776        match res {
2777            Ok(res) => Ok(res),
2778            Err(err) => {
2779                let failed_tables = create_table_exprs
2780                    .into_iter()
2781                    .map(|expr| {
2782                        format!(
2783                            "{}.{}.{}",
2784                            expr.catalog_name, expr.schema_name, expr.table_name
2785                        )
2786                    })
2787                    .collect::<Vec<_>>();
2788                error!(
2789                    err;
2790                    "Failed to create logical tables {:?}",
2791                    failed_tables
2792                );
2793                Err(err)
2794            }
2795        }
2796    }
2797
2798    /// Returns the dispatcher shared with batching execution paths.
2799    pub fn write_dispatcher(&self) -> &WriteDispatcherRef {
2800        &self.write_dispatcher
2801    }
2802
2803    pub fn node_manager(&self) -> &NodeManagerRef {
2804        &self.node_manager
2805    }
2806
2807    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
2808        &self.partition_manager
2809    }
2810
2811    pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
2812        &self.table_flownode_set_cache
2813    }
2814}
2815
2816/// Merges `alter_expr` into the pending ALTER of the same table, so each table
2817/// gets one `AddColumns`. An ALTER LOGICAL TABLES procedure reads the metadata
2818/// of each table once and fails on a second ALTER of the same table.
2819fn merge_alter_table_expr(alter_tables: &mut Vec<AlterTableExpr>, alter_expr: AlterTableExpr) {
2820    let pending = alter_tables
2821        .iter_mut()
2822        .find(|pending| pending.table_name == alter_expr.table_name)
2823        .and_then(|pending| pending.kind.as_mut());
2824    if let Some(Kind::AddColumns(pending)) = pending
2825        && let Some(Kind::AddColumns(add_columns)) = alter_expr.kind
2826    {
2827        for add_column in add_columns.add_columns {
2828            let name = add_column.column_def.as_ref().map(|def| &def.name);
2829            if !pending
2830                .add_columns
2831                .iter()
2832                .any(|column| column.column_def.as_ref().map(|def| &def.name) == name)
2833            {
2834                pending.add_columns.push(add_column);
2835            }
2836        }
2837    } else {
2838        alter_tables.push(alter_expr);
2839    }
2840}
2841
2842fn request_is_native_histogram(request_schema: &[ColumnSchema]) -> bool {
2843    let mut fields = request_schema
2844        .iter()
2845        .filter(|col| col.semantic_type == SemanticType::Field as i32);
2846    let Some(col) = fields.next() else {
2847        return false;
2848    };
2849
2850    fields.next().is_none()
2851        && api::helper::is_column_type_value_eq(
2852            col.datatype,
2853            col.datatype_extension.clone(),
2854            native_histogram_value_type(),
2855        )
2856}
2857
2858/// Returns the table's time index unit, if any. A metric table without a
2859/// timestamp column is left alone by the unit alignment: the metric engine
2860/// rejects it anyway.
2861fn table_time_index_unit(table: &TableRef) -> Option<TimeUnit> {
2862    table
2863        .table_info()
2864        .meta
2865        .schema
2866        .timestamp_column()
2867        .and_then(|col| col.data_type.as_timestamp().map(|ts| ts.unit()))
2868}
2869
2870fn set_time_index_unit(create_table_expr: &mut CreateTableExpr, unit: TimeUnit) {
2871    if let Some(column) = create_table_expr
2872        .column_defs
2873        .iter_mut()
2874        .find(|column| column.name == create_table_expr.time_index)
2875    {
2876        column.data_type = api::helper::timestamp_datatype(unit) as i32;
2877        // Timestamp columns never carry a datatype extension.
2878        column.datatype_extension = None;
2879    }
2880}
2881
2882fn convert_rows_time_unit(rows: &mut Rows, target_unit: TimeUnit) -> Result<()> {
2883    let Some(ts_index) = rows
2884        .schema
2885        .iter()
2886        .position(|col| col.semantic_type == SemanticType::Timestamp as i32)
2887    else {
2888        return Ok(());
2889    };
2890    let Some(source_unit) = ColumnDataType::try_from(rows.schema[ts_index].datatype)
2891        .ok()
2892        .and_then(api::helper::timestamp_unit)
2893    else {
2894        return Ok(());
2895    };
2896    if source_unit == target_unit {
2897        return Ok(());
2898    }
2899
2900    rows.schema[ts_index].datatype = api::helper::timestamp_datatype(target_unit) as i32;
2901    // Timestamp columns never carry a datatype extension.
2902    rows.schema[ts_index].datatype_extension = None;
2903
2904    // Note: the schema is rewritten before the rows are converted, so an
2905    // overflow error mid-batch leaves this request half-converted. That is
2906    // harmless: the error aborts the whole insert request.
2907    //
2908    // `validate_column_count_match` guarantees every row carries exactly one
2909    // value per schema column, so the time index position is directly in
2910    // bounds; no per-value search is needed.
2911    for row in &mut rows.rows {
2912        debug_assert_eq!(row.values.len(), rows.schema.len());
2913        let value = &mut row.values[ts_index];
2914        let Some(value_data) = value.value_data.take() else {
2915            continue;
2916        };
2917        value.value_data =
2918            convert_timestamp_value_data(value_data, source_unit, target_unit, ts_index)?;
2919    }
2920    Ok(())
2921}
2922
2923fn convert_timestamp_value_data(
2924    value_data: ValueData,
2925    source_unit: TimeUnit,
2926    target_unit: TimeUnit,
2927    column_index: usize,
2928) -> Result<Option<ValueData>> {
2929    let timestamp = match value_data {
2930        ValueData::TimestampSecondValue(v) => Timestamp::new_second(v),
2931        ValueData::TimestampMillisecondValue(v) => Timestamp::new_millisecond(v),
2932        ValueData::TimestampMicrosecondValue(v) => Timestamp::new_microsecond(v),
2933        ValueData::TimestampNanosecondValue(v) => Timestamp::new_nanosecond(v),
2934        // Null or non-timestamp value; nothing to convert.
2935        other => return Ok(Some(other)),
2936    };
2937    let converted = timestamp
2938        .convert_to(target_unit)
2939        .with_context(|| InvalidInsertRequestSnafu {
2940            reason: format!(
2941                "timestamp column {column_index} value {} in unit {source_unit:?} overflows when converting to unit {target_unit:?}",
2942                timestamp.value()
2943            ),
2944        })?;
2945    Ok(api::helper::to_grpc_value(datatypes::value::Value::Timestamp(converted)).value_data)
2946}
2947
2948fn table_is_native_histogram(table: &TableRef) -> bool {
2949    let mut fields = table.field_columns();
2950    let Some(col) = fields.next() else {
2951        return false;
2952    };
2953
2954    fields.next().is_none() && is_native_histogram_value_type(&col.data_type)
2955}
2956
2957fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> {
2958    for request in &requests.inserts {
2959        let rows = request.rows.as_ref().unwrap();
2960        let column_count = rows.schema.len();
2961        rows.rows.iter().try_for_each(|r| {
2962            ensure!(
2963                r.values.len() == column_count,
2964                InvalidInsertRequestSnafu {
2965                    reason: format!(
2966                        "column count mismatch, columns: {}, values: {}",
2967                        column_count,
2968                        r.values.len()
2969                    )
2970                }
2971            );
2972            Ok(())
2973        })?;
2974    }
2975    Ok(())
2976}
2977
2978fn exemplar_source_add_columns(
2979    info: &TableInfo,
2980    tags: &[ColumnSchema],
2981) -> Result<Option<api::v1::AddColumns>> {
2982    for tag in tags {
2983        if let Some(index) = info.meta.schema.column_index_by_name(&tag.column_name) {
2984            let column = &info.meta.schema.column_schemas()[index];
2985            // Existing source defaults may already be part of the normalized series identity.
2986            ensure!(
2987                info.meta.primary_key_indices.contains(&index) && column.data_type.is_string(),
2988                InvalidInsertRequestSnafu {
2989                    reason: format!(
2990                        "exemplar source {} column {} must be a string tag",
2991                        info.name, tag.column_name
2992                    ),
2993                }
2994            );
2995        }
2996    }
2997    expr_helper::extract_add_columns_expr(&info.meta.schema, ColumnExpr::from_column_schemas(tags))
2998}
2999
3000/// Validates the fixed exemplar contract before writing or scanning a shared table.
3001pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> {
3002    let meta = &table.meta;
3003    let options = &meta.options.extra_options;
3004    ensure!(
3005        meta.engine == default_engine()
3006            && options
3007                .get(APPEND_MODE_KEY)
3008                .is_some_and(|v| v.eq_ignore_ascii_case("true"))
3009            && options
3010                .get(store_api::metric_engine_consts::PRIMARY_KEY_ENCODING)
3011                .is_some_and(|v| v.eq_ignore_ascii_case("sparse")),
3012        InvalidInsertRequestSnafu {
3013            reason: format!(
3014                "{METRICS_EXEMPLARS_TABLE} requires Mito, append_mode=true and primary_key_encoding=sparse"
3015            )
3016        }
3017    );
3018    let columns = meta.schema.column_schemas();
3019    let lookup = |name: &str| {
3020        columns
3021            .iter()
3022            .enumerate()
3023            .find(|(_, c)| c.name == name)
3024            .with_context(|| InvalidInsertRequestSnafu {
3025                reason: format!("missing exemplar column {name}"),
3026            })
3027    };
3028    let (_, timestamp) = lookup(greptime_timestamp())?;
3029    for (position, name, id, data_type) in [
3030        (
3031            0,
3032            DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
3033            ReservedColumnId::table_id(),
3034            datatypes::prelude::ConcreteDataType::uint32_datatype(),
3035        ),
3036        (
3037            1,
3038            DATA_SCHEMA_TSID_COLUMN_NAME,
3039            ReservedColumnId::tsid(),
3040            datatypes::prelude::ConcreteDataType::uint64_datatype(),
3041        ),
3042    ] {
3043        let (index, column) = lookup(name)?;
3044        ensure!(
3045            meta.primary_key_indices.get(position) == Some(&index)
3046                && meta.column_ids.get(index) == Some(&id)
3047                && column.data_type == data_type
3048                && !column.is_nullable()
3049                && column.default_constraint().is_none(),
3050            InvalidInsertRequestSnafu {
3051                reason: format!("invalid exemplar source identity column {name}"),
3052            }
3053        );
3054    }
3055    ensure!(
3056        timestamp.is_time_index() && timestamp.data_type.is_timestamp(),
3057        InvalidInsertRequestSnafu {
3058            reason: "invalid exemplar time index"
3059        }
3060    );
3061    let (metric_index, metric) = lookup(EXEMPLAR_METRIC_COLUMN)?;
3062    ensure!(
3063        metric.data_type.is_string() && meta.primary_key_indices.contains(&metric_index),
3064        InvalidInsertRequestSnafu {
3065            reason: "exemplar metric name must be a string tag"
3066        }
3067    );
3068    let (value_index, value) = lookup(greptime_value())?;
3069    ensure!(
3070        value.data_type == datatypes::prelude::ConcreteDataType::float64_datatype()
3071            && !meta.primary_key_indices.contains(&value_index),
3072        InvalidInsertRequestSnafu {
3073            reason: "exemplar value must be a DOUBLE field"
3074        }
3075    );
3076    let (labels_index, labels) = lookup(greptime_exemplar_labels())?;
3077    ensure!(
3078        labels.data_type.is_json2() && !meta.primary_key_indices.contains(&labels_index),
3079        InvalidInsertRequestSnafu {
3080            reason: format!("{} must be a JSON2 field", greptime_exemplar_labels())
3081        }
3082    );
3083    if let Some(extension) = labels
3084        .extension_type::<datatypes::extension::json::Json2ExtensionType>()
3085        .map_err(|error| {
3086            InvalidInsertRequestSnafu {
3087                reason: error.to_string(),
3088            }
3089            .build()
3090        })?
3091    {
3092        ensure!(
3093            extension
3094                .metadata()
3095                .json_settings()
3096                .type_hints()
3097                .iter()
3098                .all(|hint| hint.path.len() == 1 && hint.data_type.is_string()),
3099            InvalidInsertRequestSnafu {
3100                reason: "exemplar JSON2 hints must preserve string labels"
3101            }
3102        );
3103    }
3104    for (index, column) in columns.iter().enumerate() {
3105        if [
3106            greptime_timestamp(),
3107            greptime_value(),
3108            EXEMPLAR_METRIC_COLUMN,
3109            greptime_exemplar_labels(),
3110            DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
3111            DATA_SCHEMA_TSID_COLUMN_NAME,
3112        ]
3113        .contains(&column.name.as_str())
3114        {
3115            continue;
3116        }
3117        ensure!(
3118            meta.primary_key_indices.contains(&index)
3119                && column.data_type.is_string()
3120                && column.is_nullable(),
3121            InvalidInsertRequestSnafu {
3122                reason: "inherited exemplar labels must be nullable string tags"
3123            }
3124        );
3125        // An absent inherited label must remain absent from the source series identity,
3126        // and lets sparse keys prepared before an append-only tag ALTER stay valid.
3127        ensure!(
3128            matches!(
3129                column.default_constraint(),
3130                None | Some(ColumnDefaultConstraint::Value(
3131                    datatypes::value::Value::Null
3132                ))
3133            ),
3134            InvalidInsertRequestSnafu {
3135                reason: "inherited exemplar labels must not have non-NULL defaults"
3136            }
3137        );
3138    }
3139    Ok(())
3140}
3141
3142/// Rejects writes from a different built-in trace model before schema mutation.
3143/// Unstamped, explicitly created tables remain subject to normal schema validation.
3144pub fn validate_trace_table_model(table_info: &TableInfo, ctx: &QueryContextRef) -> Result<()> {
3145    let Some(expected @ (TABLE_DATA_MODEL_TRACE_V1 | TABLE_DATA_MODEL_TRACE_V2)) =
3146        ctx.extension(SEMANTIC_PIPELINE)
3147    else {
3148        return Ok(());
3149    };
3150    if let Some(actual) = table_info.meta.options.data_model() {
3151        ensure!(
3152            actual == expected,
3153            InvalidInsertRequestSnafu {
3154                reason: format!(
3155                    "Trace table `{}` uses {actual}, but the request uses {expected}",
3156                    table_info.name,
3157                ),
3158            }
3159        );
3160    }
3161    Ok(())
3162}
3163
3164/// Copies a retention `ttl` hint onto a physical metric table being created.
3165/// Only `ttl` is copied: other ingest hints must not land on the shared physical
3166/// table, and `ttl=instant` stays on the logical table for flow forwarding.
3167/// Once the physical table exists, the hint has no effect.
3168pub fn apply_retention_ttl_hint(
3169    table_options: &mut std::collections::HashMap<String, String>,
3170    ctx: &QueryContextRef,
3171) {
3172    if let Some(ttl) = ctx.extension(TTL_KEY).filter(|ttl| is_retention_ttl(ttl)) {
3173        table_options.insert(TTL_KEY.to_string(), ttl.to_string());
3174    }
3175}
3176
3177/// Fill table options for a new table by create type.
3178pub fn fill_table_options_for_create(
3179    table_options: &mut std::collections::HashMap<String, String>,
3180    create_type: &AutoCreateTableType,
3181    ctx: &QueryContextRef,
3182) {
3183    for key in VALID_TABLE_OPTION_KEYS {
3184        if let Some(value) = ctx.extension(key) {
3185            table_options.insert(key.to_string(), value.to_string());
3186        }
3187    }
3188
3189    if !matches!(create_type, AutoCreateTableType::Logical(_)) {
3190        let mut has_twcs_option = false;
3191        for key in COMPACTION_OPTION_KEYS {
3192            if let Some(value) = ctx.extension(key) {
3193                has_twcs_option |= key.starts_with(COMPACTION_TWCS_PREFIX);
3194                table_options.insert(key.to_string(), value.to_string());
3195            }
3196        }
3197        if has_twcs_option {
3198            table_options
3199                .entry(COMPACTION_TYPE.to_string())
3200                .or_insert_with(|| COMPACTION_TYPE_TWCS.to_string());
3201        }
3202    }
3203
3204    // Semantic keys use their own vocabulary instead of the fixed option list.
3205    for (key, value) in ctx.extensions() {
3206        if is_semantic_option_key(&key) && validate_semantic_option(&key, &value) {
3207            table_options.insert(key, value);
3208        }
3209    }
3210
3211    match create_type {
3212        AutoCreateTableType::Logical(physical_table) => {
3213            table_options.insert(
3214                LOGICAL_TABLE_METADATA_KEY.to_string(),
3215                physical_table.clone(),
3216            );
3217        }
3218        AutoCreateTableType::Exemplar => {
3219            table_options.retain(|key, _| {
3220                !is_semantic_option_key(key)
3221                    && key != SEMANTIC_PER_TABLE_INDEX_KEY
3222                    && key != LOGICAL_TABLE_METADATA_KEY
3223                    && key != PHYSICAL_TABLE_METADATA_KEY
3224                    && key != MERGE_MODE_KEY
3225                    && key != "otlp_metric_compat"
3226            });
3227            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3228            table_options.insert(
3229                store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
3230                "sparse".to_string(),
3231            );
3232        }
3233        AutoCreateTableType::Physical => {
3234            if let Some(append_mode) = ctx.extension(APPEND_MODE_KEY) {
3235                table_options.insert(APPEND_MODE_KEY.to_string(), append_mode.to_string());
3236            }
3237            if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
3238                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
3239            }
3240        }
3241        // Set append_mode to true for log table.
3242        // because log tables should keep rows with the same ts and tags.
3243        AutoCreateTableType::Log => {
3244            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3245        }
3246        AutoCreateTableType::LastNonNull => {
3247            if ctx
3248                .extension(APPEND_MODE_KEY)
3249                .is_some_and(|value| value.eq_ignore_ascii_case("true"))
3250            {
3251                table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3252                table_options.insert(MERGE_MODE_KEY.to_string(), "last_row".to_string());
3253            } else if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
3254                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
3255            } else {
3256                table_options.insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
3257            }
3258        }
3259        AutoCreateTableType::Trace { .. } => {
3260            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
3261        }
3262    }
3263}
3264
3265/// The parsed per-table semantic index: `{schema -> {table -> {key -> value}}}`,
3266/// produced by the OTLP metrics encode path (where one metric can fan out into
3267/// several tables with distinct keys) and the Prometheus remote write v2 path
3268/// (where per-series metadata declares type/unit, and a series may override its
3269/// target schema).
3270pub type PerTableSemanticIndex = BTreeMap<String, BTreeMap<String, BTreeMap<String, String>>>;
3271
3272/// Parses the per-table semantic index off the context extension. Call once per
3273/// create-planning round: a first write creating N tables would otherwise
3274/// re-parse the whole index N times. `None` when the request carries no index
3275/// (logs, traces, Prom RW v1) or it fails to parse.
3276pub fn parse_per_table_semantic_index(ctx: &QueryContextRef) -> Option<PerTableSemanticIndex> {
3277    let raw = ctx.extension(SEMANTIC_PER_TABLE_INDEX_KEY)?;
3278    match serde_json::from_str(raw) {
3279        Ok(index) => Some(index),
3280        Err(_) => {
3281            warn!("failed to parse semantic per-table index, skipping per-table options");
3282            None
3283        }
3284    }
3285}
3286
3287/// Folds the semantic keys of the table being created into `table_options`.
3288///
3289/// Common keys shared by every table in a request travel as plain semantic
3290/// extensions and are handled by [`fill_table_options_for_create`]; this
3291/// carries only the per-table tail and is applied after it, so a per-table
3292/// value (e.g. `declared` quality) wins. Keys are re-checked against the
3293/// vocabulary defensively.
3294pub fn apply_per_table_semantic_options(
3295    table_options: &mut std::collections::HashMap<String, String>,
3296    index: Option<&PerTableSemanticIndex>,
3297    schema: &str,
3298    table_name: &str,
3299) {
3300    let Some(entry) = index
3301        .and_then(|index| index.get(schema))
3302        .and_then(|tables| tables.get(table_name))
3303    else {
3304        return;
3305    };
3306    for (key, value) in entry {
3307        if is_semantic_option_key(key) && validate_semantic_option(key, value) {
3308            table_options.insert(key.clone(), value.clone());
3309        }
3310    }
3311}
3312
3313pub fn build_create_table_expr(
3314    table: &TableReference,
3315    request_schema: &[ColumnSchema],
3316    engine: &str,
3317) -> Result<CreateTableExpr> {
3318    expr_helper::create_table_expr_by_column_schemas(table, request_schema, engine, None)
3319}
3320
3321/// `QueryContext` extension key the Splunk HEC handler sets (to `"true"`) on its identity
3322/// path to request metadata-first primary-key ordering at table creation. It is absent for
3323/// user-supplied pipelines, so their primary-key order is left untouched.
3324pub const SPLUNK_PK_METADATA_ORDER_KEY: &str = "splunk_pk_metadata_order";
3325
3326/// Moves Splunk's metadata tags (`host`, `source`, `sourcetype`) to the front of the
3327/// primary key, keeping the relative order of the remaining tags.
3328fn reorder_splunk_primary_keys(primary_keys: &mut [String]) {
3329    const LEAD: [&str; 3] = ["host", "source", "sourcetype"];
3330    // Stable sort: `LEAD` columns move to the front in `host`/`source`/`sourcetype` order;
3331    // every other column keeps its existing relative position.
3332    primary_keys.sort_by_key(|name| {
3333        LEAD.iter()
3334            .position(|&lead| lead == name.as_str())
3335            .unwrap_or(LEAD.len())
3336    });
3337}
3338
3339/// Result of `create_or_alter_tables_on_demand`.
3340struct CreateAlterTableResult {
3341    /// table ids of ttl=instant tables.
3342    instant_table_ids: HashSet<TableId>,
3343    /// Table Info of the created tables.
3344    table_infos: HashMap<TableId, Arc<TableInfo>>,
3345}
3346
3347/// Upper bound of rows buffered by detached flow mirror tasks on this frontend.
3348///
3349/// Rows retained by in-flight mirror RPCs count against this bound. If ordinary
3350/// persisted source-table mirroring exceeds it, that mirror batch is best-effort
3351/// dropped while its datanode write continues. Instant-TTL batches fail retryably
3352/// on temporary saturation; oversized batches fail non-retryably so the client
3353/// can reduce the batch size.
3354const MAX_MIRROR_PENDING_ROWS: usize = 1_000_000;
3355
3356/// How often at most each mirror event is reported.
3357const MIRROR_LOG_INTERVAL: Duration = Duration::from_secs(10);
3358const MIRROR_LOG_NEVER_REPORTED: u64 = u64::MAX;
3359
3360struct MirrorLog {
3361    last_log_millis: AtomicU64,
3362    events: AtomicU64,
3363}
3364
3365impl MirrorLog {
3366    const fn new() -> Self {
3367        Self {
3368            last_log_millis: AtomicU64::new(MIRROR_LOG_NEVER_REPORTED),
3369            events: AtomicU64::new(0),
3370        }
3371    }
3372
3373    /// Returns the count since the previous report, including this event, to
3374    /// the single caller that claims the interval.
3375    fn claim_report(&self, now_millis: u64) -> Option<u64> {
3376        self.events.fetch_add(1, Ordering::Relaxed);
3377        let last = self.last_log_millis.load(Ordering::Relaxed);
3378        if last != MIRROR_LOG_NEVER_REPORTED
3379            && now_millis.saturating_sub(last) < MIRROR_LOG_INTERVAL.as_millis() as u64
3380        {
3381            return None;
3382        }
3383        if self
3384            .last_log_millis
3385            .compare_exchange(last, now_millis, Ordering::Relaxed, Ordering::Relaxed)
3386            .is_err()
3387        {
3388            return None;
3389        }
3390        Some(self.events.swap(0, Ordering::Relaxed))
3391    }
3392}
3393
3394static MIRROR_DROP_LOG: MirrorLog = MirrorLog::new();
3395static MIRROR_FAILURE_LOG: MirrorLog = MirrorLog::new();
3396
3397/// Milliseconds since the first call, so the drop log is rate limited on a
3398/// monotonic clock instead of the wall clock, which can jump.
3399fn mirror_drop_log_millis() -> u64 {
3400    static START: LazyLock<Instant> = LazyLock::new(Instant::now);
3401    START.elapsed().as_millis() as u64
3402}
3403
3404// A cold table needs a prefix scan to discover its flow partitions.
3405const MAX_CONCURRENT_FLOW_LOOKUPS: usize = 8;
3406
3407struct FlowMirrorTask {
3408    requests: HashMap<Peer, RegionInsertRequests>,
3409}
3410
3411impl FlowMirrorTask {
3412    async fn new(
3413        cache: &TableFlownodeSetCacheRef,
3414        requests: impl Iterator<Item = &RegionInsertRequest>,
3415    ) -> Result<Self> {
3416        let mut by_table: HashMap<TableId, Vec<&RegionInsertRequest>> = HashMap::new();
3417        for req in requests {
3418            let table_id = RegionId::from_u64(req.region_id).table_id();
3419            by_table.entry(table_id).or_default().push(req);
3420        }
3421
3422        let table_ids: Vec<_> = by_table.keys().copied().collect();
3423        let mut lookups = stream::iter(table_ids)
3424            .map(|id| async move { cache.get(id).await.map(|flows| (id, flows)) })
3425            .buffer_unordered(MAX_CONCURRENT_FLOW_LOOKUPS);
3426        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
3427        while let Some((id, flows)) = lookups.try_next().await.context(RequestInsertsSnafu)? {
3428            if let Some(flows) = flows {
3429                for peer in flows.values().collect::<HashSet<_>>() {
3430                    inserts
3431                        .entry(peer.clone())
3432                        .or_default()
3433                        .requests
3434                        .extend(by_table[&id].iter().copied().cloned());
3435                }
3436            }
3437        }
3438
3439        Ok(Self { requests: inserts })
3440    }
3441
3442    /// Rows of row data this task keeps alive once detached: the payload it
3443    /// spawns per peer, not the source requests it was built from.
3444    ///
3445    /// A source table mapped to several flownodes clones its requests per peer
3446    /// and every clone owns its own copy of the rows, so reserving from
3447    /// `self.requests` is what the per-peer shares released by [`Self::detach`]
3448    /// sum to. Counting the source requests instead under-reserves whenever a
3449    /// batch holds several requests for the same source table.
3450    fn pending_rows(&self) -> u64 {
3451        self.requests.values().map(region_inserts_rows).sum()
3452    }
3453
3454    fn detach(
3455        self,
3456        node_manager: NodeManagerRef,
3457        mirror_pending_rows: Arc<AtomicU64>,
3458        has_instant_rows: bool,
3459    ) -> Result<()> {
3460        // Reserve the cloned per-peer payload before spawning. A full budget
3461        // drops normal mirrors or rejects instant writes before datanode dispatch.
3462        let num_rows = self.pending_rows();
3463        if num_rows == 0 {
3464            return Ok(());
3465        }
3466        if has_instant_rows && num_rows > MAX_MIRROR_PENDING_ROWS as u64 {
3467            return InvalidInsertRequestSnafu {
3468                reason: format!(
3469                    "flow mirror batch has {num_rows} peer-fan-out rows, exceeding the limit of {}; reduce the batch size",
3470                    MAX_MIRROR_PENDING_ROWS
3471                ),
3472            }
3473            .fail();
3474        }
3475
3476        let pending = reserve_mirror_pending_rows(&mirror_pending_rows, num_rows);
3477        if pending > MAX_MIRROR_PENDING_ROWS as u64 {
3478            release_mirror_pending_rows(&mirror_pending_rows, num_rows);
3479            if has_instant_rows {
3480                return Err(meter_core::collect::WriteRejected::new(
3481                    "flow mirror pending rows limit exceeded for instant-TTL insert",
3482                ))
3483                .context(WriteRejectedSnafu);
3484            }
3485            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.inc_by(num_rows);
3486            if let Some(events) = MIRROR_DROP_LOG.claim_report(mirror_drop_log_millis()) {
3487                warn!(
3488                    "Flow mirror write dropped: {} pending rows exceeds limit {}, {} drop events since last report",
3489                    pending, MAX_MIRROR_PENDING_ROWS, events
3490                );
3491            }
3492            return Ok(());
3493        }
3494
3495        for (peer, inserts) in self.requests {
3496            // Each spawned task releases exactly its own share of the
3497            // reservation. The shares are computed over the same per-peer
3498            // payload as `pending_rows`, so they sum to the reservation.
3499            let peer_rows = region_inserts_rows(&inserts);
3500            let node_manager = node_manager.clone();
3501            let mirror_pending_rows = mirror_pending_rows.clone();
3502            common_runtime::spawn_global(async move {
3503                let result = node_manager
3504                    .flownode(&peer)
3505                    .await
3506                    .handle_inserts(inserts)
3507                    .await
3508                    .context(RequestInsertsSnafu);
3509
3510                match result {
3511                    Ok(resp) => {
3512                        let affected_rows = resp.affected_rows;
3513                        crate::metrics::DIST_MIRROR_ROW_COUNT.inc_by(affected_rows);
3514                    }
3515                    Err(err) => {
3516                        if let Some(events) =
3517                            MIRROR_FAILURE_LOG.claim_report(mirror_drop_log_millis())
3518                        {
3519                            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);
3520                        }
3521                    }
3522                }
3523                // Release the reservation on both the success and the failure
3524                // path, otherwise a broken flownode would fill the budget forever.
3525                release_mirror_pending_rows(&mirror_pending_rows, peer_rows);
3526            });
3527        }
3528
3529        Ok(())
3530    }
3531}
3532
3533/// Rows of row data carried by `inserts`. A request without a `rows` payload
3534/// carries nothing to keep buffered and contributes zero.
3535fn region_inserts_rows(inserts: &RegionInsertRequests) -> u64 {
3536    inserts
3537        .requests
3538        .iter()
3539        .filter_map(|req| req.rows.as_ref())
3540        .map(|rows| rows.rows.len() as u64)
3541        .sum()
3542}
3543
3544/// Reserves `rows` of the pending mirror budget and returns the resulting
3545/// pending row count. The caller must [`release_mirror_pending_rows`] exactly
3546/// these rows once they are no longer buffered, whether it spawns the batch or
3547/// drops it.
3548fn reserve_mirror_pending_rows(mirror_pending_rows: &AtomicU64, rows: u64) -> u64 {
3549    let pending = mirror_pending_rows.fetch_add(rows, Ordering::Relaxed) + rows;
3550    // Keep the gauge in step by applying the same increment, never by setting an
3551    // absolute value: another task may move the budget in between.
3552    crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(rows as i64);
3553    pending
3554}
3555
3556/// Releases `rows` of the pending mirror budget.
3557///
3558/// Every release mirrors the reservation it hands back, so a well-behaved
3559/// release never subtracts more than is pending; the saturating update only
3560/// keeps a duplicated release from wrapping the shared budget around.
3561fn release_mirror_pending_rows(mirror_pending_rows: &AtomicU64, rows: u64) {
3562    let prev = mirror_pending_rows
3563        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |pending| {
3564            Some(pending.saturating_sub(rows))
3565        })
3566        .unwrap_or_else(|prev| prev);
3567    // Subtract from the gauge with the opposite sign of
3568    // [`reserve_mirror_pending_rows`]; reading the budget here and `set`-ting it
3569    // would publish a stale value whenever another task releases concurrently.
3570    let released = rows.min(prev);
3571    if released > 0 {
3572        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(released as i64);
3573    }
3574}
3575
3576#[cfg(test)]
3577mod tests {
3578    use std::future::Future;
3579    use std::sync::Arc;
3580    use std::sync::atomic::{AtomicU64, Ordering};
3581    use std::task::Poll;
3582
3583    use api::helper::ColumnDataTypeWrapper;
3584    use api::region::RegionResponse;
3585    use api::v1::flow::FlowResponse;
3586    use api::v1::helper::{field_column_schema, time_index_column_schema};
3587    use api::v1::{Row, RowInsertRequest, Rows, Value};
3588    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
3589    use common_error::ext::{ErrorExt, RetryHint};
3590    use common_error::mock::MockError;
3591    use common_error::status_code::StatusCode;
3592    use common_meta::cache::new_table_flownode_set_cache;
3593    use common_meta::cache_invalidator::DummyCacheInvalidator;
3594    use common_meta::ddl::test_util::datanode_handler::NaiveDatanodeHandler;
3595    use common_meta::instruction::{CacheIdent, CreateFlow};
3596    use common_meta::node_manager::{
3597        Datanode, DatanodeManager, DatanodeRef, FlownodeManager, FlownodeRef,
3598    };
3599    use common_meta::test_util::{MockDatanodeManager, MockFlownodeHandler, MockFlownodeManager};
3600    use common_query::native_histogram::NATIVE_HISTOGRAM_FIELD;
3601    use common_query::prelude::{greptime_native_histogram, set_default_prefix};
3602    use datatypes::data_type::ConcreteDataType;
3603    use datatypes::schema::ColumnSchema;
3604    use moka::future::Cache;
3605    use session::context::QueryContext;
3606    use table::TableRef;
3607    use table::dist_table::DummyDataSource;
3608    use table::metadata::{TableInfoBuilder, TableMetaBuilder, TableType};
3609    use tokio::sync::{Semaphore, mpsc};
3610
3611    use crate::insert::*;
3612    use crate::test_util::{
3613        create_partition_rule_manager, new_test_table_info, prepare_mocked_backend,
3614    };
3615    use crate::write_dispatcher::{TrackedWrite, WriteRetryOptions};
3616
3617    async fn cache_test_flow(cache: &TableFlownodeSetCacheRef, flow: CreateFlow) {
3618        cache.get_many(&flow.source_table_ids).await.unwrap();
3619        cache
3620            .invalidate(&[CacheIdent::CreateFlow(flow)])
3621            .await
3622            .unwrap();
3623    }
3624
3625    fn make_table_ref_with_schema(
3626        ts_name: &str,
3627        field_name: &str,
3628        field_type: ConcreteDataType,
3629    ) -> TableRef {
3630        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
3631            ColumnSchema::new(
3632                ts_name,
3633                ConcreteDataType::timestamp_millisecond_datatype(),
3634                false,
3635            )
3636            .with_time_index(true),
3637            ColumnSchema::new(field_name, field_type, true),
3638        ])
3639        .unwrap()
3640        .build()
3641        .unwrap();
3642        let meta = TableMetaBuilder::empty()
3643            .schema(Arc::new(schema))
3644            .primary_key_indices(vec![])
3645            .value_indices(vec![1])
3646            .engine("mito")
3647            .next_column_id(0)
3648            .options(Default::default())
3649            .created_on(Default::default())
3650            .build()
3651            .unwrap();
3652        let info = Arc::new(
3653            TableInfoBuilder::default()
3654                .table_id(1)
3655                .table_version(0)
3656                .name("test_table")
3657                .schema_name(DEFAULT_SCHEMA_NAME)
3658                .catalog_name(DEFAULT_CATALOG_NAME)
3659                .desc(None)
3660                .table_type(TableType::Base)
3661                .meta(meta)
3662                .build()
3663                .unwrap(),
3664        );
3665        Arc::new(table::Table::new(
3666            info,
3667            table::metadata::FilterPushDownType::Unsupported,
3668            Arc::new(DummyDataSource),
3669        ))
3670    }
3671
3672    fn make_metric_physical_table_ref_with_time_unit(unit: TimeUnit) -> TableRef {
3673        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
3674            ColumnSchema::new(
3675                greptime_timestamp(),
3676                ConcreteDataType::timestamp_datatype(unit),
3677                false,
3678            )
3679            .with_time_index(true),
3680            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
3681        ])
3682        .unwrap()
3683        .build()
3684        .unwrap();
3685        let meta = TableMetaBuilder::empty()
3686            .schema(Arc::new(schema))
3687            .primary_key_indices(vec![])
3688            .value_indices(vec![1])
3689            .engine("metric")
3690            .next_column_id(0)
3691            .options(Default::default())
3692            .created_on(Default::default())
3693            .build()
3694            .unwrap();
3695        let info = Arc::new(
3696            TableInfoBuilder::default()
3697                .table_id(1)
3698                .table_version(0)
3699                .name("greptime_physical_table")
3700                .schema_name(DEFAULT_SCHEMA_NAME)
3701                .catalog_name(DEFAULT_CATALOG_NAME)
3702                .desc(None)
3703                .table_type(TableType::Base)
3704                .meta(meta)
3705                .build()
3706                .unwrap(),
3707        );
3708        Arc::new(table::Table::new(
3709            info,
3710            table::metadata::FilterPushDownType::Unsupported,
3711            Arc::new(DummyDataSource),
3712        ))
3713    }
3714
3715    fn ms_row_insert_request(timestamp_ms: i64) -> RowInsertRequest {
3716        ms_row_insert_request_named("my_metric", timestamp_ms)
3717    }
3718
3719    fn ms_row_insert_request_named(table: &str, timestamp_ms: i64) -> RowInsertRequest {
3720        RowInsertRequest {
3721            table_name: table.to_string(),
3722            rows: Some(Rows {
3723                schema: vec![
3724                    time_index_column_schema(
3725                        greptime_timestamp(),
3726                        ColumnDataType::TimestampMillisecond,
3727                    ),
3728                    field_column_schema(greptime_value(), ColumnDataType::Float64),
3729                ],
3730                rows: vec![Row {
3731                    values: vec![
3732                        Value {
3733                            value_data: Some(ValueData::TimestampMillisecondValue(timestamp_ms)),
3734                        },
3735                        Value {
3736                            value_data: Some(ValueData::F64Value(1.0)),
3737                        },
3738                    ],
3739                }],
3740            }),
3741        }
3742    }
3743
3744    /// Converts the time index column of each request to `target_unit`.
3745    fn convert_row_insert_requests_time_unit(
3746        requests: &mut RowInsertRequests,
3747        target_unit: TimeUnit,
3748    ) -> Result<()> {
3749        for request in &mut requests.inserts {
3750            let Some(rows) = request.rows.as_mut() else {
3751                continue;
3752            };
3753            convert_rows_time_unit(rows, target_unit)?;
3754        }
3755        Ok(())
3756    }
3757
3758    #[test]
3759    fn test_convert_row_insert_requests_time_unit_noop_when_matching() {
3760        let mut requests = RowInsertRequests {
3761            inserts: vec![ms_row_insert_request(123)],
3762        };
3763        convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Millisecond).unwrap();
3764        let rows = requests.inserts[0].rows.as_ref().unwrap();
3765        assert_eq!(
3766            rows.schema[0].datatype,
3767            ColumnDataType::TimestampMillisecond as i32
3768        );
3769        assert!(matches!(
3770            rows.rows[0].values[0].value_data,
3771            Some(ValueData::TimestampMillisecondValue(123))
3772        ));
3773    }
3774
3775    #[test]
3776    fn test_convert_row_insert_requests_time_unit_widens_losslessly() {
3777        let mut requests = RowInsertRequests {
3778            inserts: vec![ms_row_insert_request(123)],
3779        };
3780        convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Microsecond).unwrap();
3781        let rows = requests.inserts[0].rows.as_ref().unwrap();
3782        assert_eq!(
3783            rows.schema[0].datatype,
3784            ColumnDataType::TimestampMicrosecond as i32
3785        );
3786        assert!(matches!(
3787            rows.rows[0].values[0].value_data,
3788            Some(ValueData::TimestampMicrosecondValue(123_000))
3789        ));
3790    }
3791
3792    #[test]
3793    fn test_convert_row_insert_requests_time_unit_truncates_on_narrowing() {
3794        // 123_456_789 ns floors to 123_456 us and 123 ms; negative values
3795        // floor towards negative infinity, matching `Timestamp::convert_to`.
3796        let requests = |value_ns: i64| RowInsertRequests {
3797            inserts: vec![RowInsertRequest {
3798                table_name: "my_metric".to_string(),
3799                rows: Some(Rows {
3800                    schema: vec![
3801                        time_index_column_schema(
3802                            greptime_timestamp(),
3803                            ColumnDataType::TimestampNanosecond,
3804                        ),
3805                        field_column_schema(greptime_value(), ColumnDataType::Float64),
3806                    ],
3807                    rows: vec![Row {
3808                        values: vec![
3809                            Value {
3810                                value_data: Some(ValueData::TimestampNanosecondValue(value_ns)),
3811                            },
3812                            Value {
3813                                value_data: Some(ValueData::F64Value(1.0)),
3814                            },
3815                        ],
3816                    }],
3817                }),
3818            }],
3819        };
3820
3821        let mut reqs = requests(123_456_789);
3822        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Microsecond).unwrap();
3823        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3824        assert!(matches!(
3825            rows.rows[0].values[0].value_data,
3826            Some(ValueData::TimestampMicrosecondValue(123_456))
3827        ));
3828
3829        let mut reqs = requests(123_456_789);
3830        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Millisecond).unwrap();
3831        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3832        assert!(matches!(
3833            rows.rows[0].values[0].value_data,
3834            Some(ValueData::TimestampMillisecondValue(123))
3835        ));
3836
3837        let mut reqs = requests(-123_456_789);
3838        convert_row_insert_requests_time_unit(&mut reqs, TimeUnit::Microsecond).unwrap();
3839        let rows = reqs.inserts[0].rows.as_ref().unwrap();
3840        assert!(matches!(
3841            rows.rows[0].values[0].value_data,
3842            Some(ValueData::TimestampMicrosecondValue(-123_457))
3843        ));
3844    }
3845
3846    #[test]
3847    fn test_convert_row_insert_requests_time_unit_overflow() {
3848        let mut requests = RowInsertRequests {
3849            inserts: vec![ms_row_insert_request(i64::MAX)],
3850        };
3851        let err =
3852            convert_row_insert_requests_time_unit(&mut requests, TimeUnit::Nanosecond).unwrap_err();
3853        assert!(err.to_string().contains("overflows"), "{err}");
3854    }
3855
3856    #[test]
3857    fn test_table_time_index_unit() {
3858        assert_eq!(
3859            table_time_index_unit(&make_metric_physical_table_ref_with_time_unit(
3860                TimeUnit::Microsecond
3861            )),
3862            Some(TimeUnit::Microsecond)
3863        );
3864        assert_eq!(
3865            table_time_index_unit(&make_metric_physical_table_ref_with_time_unit(
3866                TimeUnit::Millisecond
3867            )),
3868            Some(TimeUnit::Millisecond)
3869        );
3870    }
3871
3872    #[tokio::test]
3873    async fn test_accommodate_existing_schema_and_reject_kind_changes() {
3874        let ts_name = "my_ts";
3875        let field_name = "my_field";
3876        let table =
3877            make_table_ref_with_schema(ts_name, field_name, ConcreteDataType::float64_datatype());
3878
3879        // The request uses different names for timestamp and field columns
3880        let mut req = RowInsertRequest {
3881            table_name: "test_table".to_string(),
3882            rows: Some(Rows {
3883                schema: vec![
3884                    time_index_column_schema("ts_wrong", ColumnDataType::TimestampMillisecond),
3885                    field_column_schema("field_wrong", ColumnDataType::Float64),
3886                ],
3887                rows: vec![api::v1::Row {
3888                    values: vec![Value::default(), Value::default()],
3889                }],
3890            }),
3891        };
3892        let ctx = Arc::new(QueryContext::with(
3893            DEFAULT_CATALOG_NAME,
3894            DEFAULT_SCHEMA_NAME,
3895        ));
3896
3897        let kv_backend = prepare_mocked_backend().await;
3898        let inserter = Inserter::new(
3899            catalog::memory::MemoryCatalogManager::new(),
3900            create_partition_rule_manager(kv_backend.clone()).await,
3901            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
3902            Arc::new(new_table_flownode_set_cache(
3903                String::new(),
3904                Cache::new(100),
3905                kv_backend.clone(),
3906            )),
3907            true,
3908        );
3909        // Do not apply an absent-table plan to a table that appeared concurrently.
3910        assert!(
3911            inserter
3912                .get_alter_table_expr_on_demand(&mut req, &table, &ctx, false, false, false)
3913                .unwrap()
3914                .is_none()
3915        );
3916        let alter_expr = inserter
3917            .get_alter_table_expr_on_demand(&mut req, &table, &ctx, true, true, true)
3918            .unwrap();
3919        assert!(alter_expr.is_none());
3920
3921        // The request's schema should have updated names for timestamp and field columns
3922        let req_schema = req.rows.as_ref().unwrap().schema.clone();
3923        assert_eq!(req_schema[0].column_name, ts_name);
3924        assert_eq!(req_schema[1].column_name, field_name);
3925
3926        let (datatype, datatype_extension) =
3927            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
3928                .unwrap()
3929                .into_parts();
3930        let mut histogram_req = RowInsertRequest {
3931            table_name: "test_table".to_string(),
3932            rows: Some(Rows {
3933                schema: vec![
3934                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
3935                    api::v1::ColumnSchema {
3936                        column_name: greptime_native_histogram().to_string(),
3937                        datatype: datatype as i32,
3938                        semantic_type: SemanticType::Field as i32,
3939                        datatype_extension,
3940                        options: None,
3941                    },
3942                ],
3943                rows: vec![],
3944            }),
3945        };
3946        let error = inserter
3947            .get_alter_table_expr_on_demand(&mut histogram_req, &table, &ctx, false, true, true)
3948            .unwrap_err();
3949        assert!(
3950            error
3951                .to_string()
3952                .contains("cannot mix native histogram and float sample fields")
3953        );
3954
3955        let histogram_table = make_table_ref_with_schema(
3956            "ts",
3957            greptime_native_histogram(),
3958            native_histogram_value_type().clone(),
3959        );
3960        let mut sample_req = RowInsertRequest {
3961            table_name: "test_table".to_string(),
3962            rows: Some(Rows {
3963                schema: vec![
3964                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
3965                    field_column_schema(greptime_value(), ColumnDataType::Float64),
3966                ],
3967                rows: vec![],
3968            }),
3969        };
3970        let error = inserter
3971            .get_alter_table_expr_on_demand(
3972                &mut sample_req,
3973                &histogram_table,
3974                &ctx,
3975                false,
3976                true,
3977                true,
3978            )
3979            .unwrap_err();
3980        assert!(
3981            error
3982                .to_string()
3983                .contains("cannot mix native histogram and float sample fields")
3984        );
3985    }
3986
3987    #[test]
3988    fn test_native_histogram_detection_survives_prefix_change() {
3989        set_default_prefix(Some("custom")).unwrap();
3990        let table = make_table_ref_with_schema(
3991            "custom_timestamp",
3992            NATIVE_HISTOGRAM_FIELD,
3993            native_histogram_value_type().clone(),
3994        );
3995        let (datatype, datatype_extension) =
3996            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
3997                .unwrap()
3998                .into_parts();
3999        let request_schema = [api::v1::ColumnSchema {
4000            column_name: greptime_native_histogram().to_string(),
4001            datatype: datatype as i32,
4002            semantic_type: SemanticType::Field as i32,
4003            datatype_extension,
4004            options: None,
4005        }];
4006
4007        assert!(request_is_native_histogram(&request_schema));
4008        assert!(table_is_native_histogram(&table));
4009    }
4010
4011    #[derive(Clone)]
4012    struct GatedDatanodeHandler {
4013        started: mpsc::UnboundedSender<u32>,
4014        completed: mpsc::UnboundedSender<u32>,
4015        release: Arc<Semaphore>,
4016    }
4017
4018    #[async_trait::async_trait]
4019    impl Datanode for GatedDatanodeHandler {
4020        async fn handle_request(
4021            &self,
4022            request: Arc<api::v1::region::RegionRequest>,
4023        ) -> common_meta::error::Result<RegionResponse> {
4024            let Some(api::v1::region::region_request::Body::Inserts(requests)) = &request.body
4025            else {
4026                panic!("expected inserts");
4027            };
4028            let region = RegionId::from(requests.requests[0].region_id).region_number();
4029            self.started.send(region).unwrap();
4030            self.release.acquire().await.unwrap().forget();
4031            self.completed.send(region).unwrap();
4032            if region == 2 {
4033                Err(common_meta::error::Error::retry_later(MockError::new(
4034                    StatusCode::RegionBusy,
4035                )))
4036            } else {
4037                Ok(RegionResponse::new(1))
4038            }
4039        }
4040
4041        async fn handle_query(
4042            &self,
4043            _request: common_query::request::QueryRequest,
4044        ) -> common_meta::error::Result<common_recordbatch::SendableRecordBatchStream> {
4045            unreachable!()
4046        }
4047    }
4048
4049    #[async_trait::async_trait]
4050    impl DatanodeManager for GatedDatanodeHandler {
4051        async fn datanode(&self, _peer: &Peer) -> DatanodeRef {
4052            Arc::new(self.clone())
4053        }
4054    }
4055
4056    #[async_trait::async_trait]
4057    impl FlownodeManager for GatedDatanodeHandler {
4058        async fn flownode(&self, _peer: &Peer) -> FlownodeRef {
4059            unreachable!()
4060        }
4061    }
4062
4063    #[tokio::test]
4064    async fn test_insert_cancellation_drains_inflight_writes() {
4065        for confirmed in [false, true] {
4066            for max_retries in [0, 2] {
4067                let mut inserter = batcher_test_inserter().await;
4068                let (started, mut starts) = mpsc::unbounded_channel();
4069                let (completed, mut completions) = mpsc::unbounded_channel();
4070                let release = Arc::new(Semaphore::new(0));
4071                let node_manager = Arc::new(GatedDatanodeHandler {
4072                    started,
4073                    completed,
4074                    release: release.clone(),
4075                });
4076                inserter.node_manager = node_manager.clone();
4077                let dispatcher = Arc::new(
4078                    WriteDispatcher::new(node_manager, inserter.partition_manager.clone())
4079                        .with_retry(
4080                            WriteRetryOptions {
4081                                max_retries,
4082                                initial_backoff: Duration::ZERO,
4083                                max_backoff: Duration::ZERO,
4084                                ..Default::default()
4085                            },
4086                            inserter.catalog_manager.clone(),
4087                            Arc::new(DummyCacheInvalidator),
4088                        ),
4089                );
4090                let inserter = inserter.with_write_dispatcher(dispatcher);
4091                let table_infos = HashMap::from_iter([(
4092                    1,
4093                    Arc::new(new_test_table_info(1, "table_1", [1].into_iter())),
4094                )]);
4095                let counter = Arc::new(session::write_progress::WriteProgress::default());
4096                let mut ctx = QueryContext::arc().fork();
4097                ctx.set_write_progress(counter.clone());
4098                let ctx = Arc::new(ctx);
4099                let ctx = if confirmed {
4100                    Arc::new(ctx.with_confirmed_writes())
4101                } else {
4102                    ctx
4103                };
4104                let requests = InstantAndNormalInsertRequests {
4105                    normal_requests: RegionInsertRequests {
4106                        requests: [1, 2]
4107                            .map(|region| RegionInsertRequest {
4108                                region_id: RegionId::new(1, region).as_u64(),
4109                                rows: Some(Rows {
4110                                    schema: vec![],
4111                                    rows: vec![Row { values: vec![] }],
4112                                }),
4113                                ..Default::default()
4114                            })
4115                            .to_vec(),
4116                    },
4117                    instant_requests: RegionInsertRequests::default(),
4118                };
4119                let caller =
4120                    tokio::spawn(
4121                        async move { inserter.do_request(requests, &table_infos, &ctx).await },
4122                    );
4123                for _ in 0..2 {
4124                    tokio::time::timeout(Duration::from_secs(5), starts.recv())
4125                        .await
4126                        .unwrap()
4127                        .unwrap();
4128                }
4129                caller.abort();
4130                assert!(caller.await.unwrap_err().is_cancelled());
4131                release.add_permits(2);
4132                // Closing the channel proves the detached dispatcher has finished.
4133                let mut completed = tokio::time::timeout(Duration::from_secs(5), async {
4134                    let mut regions = Vec::new();
4135                    while let Some(region) = completions.recv().await {
4136                        regions.push(region);
4137                    }
4138                    regions
4139                })
4140                .await
4141                .unwrap();
4142                completed.sort_unstable();
4143                assert_eq!(
4144                    completed,
4145                    vec![1, 2],
4146                    "confirmed={confirmed}, retries={max_retries}"
4147                );
4148                assert!(
4149                    starts.try_recv().is_err(),
4150                    "cancelled caller started another retry"
4151                );
4152                assert_eq!(counter.written(), 1);
4153            }
4154        }
4155    }
4156
4157    #[tokio::test]
4158    async fn test_tracked_cancellation_stops_backoff() {
4159        let inserter = batcher_test_inserter().await;
4160        let (started, mut starts) = mpsc::unbounded_channel();
4161        let (completed, mut completions) = mpsc::unbounded_channel();
4162        let node_manager = Arc::new(GatedDatanodeHandler {
4163            started,
4164            completed,
4165            release: Arc::new(Semaphore::new(2)),
4166        });
4167        let dispatcher = WriteDispatcher::new(node_manager, inserter.partition_manager.clone())
4168            .with_retry(
4169                WriteRetryOptions {
4170                    max_retries: 2,
4171                    initial_backoff: Duration::from_secs(60),
4172                    max_backoff: Duration::from_secs(60),
4173                    ..Default::default()
4174                },
4175                inserter.catalog_manager.clone(),
4176                Arc::new(DummyCacheInvalidator),
4177            );
4178        let factory = RegionRequestFactory::new(RegionRequestHeader::default());
4179        let requests = [1, 2]
4180            .into_iter()
4181            .map(|region| TrackedWrite {
4182                request: factory.build_insert(RegionInsertRequests {
4183                    requests: vec![RegionInsertRequest {
4184                        region_id: RegionId::new(1, region).as_u64(),
4185                        ..Default::default()
4186                    }],
4187                }),
4188                owners: vec![(region - 1) as usize],
4189            })
4190            .collect();
4191        let (writes, progress) = dispatcher.prepare_tracked(requests, 2).await;
4192        let cancellation = CancellationToken::new();
4193        let execute = dispatcher.execute_tracked(writes, progress, None, Some(&cancellation));
4194        tokio::pin!(execute);
4195        // Wait for both sends to complete before cancelling the backoff.
4196        tokio::time::timeout(
4197            Duration::from_secs(1),
4198            future::poll_fn(|cx| {
4199                assert!(execute.as_mut().poll(cx).is_pending());
4200                if completions.len() == 2 {
4201                    Poll::Ready(())
4202                } else {
4203                    Poll::Pending
4204                }
4205            }),
4206        )
4207        .await
4208        .unwrap();
4209        for region in [1, 2] {
4210            assert_eq!(starts.try_recv().unwrap(), region);
4211            assert_eq!(completions.try_recv().unwrap(), region);
4212        }
4213        cancellation.cancel();
4214        let progress = tokio::time::timeout(Duration::from_secs(1), execute)
4215            .await
4216            .unwrap();
4217        assert_eq!(progress[0].affected_rows, 1);
4218        assert!(progress[0].error.is_none());
4219        assert_eq!(progress[1].affected_rows, 0);
4220        assert_eq!(
4221            progress[1].error.as_ref().unwrap().retry_hint(),
4222            RetryHint::Retryable
4223        );
4224        assert!(starts.try_recv().is_err());
4225    }
4226
4227    fn test_exemplar_table_info(
4228        id: TableId,
4229        catalog: &str,
4230        schema: &str,
4231        extra_tags: &[&str],
4232        instant: bool,
4233    ) -> TableInfoRef {
4234        use common_query::prelude::greptime_exemplar_labels;
4235        use common_time::ttl::TimeToLive;
4236        use datatypes::schema::{ColumnSchema, Schema};
4237        use table::metadata::{TableInfoBuilder, TableMetaBuilder};
4238
4239        let mut labels_col = ColumnSchema::new(
4240            greptime_exemplar_labels(),
4241            datatypes::data_type::ConcreteDataType::json2(
4242                datatypes::types::json_type::JsonNativeType::Null,
4243            ),
4244            true,
4245        );
4246        labels_col.with_extension_type(&datatypes::extension::json::Json2ExtensionType::new(
4247            Arc::new(datatypes::extension::json::JsonMetadata::new(
4248                datatypes::json::JsonSettings::new_v2(),
4249            )),
4250        ));
4251        let mut columns = vec![
4252            ColumnSchema::new(
4253                DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4254                datatypes::data_type::ConcreteDataType::uint32_datatype(),
4255                false,
4256            ),
4257            ColumnSchema::new(
4258                DATA_SCHEMA_TSID_COLUMN_NAME,
4259                datatypes::data_type::ConcreteDataType::uint64_datatype(),
4260                false,
4261            ),
4262            ColumnSchema::new(
4263                EXEMPLAR_METRIC_COLUMN,
4264                datatypes::data_type::ConcreteDataType::string_datatype(),
4265                true,
4266            ),
4267        ];
4268        for &tag in extra_tags {
4269            columns.push(ColumnSchema::new(
4270                tag,
4271                datatypes::data_type::ConcreteDataType::string_datatype(),
4272                true,
4273            ));
4274        }
4275        let pk_len = columns.len();
4276        columns.push(
4277            ColumnSchema::new(
4278                greptime_timestamp(),
4279                datatypes::data_type::ConcreteDataType::timestamp_nanosecond_datatype(),
4280                false,
4281            )
4282            .with_time_index(true),
4283        );
4284        columns.push(ColumnSchema::new(
4285            greptime_value(),
4286            datatypes::data_type::ConcreteDataType::float64_datatype(),
4287            true,
4288        ));
4289        columns.push(labels_col);
4290        let column_ids: Vec<u32> = std::iter::once(ReservedColumnId::table_id())
4291            .chain(std::iter::once(ReservedColumnId::tsid()))
4292            .chain(10..10 + (columns.len() as u32 - 2))
4293            .collect();
4294        let next_column_id = *column_ids.last().unwrap() + 1;
4295        let mut info = TableInfoBuilder::default()
4296            .table_id(id)
4297            .table_version(0)
4298            .name(METRICS_EXEMPLARS_TABLE)
4299            .catalog_name(catalog)
4300            .schema_name(schema)
4301            .meta(
4302                TableMetaBuilder::empty()
4303                    .schema(Arc::new(Schema::new(columns)))
4304                    .primary_key_indices((0..pk_len).collect())
4305                    .column_ids(column_ids)
4306                    .next_column_id(next_column_id)
4307                    .engine("mito")
4308                    .build()
4309                    .unwrap(),
4310            )
4311            .build()
4312            .unwrap();
4313        info.meta
4314            .options
4315            .extra_options
4316            .insert(APPEND_MODE_KEY.to_string(), "true".to_string());
4317        info.meta.options.extra_options.insert(
4318            store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
4319            "sparse".to_string(),
4320        );
4321        if instant {
4322            info.meta.options.ttl = Some(TimeToLive::Instant);
4323        }
4324        Arc::new(info)
4325    }
4326
4327    async fn register_unpartitioned_table_route(
4328        kv_backend: &common_meta::kv_backend::KvBackendRef,
4329        table_info: &TableInfo,
4330    ) {
4331        common_meta::key::TableMetadataManager::new(kv_backend.clone())
4332            .create_table_metadata(
4333                table_info.clone(),
4334                common_meta::key::table_route::TableRouteValue::physical(vec![
4335                    common_meta::rpc::router::RegionRoute {
4336                        region: common_meta::rpc::router::Region {
4337                            id: RegionId::new(table_info.table_id(), 1),
4338                            name: "r0".to_string(),
4339                            attrs: BTreeMap::new(),
4340                            partition_expr: String::new(),
4341                        },
4342                        leader_peer: Some(common_meta::peer::Peer::new(1, "")),
4343                        follower_peers: vec![],
4344                        leader_state: None,
4345                        leader_down_since: None,
4346                        write_route_policy: None,
4347                    },
4348                ]),
4349                std::collections::HashMap::new(),
4350            )
4351            .await
4352            .unwrap();
4353    }
4354
4355    // Keep global meter registration in one test, isolated by nextest's per-test process.
4356    #[tokio::test]
4357    async fn test_write_meter_admission() {
4358        use std::cell::Cell;
4359        use std::sync::Mutex;
4360        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4361
4362        use api::region::RegionResponse;
4363        use api::v1::region::region_request::Body;
4364        use arrow::array::{Int32Array, TimestampMillisecondArray};
4365        use arrow::record_batch::RecordBatch;
4366        use bytes::Bytes;
4367        use common_error::ext::{ErrorExt, RetryHint};
4368        use common_error::status_code::StatusCode;
4369        use common_grpc::flight::{FlightEncoder, FlightMessage};
4370        use common_meta::ddl::test_util::datanode_handler::DatanodeWatcher;
4371        use futures::future::BoxFuture;
4372        use meter_core::ItemCalculator;
4373        use meter_core::collect::{Collect, WriteRejected};
4374        use meter_core::data::MeterRecord;
4375        use meter_core::global::global_registry;
4376        use session::context::Channel;
4377
4378        const CATALOG: &str = "write_meter_test";
4379
4380        #[derive(Default)]
4381        struct Meter {
4382            reject: AtomicBool,
4383            attempts: Mutex<Vec<MeterRecord>>,
4384            accepted_value: AtomicU64,
4385        }
4386
4387        impl Collect for Meter {
4388            fn on_write(
4389                &self,
4390                record: MeterRecord,
4391            ) -> BoxFuture<'_, std::result::Result<(), WriteRejected>> {
4392                Box::pin(async move {
4393                    if record.catalog != CATALOG {
4394                        return Ok(());
4395                    }
4396                    let value = record.value;
4397                    self.attempts.lock().unwrap().push(record);
4398                    if self.reject.load(Ordering::Relaxed) {
4399                        return Err(WriteRejected::new("database row quota exhausted"));
4400                    }
4401                    self.accepted_value.fetch_add(value, Ordering::Relaxed);
4402                    Ok(())
4403                })
4404            }
4405
4406            fn on_read(&self, _: MeterRecord) {}
4407        }
4408
4409        impl ItemCalculator<InstantAndNormalInsertRequests> for Meter {
4410            fn calc(&self, _: &InstantAndNormalInsertRequests) -> u64 {
4411                17
4412            }
4413        }
4414
4415        let kv_backend = prepare_mocked_backend().await;
4416        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
4417        let (sender, mut dispatched) = tokio::sync::mpsc::channel(16);
4418        let watcher = DatanodeWatcher::new(sender).with_handler(|_, request| {
4419            let rows = match request.body.unwrap() {
4420                Body::Inserts(requests) => requests
4421                    .requests
4422                    .iter()
4423                    .filter_map(|request| request.rows.as_ref())
4424                    .map(|rows| rows.rows.len())
4425                    .sum(),
4426                // The bulk batches below each contain two rows.
4427                Body::BulkInsert(_) => 2,
4428                body => panic!("unexpected request: {body:?}"),
4429            };
4430            Ok(RegionResponse::new(rows))
4431        });
4432        let inserter = Inserter::new(
4433            catalog::memory::MemoryCatalogManager::new(),
4434            partition_manager,
4435            Arc::new(MockDatanodeManager::new(watcher)),
4436            Arc::new(new_table_flownode_set_cache(
4437                String::new(),
4438                Cache::new(100),
4439                kv_backend.clone(),
4440            )),
4441            true,
4442        );
4443        let mut table_info = new_test_table_info(1, "table_1", [1].into_iter());
4444        table_info.catalog_name = CATALOG.to_string();
4445        table_info.schema_name = "target_db".to_string();
4446        let table_info = Arc::new(table_info);
4447        let table_infos = HashMap::from_iter([(1, table_info.clone())]);
4448        let ctx = Arc::new(QueryContext::with_channel(
4449            DEFAULT_CATALOG_NAME,
4450            DEFAULT_SCHEMA_NAME,
4451            Channel::Postgres,
4452        ));
4453        let rows_request = || {
4454            let build = |num_rows| RegionInsertRequests {
4455                requests: vec![RegionInsertRequest {
4456                    region_id: RegionId::new(1, 1).as_u64(),
4457                    rows: Some(Rows {
4458                        schema: vec![],
4459                        rows: vec![api::v1::Row { values: vec![] }; num_rows],
4460                    }),
4461                    ..Default::default()
4462                }],
4463            };
4464            InstantAndNormalInsertRequests {
4465                normal_requests: build(3),
4466                instant_requests: build(2),
4467            }
4468        };
4469
4470        // No collector or calculator: ordinary OSS insertion still succeeds.
4471        let output = inserter
4472            .do_request(rows_request(), &table_infos, &ctx)
4473            .await
4474            .unwrap();
4475        assert_eq!(output.meta.cost, 0);
4476        assert!(matches!(output.data, OutputData::AffectedRows(3)));
4477        dispatched.try_recv().unwrap();
4478
4479        let meter = Arc::new(Meter::default());
4480        global_registry().set_collector(meter.clone());
4481        global_registry().register_calculator(meter.clone());
4482        // The dependency controls noop mode; exercise both builds with this test.
4483        let enabled = Cell::new(false);
4484        write_meter!({
4485            enabled.set(true);
4486            MeterRecord::new("probe".into(), "probe".into(), 0, 0, 0)
4487        })
4488        .await
4489        .unwrap();
4490        let enabled = enabled.get();
4491
4492        let output = inserter
4493            .do_request(rows_request(), &table_infos, &ctx)
4494            .await
4495            .unwrap();
4496        assert_eq!(output.meta.cost, if enabled { 17 } else { 0 });
4497        assert!(matches!(output.data, OutputData::AffectedRows(3)));
4498        dispatched.try_recv().unwrap();
4499        let flow_cache = inserter.table_flownode_set_cache();
4500        assert!(flow_cache.contains_key(&1));
4501        common_meta::cache_invalidator::CacheInvalidator::invalidate_all(flow_cache.as_ref())
4502            .unwrap();
4503        meter.reject.store(true, Ordering::Relaxed);
4504        let result = inserter
4505            .do_request(rows_request(), &table_infos, &ctx)
4506            .await;
4507        if enabled {
4508            let error = result.unwrap_err();
4509            assert_eq!(error.status_code(), StatusCode::RateLimited);
4510            assert_eq!(error.retry_hint(), RetryHint::Retryable);
4511            assert!(error.to_string().contains("database row quota exhausted"));
4512            assert!(dispatched.try_recv().is_err());
4513            assert!(
4514                !flow_cache.contains_key(&1),
4515                "rejected write reached flow mirroring"
4516            );
4517            assert_eq!(meter.accepted_value.load(Ordering::Relaxed), 17);
4518            let attempts = meter.attempts.lock().unwrap();
4519            assert_eq!(attempts.len(), 2);
4520            for record in attempts.iter() {
4521                assert_eq!(record.catalog, CATALOG);
4522                assert_eq!(record.schema, "target_db");
4523                assert_eq!(
4524                    (record.rows, record.value, record.source),
4525                    (5, 17, Channel::Postgres as u8)
4526                );
4527            }
4528        } else {
4529            assert_eq!(result.unwrap().meta.cost, 0);
4530            dispatched.try_recv().unwrap();
4531            assert!(meter.attempts.lock().unwrap().is_empty());
4532        }
4533        meter.attempts.lock().unwrap().clear();
4534
4535        // Rejection must precede queue submission, but conversion memory is reserved first.
4536        if enabled {
4537            let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher {
4538                allow_acquire: true,
4539            });
4540            let rows = Rows {
4541                schema: vec![
4542                    api::v1::helper::tag_column_schema("a", ColumnDataType::Int32),
4543                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
4544                    field_column_schema("b", ColumnDataType::Int32),
4545                ],
4546                rows: vec![api::v1::Row {
4547                    values: vec![
4548                        api::v1::value::ValueData::I32Value(60).into(),
4549                        Value {
4550                            value_data: Some(api::v1::value::ValueData::TimestampMillisecondValue(
4551                                0,
4552                            )),
4553                        },
4554                        api::v1::value::ValueData::I32Value(0).into(),
4555                    ],
4556                }],
4557            };
4558            let error = inserter
4559                .submit_table_rows(
4560                    rows,
4561                    table_info.clone(),
4562                    ctx.skip_wal(),
4563                    ctx.clone(),
4564                    &batcher,
4565                )
4566                .await
4567                .unwrap_err();
4568            assert_eq!(error.status_code(), StatusCode::RateLimited);
4569            let mut attempts = meter.attempts.lock().unwrap();
4570            assert_eq!(attempts.len(), 1);
4571            assert_eq!(attempts[0].catalog, CATALOG);
4572            assert_eq!(attempts[0].schema, "target_db");
4573            assert_eq!(attempts[0].rows, 1);
4574            attempts.clear();
4575        }
4576
4577        let table = Arc::new(table::Table::new(
4578            table_info.clone(),
4579            table::metadata::FilterPushDownType::Unsupported,
4580            Arc::new(DummyDataSource),
4581        ));
4582        let batch = RecordBatch::try_new(
4583            table_info.meta.schema.arrow_schema().clone(),
4584            vec![
4585                Arc::new(Int32Array::from(vec![60, 70])),
4586                Arc::new(TimestampMillisecondArray::from(vec![0, 1])),
4587                Arc::new(Int32Array::from(vec![0, 0])),
4588            ],
4589        )
4590        .unwrap();
4591        let bulk_insert = |batch: RecordBatch| {
4592            let flight_data = FlightEncoder::default()
4593                .encode(FlightMessage::RecordBatch(batch.clone()))
4594                .into_iter()
4595                .next()
4596                .unwrap();
4597            inserter.handle_bulk_insert(
4598                table.clone(),
4599                flight_data,
4600                batch,
4601                Bytes::new(),
4602                false,
4603                Channel::Grpc,
4604            )
4605        };
4606        // Empty batches bypass admission even while the collector rejects.
4607        assert_eq!(bulk_insert(batch.slice(0, 0)).await.unwrap(), 0);
4608        assert!(meter.attempts.lock().unwrap().is_empty());
4609        assert!(dispatched.try_recv().is_err());
4610
4611        // A collector change between batches takes effect on the very next batch.
4612        for reject in [false, true, false] {
4613            meter.reject.store(reject, Ordering::Relaxed);
4614            let result = bulk_insert(batch.clone()).await;
4615            if enabled && reject {
4616                let error = result.unwrap_err();
4617                assert_eq!(error.status_code(), StatusCode::RateLimited);
4618                assert_eq!(error.retry_hint(), RetryHint::Retryable);
4619                assert!(dispatched.try_recv().is_err());
4620            } else {
4621                assert_eq!(result.unwrap(), 2);
4622                dispatched.try_recv().unwrap();
4623            }
4624        }
4625        {
4626            let attempts = meter.attempts.lock().unwrap();
4627            assert_eq!(attempts.len(), if enabled { 3 } else { 0 });
4628            for record in attempts.iter() {
4629                assert_eq!(record.catalog, CATALOG);
4630                assert_eq!(record.schema, "target_db");
4631                assert_eq!(
4632                    (record.rows, record.value, record.source),
4633                    (2, 0, Channel::Grpc as u8)
4634                );
4635            }
4636        }
4637        assert_eq!(
4638            meter.accepted_value.load(Ordering::Relaxed),
4639            if enabled { 17 } else { 0 }
4640        );
4641
4642        // Aggregate repeated database targets and retain admission across nested
4643        // batching without changing the caller's reusable context.
4644        meter.attempts.lock().unwrap().clear();
4645        let original = Arc::new(QueryContext::with_channel(
4646            CATALOG,
4647            "a",
4648            Channel::Prometheus,
4649        ));
4650        let mut batches = ["a", "b", "a"].map(|schema| {
4651            let ctx = if schema == "a" {
4652                original.clone()
4653            } else {
4654                Arc::new(QueryContext::with_channel(
4655                    CATALOG,
4656                    schema,
4657                    Channel::Prometheus,
4658                ))
4659            };
4660            (
4661                ctx,
4662                RowInsertRequests {
4663                    inserts: vec![RowInsertRequest {
4664                        table_name: "data".into(),
4665                        rows: Some(Rows {
4666                            schema: vec![],
4667                            rows: vec![api::v1::Row::default(); 2],
4668                        }),
4669                    }],
4670                },
4671            )
4672        });
4673        admit_row_insert_batches(&mut batches).await.unwrap();
4674        admit_row_insert_batches(&mut batches).await.unwrap();
4675        assert_eq!(original.write_rows_to_admit(CATALOG, "a", 4), 4);
4676        for (ctx, _) in &batches {
4677            assert_eq!(
4678                ctx.write_rows_to_admit(CATALOG, &ctx.current_schema(), 2),
4679                0
4680            );
4681            assert_eq!(ctx.channel(), Channel::Prometheus);
4682        }
4683        {
4684            let attempts = meter.attempts.lock().unwrap();
4685            let totals = attempts
4686                .iter()
4687                .map(|r| (r.schema.as_str(), r.rows, r.value))
4688                .collect::<Vec<_>>();
4689            assert_eq!(
4690                totals,
4691                if enabled {
4692                    vec![("a", 4, 0), ("b", 2, 0)]
4693                } else {
4694                    vec![]
4695                }
4696            );
4697        }
4698        meter.attempts.lock().unwrap().clear();
4699        meter.reject.store(false, Ordering::Relaxed);
4700        let ctx = Arc::new(QueryContext::with_channel(
4701            CATALOG,
4702            "logical",
4703            Channel::Otlp,
4704        ));
4705        let admitted = admit_write(2, &ctx).await.unwrap();
4706        let mut requests = RowInsertRequests {
4707            inserts: vec![RowInsertRequest {
4708                table_name: "metric".to_string(),
4709                rows: Some(Rows {
4710                    schema: vec![],
4711                    rows: vec![api::v1::Row::default(); 2],
4712                }),
4713            }],
4714        };
4715        let original = requests.clone();
4716        let cost = Inserter::meter_row_inserts(&mut requests, &admitted)
4717            .await
4718            .unwrap();
4719        assert_eq!(cost, if enabled { 17 } else { 0 });
4720        assert_eq!(requests, original);
4721        let records = meter
4722            .attempts
4723            .lock()
4724            .unwrap()
4725            .iter()
4726            .map(|record| (record.rows, record.value))
4727            .collect::<Vec<_>>();
4728        assert_eq!(
4729            records,
4730            if enabled {
4731                vec![(2, 0), (0, 17)]
4732            } else {
4733                vec![]
4734            }
4735        );
4736        meter.reject.store(true, Ordering::Relaxed);
4737        let result = Inserter::meter_row_inserts(&mut requests, &admitted).await;
4738        if enabled {
4739            assert_eq!(result.unwrap_err().status_code(), StatusCode::RateLimited);
4740        } else {
4741            assert_eq!(result.unwrap(), 0);
4742        }
4743        assert_eq!(requests, original);
4744
4745        // Verify direct sparse writes and exemplar writes meter through `InstantAndNormalInsertRequests`.
4746        {
4747            use datatypes::schema::{ColumnSchema, Schema};
4748
4749            meter.attempts.lock().unwrap().clear();
4750            meter.reject.store(false, Ordering::Relaxed);
4751
4752            let mut sparse_info = new_test_table_info(10, "table_10", [1].into_iter());
4753            sparse_info.catalog_name = CATALOG.to_string();
4754            sparse_info.schema_name = "target_db".to_string();
4755            sparse_info.meta.engine = default_engine().to_string();
4756            sparse_info.meta.schema = Arc::new(Schema::new(vec![
4757                ColumnSchema::new(
4758                    DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4759                    datatypes::data_type::ConcreteDataType::uint32_datatype(),
4760                    false,
4761                ),
4762                ColumnSchema::new(
4763                    DATA_SCHEMA_TSID_COLUMN_NAME,
4764                    datatypes::data_type::ConcreteDataType::uint64_datatype(),
4765                    false,
4766                ),
4767                ColumnSchema::new(
4768                    "ts",
4769                    datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(),
4770                    false,
4771                )
4772                .with_time_index(true),
4773                ColumnSchema::new(
4774                    "val",
4775                    datatypes::data_type::ConcreteDataType::float64_datatype(),
4776                    true,
4777                ),
4778            ]));
4779            sparse_info.meta.primary_key_indices = vec![0, 1];
4780            sparse_info.meta.column_ids =
4781                vec![ReservedColumnId::table_id(), ReservedColumnId::tsid(), 2, 3];
4782            sparse_info.meta.options.extra_options.insert(
4783                store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(),
4784                "sparse".to_string(),
4785            );
4786            let sparse_info = Arc::new(sparse_info);
4787            register_unpartitioned_table_route(&kv_backend, &sparse_info).await;
4788            let sparse_rows = Rows {
4789                schema: vec![
4790                    api::v1::helper::tag_column_schema(
4791                        DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
4792                        ColumnDataType::Uint32,
4793                    ),
4794                    api::v1::helper::tag_column_schema(
4795                        DATA_SCHEMA_TSID_COLUMN_NAME,
4796                        ColumnDataType::Uint64,
4797                    ),
4798                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
4799                    field_column_schema("val", ColumnDataType::Float64),
4800                ],
4801                rows: vec![
4802                    api::v1::Row {
4803                        values: vec![
4804                            ValueData::U32Value(10).into(),
4805                            ValueData::U64Value(20).into(),
4806                            ValueData::TimestampMillisecondValue(1).into(),
4807                            ValueData::F64Value(1.5).into(),
4808                        ],
4809                    },
4810                    api::v1::Row {
4811                        values: vec![
4812                            ValueData::U32Value(10).into(),
4813                            ValueData::U64Value(21).into(),
4814                            ValueData::TimestampMillisecondValue(2).into(),
4815                            ValueData::F64Value(2.5).into(),
4816                        ],
4817                    },
4818                ],
4819            };
4820            let sparse_ctx = Arc::new(QueryContext::with_channel(
4821                CATALOG,
4822                "target_db",
4823                Channel::Postgres,
4824            ));
4825            let mixed = RowInsertRequests {
4826                inserts: vec![
4827                    RowInsertRequest {
4828                        table_name: sparse_info.name.clone(),
4829                        rows: Some(sparse_rows.clone()),
4830                    },
4831                    RowInsertRequest {
4832                        table_name: table_info.name.clone(),
4833                        rows: Some(Rows {
4834                            schema: vec![api::v1::helper::tag_column_schema(
4835                                "a",
4836                                ColumnDataType::Int32,
4837                            )],
4838                            rows: [1, 11, 101]
4839                                .into_iter()
4840                                .map(|a| Row {
4841                                    values: vec![ValueData::I32Value(a).into()],
4842                                })
4843                                .collect(),
4844                        }),
4845                    },
4846                ],
4847            };
4848            let infos = HashMap::from_iter([
4849                (sparse_info.table_id(), sparse_info.clone()),
4850                (table_info.table_id(), table_info.clone()),
4851            ]);
4852            for confirmed in [false, true] {
4853                for skip_wal in [false, true] {
4854                    let ctx = Arc::new(if confirmed {
4855                        sparse_ctx.with_confirmed_writes()
4856                    } else {
4857                        sparse_ctx.fork()
4858                    });
4859                    ctx.set_skip_wal(!skip_wal);
4860                    let out = inserter
4861                        .dispatch_direct_sparse_row_inserts(
4862                            mixed.clone(),
4863                            infos.clone(),
4864                            HashSet::new(),
4865                            skip_wal,
4866                            &ctx,
4867                        )
4868                        .await
4869                        .unwrap();
4870                    assert!(matches!(out.data, OutputData::AffectedRows(5)));
4871                    assert_eq!(out.meta.cost, if enabled { 17 } else { 0 });
4872                    let records = std::mem::take(&mut *meter.attempts.lock().unwrap());
4873                    assert_eq!(records.len(), usize::from(enabled));
4874                    if enabled {
4875                        assert_eq!((records[0].rows, records[0].value), (5, 17));
4876                    }
4877
4878                    let mut bulk_requests = 0;
4879                    let mut dense_rows = 0;
4880                    while let Ok((_, request)) = dispatched.try_recv() {
4881                        match request.body.unwrap() {
4882                            Body::BulkInsert(bulk) => {
4883                                assert_eq!(
4884                                    RegionId::from_u64(bulk.region_id).table_id(),
4885                                    sparse_info.table_id()
4886                                );
4887                                assert_eq!(bulk.skip_wal, skip_wal);
4888                                bulk_requests += 1;
4889                            }
4890                            Body::Inserts(inserts) => {
4891                                for insert in inserts.requests {
4892                                    assert_eq!(
4893                                        RegionId::from_u64(insert.region_id).table_id(),
4894                                        table_info.table_id()
4895                                    );
4896                                    assert_eq!(insert.skip_wal, skip_wal);
4897                                    dense_rows += insert.rows.unwrap().rows.len();
4898                                }
4899                            }
4900                            body => panic!("unexpected request: {body:?}"),
4901                        }
4902                    }
4903                    assert_eq!((bulk_requests, dense_rows), (1, 3));
4904                }
4905            }
4906
4907            meter.reject.store(true, Ordering::Relaxed);
4908            let err_or_ok = inserter
4909                .dispatch_single_sparse_table_rows(sparse_rows, sparse_info, false, &sparse_ctx)
4910                .await;
4911            if enabled {
4912                assert_eq!(
4913                    err_or_ok.unwrap_err().status_code(),
4914                    StatusCode::RateLimited
4915                );
4916                assert!(dispatched.try_recv().is_err());
4917            } else {
4918                assert_eq!(err_or_ok.unwrap().meta.cost, 0);
4919                dispatched.try_recv().unwrap();
4920            }
4921
4922            // Exemplar batch WCU metering.
4923            meter.attempts.lock().unwrap().clear();
4924            meter.reject.store(false, Ordering::Relaxed);
4925            let exemplar_info = test_exemplar_table_info(11, CATALOG, "target_db", &[], false);
4926            register_unpartitioned_table_route(&kv_backend, &exemplar_info).await;
4927            let ex_batch = ExemplarBatch::try_new(vec![
4928                Exemplar {
4929                    metric: "cpu".into(),
4930                    series_labels: BTreeMap::new().into(),
4931                    timestamp: 1_000,
4932                    value: 1.0,
4933                    labels: BTreeMap::new(),
4934                },
4935                Exemplar {
4936                    metric: "cpu".into(),
4937                    series_labels: BTreeMap::new().into(),
4938                    timestamp: 2_000,
4939                    value: 2.0,
4940                    labels: BTreeMap::new(),
4941                },
4942            ])
4943            .unwrap();
4944            let resolved = HashMap::from_iter([("cpu".to_string(), 100)]);
4945            let ex_ctx = Arc::new(QueryContext::with_channel(
4946                CATALOG,
4947                "target_db",
4948                Channel::Otlp,
4949            ));
4950            let ex_out = inserter
4951                .execute_exemplar_write(
4952                    ex_batch.clone(),
4953                    resolved.clone(),
4954                    exemplar_info.clone(),
4955                    false,
4956                    ex_ctx.clone(),
4957                )
4958                .await
4959                .unwrap();
4960            assert_eq!(ex_out.meta.cost, if enabled { 17 } else { 0 });
4961            dispatched.try_recv().unwrap();
4962            {
4963                let attempts = meter.attempts.lock().unwrap();
4964                assert_eq!(attempts.len(), if enabled { 1 } else { 0 });
4965                if enabled {
4966                    assert_eq!((attempts[0].rows, attempts[0].value), (2, 17));
4967                }
4968            }
4969            meter.reject.store(true, Ordering::Relaxed);
4970            let rejected = inserter
4971                .execute_exemplar_write(ex_batch, resolved, exemplar_info, false, ex_ctx)
4972                .await;
4973            if enabled {
4974                assert_eq!(rejected.unwrap_err().status_code(), StatusCode::RateLimited);
4975                assert!(dispatched.try_recv().is_err());
4976            } else {
4977                assert_eq!(rejected.unwrap().meta.cost, 0);
4978                dispatched.try_recv().unwrap();
4979            }
4980        }
4981    }
4982
4983    #[test]
4984    fn test_trace_create_options_copy_compaction_hints() {
4985        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
4986        ctx.set_extension("compaction.twcs.time_window", "1h");
4987        ctx.set_extension("compaction.twcs.max_output_file_size", "256MB");
4988        ctx.set_extension("compaction.twcs.remote_compaction", "true");
4989        ctx.set_extension("compaction.unknown", "ignored");
4990        let ctx = Arc::new(ctx);
4991        let mut table_options = Default::default();
4992
4993        fill_table_options_for_create(
4994            &mut table_options,
4995            &AutoCreateTableType::Trace {
4996                alter_existing: true,
4997            },
4998            &ctx,
4999        );
5000
5001        assert_eq!(
5002            Some("twcs"),
5003            table_options.get(COMPACTION_TYPE).map(String::as_str)
5004        );
5005        assert_eq!(
5006            Some("1h"),
5007            table_options
5008                .get("compaction.twcs.time_window")
5009                .map(String::as_str)
5010        );
5011        assert_eq!(
5012            Some("256MB"),
5013            table_options
5014                .get("compaction.twcs.max_output_file_size")
5015                .map(String::as_str)
5016        );
5017        assert_eq!(
5018            Some("true"),
5019            table_options
5020                .get("compaction.twcs.remote_compaction")
5021                .map(String::as_str)
5022        );
5023        assert!(!table_options.contains_key("compaction.unknown"));
5024    }
5025
5026    #[test]
5027    fn test_exemplar_create_options_isolate_metric_context() {
5028        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5029        for (key, value) in [
5030            (APPEND_MODE_KEY, "false"),
5031            (MERGE_MODE_KEY, "last_non_null"),
5032            (PHYSICAL_TABLE_METADATA_KEY, "true"),
5033            (LOGICAL_TABLE_METADATA_KEY, "physical_metrics"),
5034            ("otlp_metric_compat", "prometheus"),
5035            (table::requests::SEMANTIC_SIGNAL_TYPE, "metric"),
5036            (SEMANTIC_PER_TABLE_INDEX_KEY, "{}"),
5037            ("ttl", "7d"),
5038            ("compaction.twcs.time_window", "1h"),
5039        ] {
5040            ctx.set_extension(key, value);
5041        }
5042        let mut options = Default::default();
5043        fill_table_options_for_create(&mut options, &AutoCreateTableType::Exemplar, &Arc::new(ctx));
5044        assert_eq!(
5045            options,
5046            std::collections::HashMap::from([
5047                (APPEND_MODE_KEY.into(), "true".into()),
5048                (
5049                    store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.into(),
5050                    "sparse".into()
5051                ),
5052                ("ttl".into(), "7d".into()),
5053                (COMPACTION_TYPE.into(), "twcs".into()),
5054                ("compaction.twcs.time_window".into(), "1h".into()),
5055            ])
5056        );
5057    }
5058
5059    #[test]
5060    fn test_skip_wal_does_not_change_table_options() {
5061        check_skip_wal_does_not_change_table_options(false);
5062        check_skip_wal_does_not_change_table_options(true);
5063    }
5064
5065    fn check_skip_wal_does_not_change_table_options(skip_wal: bool) {
5066        let ctx = Arc::new(QueryContext::with(
5067            DEFAULT_CATALOG_NAME,
5068            DEFAULT_SCHEMA_NAME,
5069        ));
5070        ctx.set_skip_wal(skip_wal);
5071        let mut options = Default::default();
5072        fill_table_options_for_create(&mut options, &AutoCreateTableType::Physical, &ctx);
5073        assert!(!options.contains_key(session::hints::INSERT_SKIP_WAL_HINT));
5074        assert!(!options.contains_key("skip_wal"));
5075    }
5076
5077    #[test]
5078    fn test_last_non_null_create_options_preserve_default_without_append_mode() {
5079        let ctx = Arc::new(QueryContext::with(
5080            DEFAULT_CATALOG_NAME,
5081            DEFAULT_SCHEMA_NAME,
5082        ));
5083        let mut table_options = Default::default();
5084
5085        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5086
5087        assert_eq!(
5088            Some("last_non_null"),
5089            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5090        );
5091        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5092    }
5093
5094    #[test]
5095    fn test_fill_table_options_copies_semantic_extensions() {
5096        use table::requests::{
5097            SEMANTIC_METRIC_TYPE, SEMANTIC_PER_TABLE_INDEX_KEY, SEMANTIC_SIGNAL_TYPE,
5098            SEMANTIC_SOURCE, SEMANTIC_SOURCE_VERSION, SIGNAL_TYPE_METRIC, SOURCE_OPENTELEMETRY,
5099        };
5100
5101        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5102        ctx.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC);
5103        ctx.set_extension(SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY);
5104        ctx.set_extension(SEMANTIC_SOURCE_VERSION, "2.0");
5105        ctx.set_extension(SEMANTIC_METRIC_TYPE, "bogus");
5106        // The internal transport key must NOT be copied into table options.
5107        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, "{}");
5108        let ctx = Arc::new(ctx);
5109        let mut table_options = Default::default();
5110
5111        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::Physical, &ctx);
5112
5113        assert_eq!(
5114            Some(SIGNAL_TYPE_METRIC),
5115            table_options.get(SEMANTIC_SIGNAL_TYPE).map(String::as_str)
5116        );
5117        assert_eq!(
5118            Some(SOURCE_OPENTELEMETRY),
5119            table_options.get(SEMANTIC_SOURCE).map(String::as_str)
5120        );
5121        assert_eq!(
5122            Some("2.0"),
5123            table_options
5124                .get(SEMANTIC_SOURCE_VERSION)
5125                .map(String::as_str)
5126        );
5127        assert!(!table_options.contains_key(SEMANTIC_METRIC_TYPE));
5128        assert!(!table_options.contains_key(SEMANTIC_PER_TABLE_INDEX_KEY));
5129    }
5130
5131    #[test]
5132    fn test_apply_retention_ttl_hint_copies_only_retention_ttl() {
5133        let mut instant_ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5134        instant_ctx.set_extension(TTL_KEY, "instant");
5135        instant_ctx.set_extension(APPEND_MODE_KEY, "true");
5136        let instant_ctx = Arc::new(instant_ctx);
5137        let mut instant_options = std::collections::HashMap::new();
5138        apply_retention_ttl_hint(&mut instant_options, &instant_ctx);
5139        assert!(instant_options.is_empty());
5140
5141        let mut retention_ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5142        retention_ctx.set_extension(TTL_KEY, "7d");
5143        retention_ctx.set_extension(APPEND_MODE_KEY, "true");
5144        let retention_ctx = Arc::new(retention_ctx);
5145        let mut retention_options = std::collections::HashMap::new();
5146        apply_retention_ttl_hint(&mut retention_options, &retention_ctx);
5147        assert_eq!(
5148            retention_options.get(TTL_KEY).map(String::as_str),
5149            Some("7d")
5150        );
5151        assert!(!retention_options.contains_key(APPEND_MODE_KEY));
5152    }
5153
5154    #[test]
5155    fn test_apply_per_table_semantic_options() {
5156        use table::requests::{
5157            SEMANTIC_METRIC_TYPE, SEMANTIC_METRIC_UNIT, SEMANTIC_PER_TABLE_INDEX_KEY,
5158        };
5159
5160        let index = format!(
5161            r#"{{
5162            "{DEFAULT_SCHEMA_NAME}": {{
5163                "http_requests_total": {{
5164                    "greptime.semantic.metric.type": "counter",
5165                    "greptime.semantic.metric.unit": "By",
5166                    "greptime.semantic.metric.type_BOGUS": "x"
5167                }},
5168                "other_table": {{
5169                    "greptime.semantic.metric.type": "gauge"
5170                }}
5171            }},
5172            "other_schema": {{
5173                "http_requests_total": {{
5174                    "greptime.semantic.metric.type": "gauge"
5175                }}
5176            }}
5177        }}"#
5178        );
5179        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5180        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, index);
5181        let ctx = Arc::new(ctx);
5182
5183        let index = parse_per_table_semantic_index(&ctx);
5184        assert!(index.is_some());
5185        let index = index.as_ref();
5186
5187        let mut table_options = std::collections::HashMap::new();
5188        apply_per_table_semantic_options(
5189            &mut table_options,
5190            index,
5191            DEFAULT_SCHEMA_NAME,
5192            "http_requests_total",
5193        );
5194        // The write schema's entry applies — not other_schema's `gauge`.
5195        assert_eq!(
5196            table_options.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
5197            Some("counter")
5198        );
5199        assert_eq!(
5200            table_options.get(SEMANTIC_METRIC_UNIT).map(String::as_str),
5201            Some("By")
5202        );
5203        // The unknown key is rejected by the vocabulary check; other tables' keys
5204        // never appear.
5205        assert!(!table_options.contains_key("greptime.semantic.metric.type_BOGUS"));
5206        assert_eq!(table_options.len(), 2);
5207
5208        let mut empty = std::collections::HashMap::new();
5209        apply_per_table_semantic_options(&mut empty, index, DEFAULT_SCHEMA_NAME, "not_in_index");
5210        assert!(empty.is_empty());
5211
5212        // A schema with no entry is a no-op even when the table name matches
5213        // elsewhere.
5214        let mut opts = std::collections::HashMap::new();
5215        apply_per_table_semantic_options(
5216            &mut opts,
5217            index,
5218            "schema_without_entry",
5219            "http_requests_total",
5220        );
5221        assert!(opts.is_empty());
5222
5223        // No extension at all parses to no index (e.g. logs / Prom RW v1).
5224        let bare = Arc::new(QueryContext::with(
5225            DEFAULT_CATALOG_NAME,
5226            DEFAULT_SCHEMA_NAME,
5227        ));
5228        assert!(parse_per_table_semantic_index(&bare).is_none());
5229        let mut opts = std::collections::HashMap::new();
5230        apply_per_table_semantic_options(
5231            &mut opts,
5232            None,
5233            DEFAULT_SCHEMA_NAME,
5234            "http_requests_total",
5235        );
5236        assert!(opts.is_empty());
5237    }
5238
5239    #[test]
5240    fn test_last_non_null_create_options_preserve_default_with_append_mode_false() {
5241        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5242        ctx.set_extension(APPEND_MODE_KEY, "false");
5243        let ctx = Arc::new(ctx);
5244        let mut table_options = Default::default();
5245
5246        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5247
5248        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5249        assert_eq!(
5250            Some("last_non_null"),
5251            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5252        );
5253    }
5254
5255    #[test]
5256    fn test_last_non_null_create_options_use_configured_merge_mode() {
5257        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5258        ctx.set_extension(MERGE_MODE_KEY, "last_row");
5259        let ctx = Arc::new(ctx);
5260        let mut table_options = Default::default();
5261
5262        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5263
5264        assert_eq!(
5265            Some("last_row"),
5266            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5267        );
5268        assert!(!table_options.contains_key(APPEND_MODE_KEY));
5269    }
5270
5271    #[test]
5272    fn test_last_non_null_create_options_use_last_row_with_append_mode_true() {
5273        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
5274        ctx.set_extension(APPEND_MODE_KEY, "true");
5275        let ctx = Arc::new(ctx);
5276        let mut table_options = Default::default();
5277
5278        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
5279
5280        assert_eq!(
5281            Some("true"),
5282            table_options.get(APPEND_MODE_KEY).map(String::as_str)
5283        );
5284        assert_eq!(
5285            Some("last_row"),
5286            table_options.get(MERGE_MODE_KEY).map(String::as_str)
5287        );
5288    }
5289
5290    #[derive(Default)]
5291    struct UnexpectedBatcher {
5292        allow_acquire: bool,
5293    }
5294
5295    #[async_trait::async_trait]
5296    impl PendingRowsBatcher for UnexpectedBatcher {
5297        async fn acquire(&self, _: usize, _: u64) -> Result<crate::batcher::PendingRowsPermit> {
5298            assert!(
5299                self.allow_acquire,
5300                "empty writes must not acquire batch admission"
5301            );
5302            Ok(Arc::new(()))
5303        }
5304
5305        async fn submit(
5306            &self,
5307            _table_info: TableInfoRef,
5308            _batch: arrow::record_batch::RecordBatch,
5309            _ctx: QueryContextRef,
5310            _permit: crate::batcher::PendingRowsPermit,
5311        ) -> Result<Output> {
5312            panic!("writes must not submit a batch")
5313        }
5314    }
5315
5316    async fn batcher_test_inserter() -> Inserter {
5317        let kv_backend = prepare_mocked_backend().await;
5318        Inserter::new(
5319            catalog::memory::MemoryCatalogManager::new(),
5320            create_partition_rule_manager(kv_backend.clone()).await,
5321            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5322            Arc::new(new_table_flownode_set_cache(
5323                String::new(),
5324                Cache::new(100),
5325                kv_backend,
5326            )),
5327            true,
5328        )
5329    }
5330
5331    #[tokio::test]
5332    async fn test_logical_batcher_eligibility() {
5333        use catalog::RegisterTableRequest;
5334        use catalog::memory::MemoryCatalogManager;
5335        use common_meta::kv_backend::KvBackendRef;
5336        use common_meta::kv_backend::memory::MemoryKvBackend;
5337        use datatypes::schema::{ColumnDefaultConstraint, SchemaBuilder};
5338        let requests = RowInsertRequests {
5339            inserts: vec![RowInsertRequest {
5340                table_name: "test_table".to_string(),
5341                rows: None,
5342            }],
5343        };
5344        let original =
5345            make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5346                .table_info();
5347        for case in [
5348            "eligible",
5349            "physical",
5350            "ordinary",
5351            "instant",
5352            "disabled",
5353            "hint",
5354            "flow",
5355            "required_tag",
5356            "default",
5357        ] {
5358            let mut info = (*original).clone();
5359            info.meta.engine = METRIC_ENGINE_NAME.to_string();
5360            info.meta.options.extra_options.insert(
5361                LOGICAL_TABLE_METADATA_KEY.to_string(),
5362                "physical".to_string(),
5363            );
5364            let mut ctx = QueryContext::arc().fork();
5365            match case {
5366                "physical" => {
5367                    info.meta
5368                        .options
5369                        .extra_options
5370                        .insert(LOGICAL_TABLE_METADATA_KEY.to_string(), "other".to_string());
5371                }
5372                "ordinary" => info.meta.engine = "mito".to_string(),
5373                "instant" => info.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant),
5374                "hint" => ctx.set_extension(AUTO_CREATE_TABLE_KEY, "false"),
5375                "required_tag" | "default" => {
5376                    let mut columns = info.meta.schema.column_schemas().to_vec();
5377                    let mut tag = ColumnSchema::new(
5378                        "tag",
5379                        ConcreteDataType::string_datatype(),
5380                        case != "required_tag",
5381                    );
5382                    if case == "default" {
5383                        tag = tag
5384                            .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
5385                            .unwrap();
5386                    }
5387                    columns.push(tag);
5388                    info.meta.schema = Arc::new(
5389                        SchemaBuilder::try_from_columns(columns)
5390                            .unwrap()
5391                            .build()
5392                            .unwrap(),
5393                    );
5394                    info.meta.primary_key_indices = vec![2];
5395                }
5396                _ => {}
5397            }
5398            let catalog = MemoryCatalogManager::with_default_setup();
5399            let table = Arc::new(table::Table::new(
5400                Arc::new(info),
5401                table::metadata::FilterPushDownType::Unsupported,
5402                Arc::new(DummyDataSource),
5403            ));
5404            catalog
5405                .register_table_sync(RegisterTableRequest {
5406                    catalog: DEFAULT_CATALOG_NAME.to_string(),
5407                    schema: DEFAULT_SCHEMA_NAME.to_string(),
5408                    table_name: "test_table".to_string(),
5409                    table_id: 1,
5410                    table,
5411                })
5412                .unwrap();
5413            let mut inserter = batcher_test_inserter().await;
5414            inserter.catalog_manager = catalog;
5415            inserter.auto_create_table = case != "disabled";
5416            let kv_backend: KvBackendRef = Arc::new(MemoryKvBackend::default());
5417            inserter.table_flownode_set_cache = Arc::new(new_table_flownode_set_cache(
5418                String::new(),
5419                Cache::new(10),
5420                kv_backend,
5421            ));
5422            if case == "flow" {
5423                cache_test_flow(
5424                    &inserter.table_flownode_set_cache,
5425                    CreateFlow {
5426                        flow_id: 1,
5427                        source_table_ids: vec![1],
5428                        partition_to_peer_mapping: vec![(0, Peer::empty(1))],
5429                    },
5430                )
5431                .await;
5432            }
5433            assert_eq!(
5434                inserter
5435                    .can_batch_metric_rows(&requests, &Arc::new(ctx), "physical")
5436                    .await
5437                    .unwrap(),
5438                case == "eligible",
5439                "{case}"
5440            );
5441        }
5442    }
5443
5444    #[tokio::test]
5445    async fn test_batcher_meter_preserves_request() {
5446        let mut requests = RowInsertRequests {
5447            inserts: vec![RowInsertRequest {
5448                table_name: "sample".to_string(),
5449                rows: Some(Rows {
5450                    schema: vec![],
5451                    rows: vec![api::v1::Row {
5452                        values: vec![Value {
5453                            value_data: Some(api::v1::value::ValueData::F64Value(1.5)),
5454                        }],
5455                    }],
5456                }),
5457            }],
5458        };
5459        let expected = requests.clone();
5460        Inserter::meter_row_inserts(&mut requests, &QueryContext::arc())
5461            .await
5462            .unwrap();
5463        assert_eq!(requests, expected);
5464    }
5465
5466    #[tokio::test]
5467    async fn test_instant_table_bypasses_batcher() {
5468        let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher::default());
5469        let inserter = batcher_test_inserter()
5470            .await
5471            .with_pending_rows_batcher(Some(batcher));
5472        let mut ctx = session::context::QueryContextBuilder::default().build();
5473        ctx.set_batching_enabled(true);
5474        let ctx = Arc::new(ctx);
5475        let table = make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5476            .table_info();
5477        assert!(inserter.table_batcher(&table, &ctx).is_some());
5478        let mut instant = (*table).clone();
5479        instant.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant);
5480        assert!(inserter.table_batcher(&Arc::new(instant), &ctx).is_none());
5481    }
5482
5483    #[tokio::test]
5484    async fn test_empty_prepared_rows_skip_batcher() {
5485        let inserter = batcher_test_inserter().await;
5486        let table = make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype())
5487            .table_info();
5488        let batcher: Arc<dyn PendingRowsBatcher> = Arc::new(UnexpectedBatcher::default());
5489        let ctx = QueryContext::arc();
5490        let output = inserter
5491            .submit_table_rows(
5492                Rows {
5493                    schema: vec![],
5494                    rows: vec![],
5495                },
5496                table.clone(),
5497                ctx.skip_wal(),
5498                ctx.clone(),
5499                &batcher,
5500            )
5501            .await
5502            .unwrap();
5503        assert!(matches!(output.data, OutputData::AffectedRows(0)));
5504        let output = inserter
5505            .submit_pending_rows(
5506                RowInsertRequests {
5507                    inserts: vec![RowInsertRequest {
5508                        table_name: table.name.clone(),
5509                        rows: None,
5510                    }],
5511                },
5512                HashMap::from_iter([(table.table_id(), table)]),
5513                ctx.skip_wal(),
5514                ctx,
5515                &batcher,
5516            )
5517            .await
5518            .unwrap();
5519        assert!(matches!(output.data, OutputData::AffectedRows(0)));
5520    }
5521
5522    /// Flownode handler that keeps mirror inserts in flight until the test
5523    /// releases the gate, so the pending mirror budget can be observed
5524    /// deterministically.
5525    #[derive(Clone)]
5526    struct GatedFlownodeHandler {
5527        gate: Arc<tokio::sync::Semaphore>,
5528        affected_rows: u64,
5529    }
5530
5531    #[async_trait::async_trait]
5532    impl MockFlownodeHandler for GatedFlownodeHandler {
5533        async fn handle_inserts(
5534            &self,
5535            _peer: &Peer,
5536            _requests: api::v1::region::InsertRequests,
5537        ) -> common_meta::error::Result<FlowResponse> {
5538            let _permit = self.gate.acquire().await.unwrap();
5539            Ok(FlowResponse {
5540                affected_rows: self.affected_rows,
5541                ..Default::default()
5542            })
5543        }
5544    }
5545
5546    fn flownode_peer() -> Peer {
5547        Peer {
5548            id: 1,
5549            addr: "127.0.0.1:4001".to_string(),
5550        }
5551    }
5552
5553    #[derive(Clone)]
5554    struct RecordingNodeManager {
5555        datanode_dispatch: tokio::sync::mpsc::UnboundedSender<usize>,
5556        flownode_dispatch: mpsc::UnboundedSender<(Peer, RegionInsertRequests)>,
5557        gates: Arc<std::sync::Mutex<HashMap<u64, Arc<tokio::sync::Semaphore>>>>,
5558        fail_flownode: bool,
5559    }
5560
5561    #[async_trait::async_trait]
5562    impl common_meta::node_manager::DatanodeManager for RecordingNodeManager {
5563        async fn datanode(&self, peer: &Peer) -> common_meta::node_manager::DatanodeRef {
5564            Arc::new(RecordingNode {
5565                peer: peer.clone(),
5566                manager: self.clone(),
5567            })
5568        }
5569    }
5570
5571    #[async_trait::async_trait]
5572    impl common_meta::node_manager::FlownodeManager for RecordingNodeManager {
5573        async fn flownode(&self, peer: &Peer) -> common_meta::node_manager::FlownodeRef {
5574            Arc::new(RecordingNode {
5575                peer: peer.clone(),
5576                manager: self.clone(),
5577            })
5578        }
5579    }
5580
5581    struct RecordingNode {
5582        peer: Peer,
5583        manager: RecordingNodeManager,
5584    }
5585
5586    #[async_trait::async_trait]
5587    impl common_meta::node_manager::Datanode for RecordingNode {
5588        async fn handle_request(
5589            &self,
5590            _request: Arc<api::v1::region::RegionRequest>,
5591        ) -> common_meta::error::Result<api::region::RegionResponse> {
5592            let rows = match _request.body.as_ref() {
5593                Some(api::v1::region::region_request::Body::Inserts(requests)) => requests
5594                    .requests
5595                    .iter()
5596                    .filter_map(|request| request.rows.as_ref())
5597                    .map(|rows| rows.rows.len())
5598                    .sum(),
5599                Some(api::v1::region::region_request::Body::BulkInsert(bulk)) => {
5600                    let Some(api::v1::region::bulk_insert_request::Body::ArrowIpc(ipc)) =
5601                        bulk.body.as_ref()
5602                    else {
5603                        return Ok(api::region::RegionResponse::new(0));
5604                    };
5605                    common_grpc::flight::FlightDecoder::try_from_schema_bytes(&ipc.schema)
5606                        .and_then(|mut decoder| {
5607                            decoder.try_decode_record_batch(&ipc.data_header, &ipc.payload)
5608                        })
5609                        .map(|batch| batch.num_rows())
5610                        .unwrap_or(0)
5611                }
5612                _ => 0,
5613            };
5614            let _ = self.manager.datanode_dispatch.send(rows);
5615            Ok(api::region::RegionResponse::new(rows))
5616        }
5617
5618        async fn handle_query(
5619            &self,
5620            _request: common_query::request::QueryRequest,
5621        ) -> common_meta::error::Result<common_recordbatch::SendableRecordBatchStream> {
5622            unreachable!()
5623        }
5624    }
5625
5626    #[async_trait::async_trait]
5627    impl common_meta::node_manager::Flownode for RecordingNode {
5628        async fn handle(
5629            &self,
5630            _request: api::v1::flow::FlowRequest,
5631        ) -> common_meta::error::Result<FlowResponse> {
5632            unreachable!()
5633        }
5634
5635        async fn handle_inserts(
5636            &self,
5637            request: api::v1::region::InsertRequests,
5638        ) -> common_meta::error::Result<FlowResponse> {
5639            let _ = self
5640                .manager
5641                .flownode_dispatch
5642                .send((self.peer.clone(), request));
5643            if self.manager.fail_flownode {
5644                return Err(common_meta::error::UnexpectedSnafu {
5645                    err_msg: "test flownode failure".to_string(),
5646                }
5647                .build());
5648            }
5649            let gate = self
5650                .manager
5651                .gates
5652                .lock()
5653                .unwrap()
5654                .get(&self.peer.id)
5655                .cloned();
5656            if let Some(gate) = gate {
5657                let _permit = gate.acquire().await.unwrap();
5658            }
5659            Ok(FlowResponse::default())
5660        }
5661
5662        async fn handle_mark_window_dirty(
5663            &self,
5664            _request: api::v1::flow::DirtyWindowRequests,
5665        ) -> common_meta::error::Result<FlowResponse> {
5666            unreachable!()
5667        }
5668    }
5669
5670    fn mirror_requests(peer: &Peer, num_rows: usize) -> HashMap<Peer, RegionInsertRequests> {
5671        HashMap::from_iter([(
5672            peer.clone(),
5673            RegionInsertRequests {
5674                requests: vec![RegionInsertRequest {
5675                    region_id: RegionId::new(1, 1).as_u64(),
5676                    rows: Some(Rows {
5677                        schema: vec![],
5678                        rows: vec![api::v1::Row { values: vec![] }; num_rows],
5679                    }),
5680                    ..Default::default()
5681                }],
5682            },
5683        )])
5684    }
5685
5686    /// Serializes the mirror metric tests below: the metrics are process-wide
5687    /// singletons, so these tests would otherwise observe each other's updates
5688    /// when the test binary runs tests in parallel (they are isolated per
5689    /// process only under nextest).
5690    static MIRROR_METRIC_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
5691
5692    async fn lock_mirror_metrics() -> tokio::sync::MutexGuard<'static, ()> {
5693        MIRROR_METRIC_TEST_LOCK.lock().await
5694    }
5695
5696    // The tests below share the process-wide mirror metrics, so they take
5697    // `MIRROR_METRIC_TEST_LOCK` and assert on the difference their own budget
5698    // publishes instead of on absolute values.
5699    #[tokio::test]
5700    async fn flow_mirror_saturation_preserves_instant_and_normal_contracts() {
5701        use common_error::ext::{ErrorExt, RetryHint};
5702        use common_error::status_code::StatusCode;
5703
5704        let _guard = lock_mirror_metrics().await;
5705        let kv_backend = prepare_mocked_backend().await;
5706        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
5707        let (datanode_tx, mut datanode_rx) = tokio::sync::mpsc::unbounded_channel();
5708        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
5709        let node_manager = Arc::new(RecordingNodeManager {
5710            datanode_dispatch: datanode_tx,
5711            flownode_dispatch: flownode_tx,
5712            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
5713            fail_flownode: false,
5714        });
5715        let flow_cache = Cache::new(10);
5716        let flow_cache_backend = prepare_mocked_backend().await;
5717        let inserter = Inserter::new(
5718            catalog::memory::MemoryCatalogManager::new(),
5719            partition_manager,
5720            node_manager,
5721            Arc::new(new_table_flownode_set_cache(
5722                String::new(),
5723                flow_cache.clone(),
5724                flow_cache_backend,
5725            )),
5726            true,
5727        );
5728        let peer = flownode_peer();
5729        cache_test_flow(
5730            &inserter.table_flownode_set_cache,
5731            CreateFlow {
5732                flow_id: 1,
5733                source_table_ids: vec![1, 2],
5734                partition_to_peer_mapping: vec![(0, peer)],
5735            },
5736        )
5737        .await;
5738        let mut normal_info = new_test_table_info(1, "normal_table", [1].into_iter());
5739        normal_info.catalog_name = DEFAULT_CATALOG_NAME.to_string();
5740        normal_info.schema_name = DEFAULT_SCHEMA_NAME.to_string();
5741        let mut instant_info = new_test_table_info(2, "instant_table", [1].into_iter());
5742        instant_info.meta.options.ttl = Some(common_time::ttl::TimeToLive::Instant);
5743        let table_infos =
5744            HashMap::from_iter([(1, Arc::new(normal_info)), (2, Arc::new(instant_info))]);
5745        let ctx = Arc::new(QueryContext::with(
5746            DEFAULT_CATALOG_NAME,
5747            DEFAULT_SCHEMA_NAME,
5748        ));
5749        let insert = |table_id, num_rows| RegionInsertRequests {
5750            requests: vec![RegionInsertRequest {
5751                region_id: RegionId::new(table_id, 1).as_u64(),
5752                rows: Some(Rows {
5753                    schema: vec![],
5754                    rows: vec![api::v1::Row::default(); num_rows],
5755                }),
5756                ..Default::default()
5757            }],
5758        };
5759        let make_request = |normal, instant| InstantAndNormalInsertRequests {
5760            normal_requests: if normal == 0 {
5761                RegionInsertRequests::default()
5762            } else {
5763                insert(1, normal)
5764            },
5765            instant_requests: if instant == 0 {
5766                RegionInsertRequests::default()
5767            } else {
5768                insert(2, instant)
5769            },
5770        };
5771
5772        let pending = inserter.mirror_pending_rows.clone();
5773        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
5774        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(MAX_MIRROR_PENDING_ROWS as i64);
5775        pending.store(MAX_MIRROR_PENDING_ROWS as u64, Ordering::Relaxed);
5776        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
5777        for request in [make_request(0, 1), make_request(1, 1)] {
5778            let error = inserter
5779                .do_request(request, &table_infos, &ctx)
5780                .await
5781                .unwrap_err();
5782            assert_eq!(error.status_code(), StatusCode::RateLimited);
5783            assert_eq!(error.retry_hint(), RetryHint::Retryable);
5784            assert!(datanode_rx.try_recv().is_err());
5785            assert!(flownode_rx.try_recv().is_err());
5786            assert_eq!(
5787                pending.load(Ordering::Relaxed),
5788                MAX_MIRROR_PENDING_ROWS as u64
5789            );
5790        }
5791        assert_eq!(
5792            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5793            dropped_before
5794        );
5795
5796        for pending_before in [0, MAX_MIRROR_PENDING_ROWS as u64] {
5797            if pending_before == 0 {
5798                pending.store(0, Ordering::Relaxed);
5799                crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(MAX_MIRROR_PENDING_ROWS as i64);
5800            }
5801            let gauge_before_rejection = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
5802            for (normal, instant) in [
5803                (0, MAX_MIRROR_PENDING_ROWS + 1),
5804                (MAX_MIRROR_PENDING_ROWS / 2, MAX_MIRROR_PENDING_ROWS / 2 + 1),
5805            ] {
5806                let error = inserter
5807                    .do_request(make_request(normal, instant), &table_infos, &ctx)
5808                    .await
5809                    .unwrap_err();
5810                assert_eq!(error.status_code(), StatusCode::InvalidArguments);
5811                assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
5812                let message = error.to_string();
5813                assert!(message.contains("1000001"), "{message}");
5814                assert!(message.contains("1000000"), "{message}");
5815                assert!(message.contains("reduce the batch size"), "{message}");
5816                assert!(datanode_rx.try_recv().is_err());
5817                assert!(flownode_rx.try_recv().is_err());
5818                assert_eq!(pending.load(Ordering::Relaxed), pending_before);
5819                assert_eq!(
5820                    crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
5821                    gauge_before_rejection
5822                );
5823                assert_eq!(
5824                    crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5825                    dropped_before
5826                );
5827            }
5828            if pending_before == 0 {
5829                crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(MAX_MIRROR_PENDING_ROWS as i64);
5830                pending.store(MAX_MIRROR_PENDING_ROWS as u64, Ordering::Relaxed);
5831            }
5832        }
5833
5834        let result = inserter
5835            .do_request(make_request(1, 0), &table_infos, &ctx)
5836            .await
5837            .unwrap();
5838        assert!(matches!(result.data, OutputData::AffectedRows(1)));
5839        assert_eq!(1, datanode_rx.try_recv().unwrap());
5840        assert!(flownode_rx.try_recv().is_err());
5841        assert_eq!(
5842            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
5843            dropped_before + 1
5844        );
5845        pending.store(0, Ordering::Relaxed);
5846        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(MAX_MIRROR_PENDING_ROWS as i64);
5847        assert_eq!(
5848            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
5849            gauge_before
5850        );
5851    }
5852
5853    #[tokio::test]
5854    async fn flow_mirror_new_counts_regions_and_peer_clones() {
5855        let peer1 = flownode_peer();
5856        let peer2 = Peer {
5857            id: 2,
5858            addr: "127.0.0.1:4002".to_string(),
5859        };
5860        let cache_backend = prepare_mocked_backend().await;
5861        let cache = Arc::new(new_table_flownode_set_cache(
5862            String::new(),
5863            Cache::new(10),
5864            cache_backend,
5865        ));
5866        cache_test_flow(
5867            &cache,
5868            CreateFlow {
5869                flow_id: 1,
5870                source_table_ids: vec![1],
5871                partition_to_peer_mapping: vec![(0, peer1), (1, peer2)],
5872            },
5873        )
5874        .await;
5875        let request = |region_id| RegionInsertRequest {
5876            region_id,
5877            rows: Some(Rows {
5878                schema: vec![],
5879                rows: vec![api::v1::Row { values: vec![] }; 3],
5880            }),
5881            ..Default::default()
5882        };
5883        let requests = [
5884            request(RegionId::new(1, 0).as_u64()),
5885            request(RegionId::new(1, 1).as_u64()),
5886        ];
5887        let task = FlowMirrorTask::new(&cache, requests.iter()).await.unwrap();
5888        assert_eq!(12, task.pending_rows());
5889        assert_eq!(2, task.requests.len());
5890        for mirrored in task.requests.values() {
5891            assert_eq!(mirrored.requests.as_slice(), requests.as_slice());
5892        }
5893    }
5894
5895    #[tokio::test]
5896    async fn flow_mirror_bounds_and_deduplicates_cold_lookups() {
5897        let (started, mut loads) = tokio::sync::mpsc::unbounded_channel();
5898        let cache = Arc::new(common_meta::cache::CacheContainer::new(
5899            "test".into(),
5900            Cache::new(32),
5901            Arc::new(move |&id| {
5902                let (resume, gate) = tokio::sync::oneshot::channel();
5903                started.send((id, resume)).unwrap();
5904                Box::pin(async move {
5905                    gate.await.unwrap();
5906                    Ok(Some(Default::default()))
5907                })
5908            }),
5909            common_meta::instruction::CacheIdent::table_id_key,
5910        ));
5911        let requests: Vec<_> = (1..=12)
5912            .flat_map(|id| {
5913                (0..2).map(move |region| RegionInsertRequest {
5914                    region_id: RegionId::new(id, region).as_u64(),
5915                    ..Default::default()
5916                })
5917            })
5918            .collect();
5919        let mut task = Box::pin(FlowMirrorTask::new(&cache, requests.iter()));
5920        let mut seen = BTreeSet::new();
5921        // Every table occurs twice. Only eight distinct misses may start before one completes.
5922        for expected in [8, 4] {
5923            assert!(futures_util::poll!(&mut task).is_pending());
5924            let mut gates = Vec::new();
5925            while let Ok((id, resume)) = loads.try_recv() {
5926                assert!(seen.insert(id));
5927                gates.push(resume);
5928            }
5929            assert_eq!(gates.len(), expected);
5930            for gate in gates {
5931                gate.send(()).unwrap();
5932            }
5933        }
5934        assert!(task.await.unwrap().requests.is_empty());
5935        assert_eq!(seen.len(), 12);
5936    }
5937
5938    #[tokio::test]
5939    async fn batch_eligibility_checks_flows_and_fails_closed() {
5940        let kv_backend = prepare_mocked_backend().await;
5941        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
5942        let inserter_with_cache = |flow_cache| {
5943            Inserter::new(
5944                catalog::memory::MemoryCatalogManager::new(),
5945                partition_manager.clone(),
5946                Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
5947                flow_cache,
5948                true,
5949            )
5950        };
5951
5952        // Subscribed flow source forces batching bypass.
5953        let subscribed_cache = Arc::new(new_table_flownode_set_cache(
5954            String::new(),
5955            Cache::new(32),
5956            kv_backend,
5957        ));
5958        assert!(
5959            !inserter_with_cache(subscribed_cache.clone())
5960                .any_table_has_flow(1..=4)
5961                .await
5962        );
5963        cache_test_flow(
5964            &subscribed_cache,
5965            CreateFlow {
5966                flow_id: 1,
5967                source_table_ids: vec![2],
5968                partition_to_peer_mapping: vec![(0, flownode_peer())],
5969            },
5970        )
5971        .await;
5972        assert!(
5973            inserter_with_cache(subscribed_cache)
5974                .any_table_has_flow(1..=4)
5975                .await
5976        );
5977
5978        // Lookup error fails closed and bypasses batching.
5979        let failing_cache = Arc::new(common_meta::cache::CacheContainer::new(
5980            "test_failing".into(),
5981            Cache::new(32),
5982            Arc::new(move |&id| {
5983                Box::pin(async move {
5984                    if id == 2 {
5985                        common_meta::error::UnexpectedSnafu { err_msg: "kv down" }.fail()
5986                    } else {
5987                        Ok(None)
5988                    }
5989                })
5990            }),
5991            common_meta::instruction::CacheIdent::table_id_key,
5992        ));
5993        assert!(
5994            inserter_with_cache(failing_cache)
5995                .any_table_has_flow(1..=4)
5996                .await
5997        );
5998    }
5999
6000    #[tokio::test]
6001    async fn flow_mirror_dropped_when_pending_exceeds_limit() {
6002        let _guard = lock_mirror_metrics().await;
6003        let pending = Arc::new(AtomicU64::new(MAX_MIRROR_PENDING_ROWS as u64));
6004        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
6005        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6006        let num_rows = 100;
6007
6008        let task = FlowMirrorTask {
6009            requests: mirror_requests(&flownode_peer(), num_rows),
6010        };
6011        // The budget is already full, so nothing may be spawned for this batch.
6012        task.detach(
6013            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
6014            pending.clone(),
6015            false,
6016        )
6017        .unwrap();
6018
6019        assert_eq!(
6020            num_rows as u64,
6021            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get() - dropped_before
6022        );
6023        // The dropped batch must not leak its reservation.
6024        assert_eq!(
6025            MAX_MIRROR_PENDING_ROWS as u64,
6026            pending.load(Ordering::Relaxed)
6027        );
6028        // The reservation taken before the limit check is released again, so the
6029        // gauge nets out and keeps matching the pending budget.
6030        assert_eq!(
6031            gauge_before,
6032            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
6033            "a dropped batch must not change the pending gauge"
6034        );
6035
6036        let task = FlowMirrorTask {
6037            requests: mirror_requests(&flownode_peer(), num_rows),
6038        };
6039        let error = task
6040            .detach(
6041                Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
6042                pending.clone(),
6043                true,
6044            )
6045            .err()
6046            .unwrap();
6047        use common_error::ext::{ErrorExt, RetryHint};
6048        use common_error::status_code::StatusCode;
6049        assert_eq!(error.status_code(), StatusCode::RateLimited);
6050        assert_eq!(error.retry_hint(), RetryHint::Retryable);
6051        assert_eq!(
6052            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
6053            dropped_before + num_rows as u64,
6054            "rejected instant rows are not successful best-effort drops"
6055        );
6056        assert_eq!(
6057            MAX_MIRROR_PENDING_ROWS as u64,
6058            pending.load(Ordering::Relaxed)
6059        );
6060        assert_eq!(
6061            gauge_before,
6062            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get()
6063        );
6064    }
6065
6066    /// A source table mapped to several flownodes clones its requests per peer,
6067    /// so the reservation must cover every clone and each spawned task must hand
6068    /// back exactly its own share; otherwise the shared budget drifts.
6069    #[tokio::test]
6070    async fn flow_mirror_reserves_and_releases_per_peer_shares() {
6071        let _guard = lock_mirror_metrics().await;
6072        let per_peer_rows = 10;
6073        let total_rows = (2 * per_peer_rows) as u64;
6074        // Exactly enough room for the whole batch, cloned rows included.
6075        let start = MAX_MIRROR_PENDING_ROWS as u64 - total_rows;
6076        let pending = Arc::new(AtomicU64::new(start));
6077        let gate = Arc::new(tokio::sync::Semaphore::new(0));
6078        let node_manager = Arc::new(MockFlownodeManager::new(GatedFlownodeHandler {
6079            gate: gate.clone(),
6080            affected_rows: per_peer_rows as u64,
6081        }));
6082
6083        let mut requests = mirror_requests(&flownode_peer(), per_peer_rows);
6084        requests.extend(mirror_requests(
6085            &Peer {
6086                id: 2,
6087                addr: "127.0.0.1:4002".to_string(),
6088            },
6089            per_peer_rows,
6090        ));
6091
6092        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6093        FlowMirrorTask { requests }
6094            .detach(node_manager, pending.clone(), false)
6095            .unwrap();
6096
6097        // Both per-peer payloads are counted, so the budget is exactly full
6098        // instead of over-reserved by the duplicated rows.
6099        assert_eq!(
6100            MAX_MIRROR_PENDING_ROWS as u64,
6101            pending.load(Ordering::Relaxed)
6102        );
6103
6104        // Let both tasks finish and check that the budget lands back on its
6105        // starting value: over-releasing a shared reservation would saturate it.
6106        // The gauge is checked too because `release_mirror_pending_rows` moves
6107        // the budget before the gauge; exiting on the budget alone could leak a
6108        // pending `gauge.sub` into the next test holding the metrics lock.
6109        gate.add_permits(2);
6110        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
6111        while pending.load(Ordering::Relaxed) != start
6112            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6113        {
6114            assert!(
6115                std::time::Instant::now() < deadline,
6116                "the mirror tasks must release exactly their own shares"
6117            );
6118            std::thread::sleep(std::time::Duration::from_millis(1));
6119        }
6120    }
6121
6122    #[tokio::test]
6123    async fn flow_mirror_fast_peer_releases_only_its_share_before_drop() {
6124        let _guard = lock_mirror_metrics().await;
6125        let peer1 = flownode_peer();
6126        let peer2 = Peer {
6127            id: 2,
6128            addr: "127.0.0.1:4002".to_string(),
6129        };
6130        let gate1 = Arc::new(tokio::sync::Semaphore::new(0));
6131        let gate2 = Arc::new(tokio::sync::Semaphore::new(0));
6132        let gates = Arc::new(std::sync::Mutex::new(HashMap::from_iter([
6133            (peer1.id, gate1.clone()),
6134            (peer2.id, gate2.clone()),
6135        ])));
6136        let (datanode_tx, _datanode_rx) = tokio::sync::mpsc::unbounded_channel();
6137        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
6138        let node_manager = Arc::new(RecordingNodeManager {
6139            datanode_dispatch: datanode_tx,
6140            flownode_dispatch: flownode_tx,
6141            gates,
6142            fail_flownode: false,
6143        });
6144        let pending = Arc::new(AtomicU64::new(MAX_MIRROR_PENDING_ROWS as u64 - 20));
6145        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6146        let mut requests = mirror_requests(&peer1, 10);
6147        requests.extend(mirror_requests(&peer2, 10));
6148        let task = FlowMirrorTask { requests };
6149        task.detach(node_manager.clone(), pending.clone(), false)
6150            .unwrap();
6151        let (first, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6152            .await
6153            .unwrap()
6154            .unwrap();
6155        let (second, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6156            .await
6157            .unwrap()
6158            .unwrap();
6159        assert_ne!(first.id, second.id);
6160        let fast_gate = if first.id == peer1.id {
6161            gate1.clone()
6162        } else {
6163            gate2.clone()
6164        };
6165        let slow_gate = if first.id == peer1.id {
6166            gate2.clone()
6167        } else {
6168            gate1.clone()
6169        };
6170        fast_gate.add_permits(1);
6171        let deadline = std::time::Instant::now() + Duration::from_secs(10);
6172        while pending.load(Ordering::Relaxed) != MAX_MIRROR_PENDING_ROWS as u64 - 10 {
6173            assert!(
6174                std::time::Instant::now() < deadline,
6175                "fast peer did not release"
6176            );
6177            std::thread::sleep(Duration::from_millis(1));
6178        }
6179        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
6180        FlowMirrorTask {
6181            requests: mirror_requests(&peer1, 11),
6182        }
6183        .detach(node_manager, pending.clone(), false)
6184        .unwrap();
6185        assert_eq!(
6186            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
6187            dropped_before + 11
6188        );
6189        assert!(flownode_rx.try_recv().is_err());
6190        slow_gate.add_permits(1);
6191        while pending.load(Ordering::Relaxed) != MAX_MIRROR_PENDING_ROWS as u64 - 20
6192            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6193        {
6194            assert!(
6195                std::time::Instant::now() < deadline,
6196                "slow peer did not release"
6197            );
6198            std::thread::sleep(Duration::from_millis(1));
6199        }
6200    }
6201
6202    #[tokio::test]
6203    async fn flow_mirror_failure_releases_budget_and_gauge() {
6204        let _guard = lock_mirror_metrics().await;
6205        let (datanode_tx, _datanode_rx) = tokio::sync::mpsc::unbounded_channel();
6206        let (flownode_tx, mut flownode_rx) = tokio::sync::mpsc::unbounded_channel();
6207        let node_manager = Arc::new(RecordingNodeManager {
6208            datanode_dispatch: datanode_tx,
6209            flownode_dispatch: flownode_tx,
6210            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
6211            fail_flownode: true,
6212        });
6213        let pending = Arc::new(AtomicU64::new(0));
6214        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6215        FlowMirrorTask {
6216            requests: mirror_requests(&flownode_peer(), 5),
6217        }
6218        .detach(node_manager, pending.clone(), false)
6219        .unwrap();
6220        let (peer, _) = tokio::time::timeout(Duration::from_secs(10), flownode_rx.recv())
6221            .await
6222            .unwrap()
6223            .unwrap();
6224        assert_eq!(peer.id, flownode_peer().id);
6225        let deadline = std::time::Instant::now() + Duration::from_secs(10);
6226        while pending.load(Ordering::Relaxed) != 0
6227            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6228        {
6229            assert!(
6230                std::time::Instant::now() < deadline,
6231                "failed task leaked reservation"
6232            );
6233            std::thread::sleep(Duration::from_millis(1));
6234        }
6235    }
6236
6237    #[tokio::test]
6238    async fn flow_mirror_pending_counter_consistent() {
6239        let _guard = lock_mirror_metrics().await;
6240        let pending = Arc::new(AtomicU64::new(0));
6241        let gate = Arc::new(tokio::sync::Semaphore::new(0));
6242        let node_manager = Arc::new(MockFlownodeManager::new(GatedFlownodeHandler {
6243            gate: gate.clone(),
6244            affected_rows: 7,
6245        }));
6246
6247        // A batch without rows short-circuits and leaves the budget untouched.
6248        let gauge_before = crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get();
6249        FlowMirrorTask {
6250            requests: HashMap::new(),
6251        }
6252        .detach(node_manager.clone(), pending.clone(), false)
6253        .unwrap();
6254        assert_eq!(0, pending.load(Ordering::Relaxed));
6255        assert_eq!(
6256            gauge_before,
6257            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get(),
6258            "an empty batch must not touch the pending gauge"
6259        );
6260
6261        let dropped_before = crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get();
6262        let num_rows = 7;
6263
6264        FlowMirrorTask {
6265            requests: mirror_requests(&flownode_peer(), num_rows),
6266        }
6267        .detach(node_manager, pending.clone(), false)
6268        .unwrap();
6269
6270        // The spawned task is still waiting on the gated flownode, so the
6271        // reservation made by `detach` is the value observable here.
6272        assert_eq!(num_rows as u64, pending.load(Ordering::Relaxed));
6273        assert_eq!(
6274            num_rows as i64,
6275            crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() - gauge_before,
6276            "the pending gauge must track the pending rows"
6277        );
6278        assert_eq!(
6279            dropped_before,
6280            crate::metrics::DIST_MIRROR_DROPPED_ROW_COUNT.get(),
6281            "a batch within the limit must not be counted as dropped"
6282        );
6283
6284        // Release the in-flight task and wait for it to hand its reservation
6285        // back, so no task is left holding the shared metrics after this test.
6286        gate.add_permits(1);
6287        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
6288        while pending.load(Ordering::Relaxed) != 0
6289            || crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.get() != gauge_before
6290        {
6291            assert!(
6292                std::time::Instant::now() < deadline,
6293                "the mirror task did not release its pending reservation"
6294            );
6295            std::thread::sleep(std::time::Duration::from_millis(1));
6296        }
6297    }
6298
6299    #[test]
6300    fn mirror_logs_are_rate_limited() {
6301        let log = Arc::new(MirrorLog::new());
6302        assert_eq!(Some(1), log.claim_report(1_000));
6303        assert_eq!(None, log.claim_report(1_500));
6304        assert_eq!(None, log.claim_report(10_999));
6305        assert_eq!(Some(3), log.claim_report(11_000));
6306        assert_eq!(None, log.claim_report(11_001));
6307        assert_eq!(Some(2), log.claim_report(21_000));
6308
6309        let concurrent = Arc::new(MirrorLog::new());
6310        assert_eq!(Some(1), concurrent.claim_report(50_000));
6311        let barrier = Arc::new(std::sync::Barrier::new(8));
6312        let threads = (0..8)
6313            .map(|_| {
6314                let log = concurrent.clone();
6315                let barrier = barrier.clone();
6316                std::thread::spawn(move || {
6317                    barrier.wait();
6318                    log.claim_report(60_000)
6319                })
6320            })
6321            .collect::<Vec<_>>();
6322        let winners = threads
6323            .into_iter()
6324            .filter_map(|thread| thread.join().unwrap())
6325            .collect::<Vec<_>>();
6326        assert_eq!(winners.len(), 1);
6327        assert!(concurrent.events.swap(0, Ordering::Relaxed) + winners[0] == 8);
6328    }
6329
6330    async fn recording_inserter(
6331        kv_backend: &common_meta::kv_backend::KvBackendRef,
6332    ) -> (
6333        Inserter,
6334        mpsc::UnboundedReceiver<usize>,
6335        mpsc::UnboundedReceiver<(Peer, RegionInsertRequests)>,
6336    ) {
6337        let partition_manager = create_partition_rule_manager(kv_backend.clone()).await;
6338        let (datanode_tx, datanode_rx) = mpsc::unbounded_channel();
6339        let (flownode_tx, flownode_rx) = mpsc::unbounded_channel();
6340        let node_manager = Arc::new(RecordingNodeManager {
6341            datanode_dispatch: datanode_tx,
6342            flownode_dispatch: flownode_tx,
6343            gates: Arc::new(std::sync::Mutex::new(HashMap::new())),
6344            fail_flownode: false,
6345        });
6346        let inserter = Inserter::new(
6347            catalog::memory::MemoryCatalogManager::new(),
6348            partition_manager,
6349            node_manager,
6350            Arc::new(new_table_flownode_set_cache(
6351                String::new(),
6352                Cache::new(10),
6353                kv_backend.clone(),
6354            )),
6355            true,
6356        );
6357        cache_test_flow(
6358            &inserter.table_flownode_set_cache,
6359            CreateFlow {
6360                flow_id: 1,
6361                source_table_ids: vec![10, 11],
6362                partition_to_peer_mapping: vec![(0, flownode_peer())],
6363            },
6364        )
6365        .await;
6366        (inserter, datanode_rx, flownode_rx)
6367    }
6368
6369    #[tokio::test]
6370    async fn test_mixed_sparse_write_preserves_instant_flow_default() {
6371        use api::v1::helper::tag_column_schema;
6372        use common_time::ttl::TimeToLive;
6373        use datatypes::schema::{ColumnDefaultConstraint, Schema};
6374
6375        let _guard = lock_mirror_metrics().await;
6376        let kv_backend = prepare_mocked_backend().await;
6377        let (inserter, mut datanode_rx, mut flownode_rx) = recording_inserter(&kv_backend).await;
6378        let mut stored = new_test_table_info(10, "stored", std::iter::empty());
6379        stored.meta.engine = default_engine().into();
6380        stored.meta.schema = Arc::new(Schema::new(vec![
6381            ColumnSchema::new(
6382                DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
6383                ConcreteDataType::uint32_datatype(),
6384                false,
6385            ),
6386            ColumnSchema::new(
6387                DATA_SCHEMA_TSID_COLUMN_NAME,
6388                ConcreteDataType::uint64_datatype(),
6389                false,
6390            ),
6391            ColumnSchema::new(
6392                "ts",
6393                ConcreteDataType::timestamp_millisecond_datatype(),
6394                false,
6395            )
6396            .with_time_index(true)
6397            .with_default_constraint(Some(ColumnDefaultConstraint::Function("now()".into())))
6398            .unwrap(),
6399        ]));
6400        stored.meta.column_ids = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid(), 2];
6401        stored.meta.primary_key_indices = vec![0, 1];
6402        stored.meta.partition_key_indices.clear();
6403        let mut instant = stored.clone();
6404        instant.ident.table_id = 11;
6405        instant.name = "instant".into();
6406        instant.meta.options.ttl = Some(TimeToLive::Instant);
6407        stored.meta.options.extra_options.insert(
6408            store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.into(),
6409            "sparse".into(),
6410        );
6411        let mut infos = HashMap::new();
6412        let mut requests = RowInsertRequests::default();
6413        for table in [stored, instant] {
6414            register_unpartitioned_table_route(&kv_backend, &table).await;
6415            requests.inserts.push(RowInsertRequest {
6416                table_name: table.name.clone(),
6417                rows: Some(Rows {
6418                    schema: vec![
6419                        tag_column_schema(DATA_SCHEMA_TABLE_ID_COLUMN_NAME, ColumnDataType::Uint32),
6420                        tag_column_schema(DATA_SCHEMA_TSID_COLUMN_NAME, ColumnDataType::Uint64),
6421                    ],
6422                    rows: vec![Row {
6423                        values: vec![ValueData::U32Value(1).into(), ValueData::U64Value(2).into()],
6424                    }],
6425                }),
6426            });
6427            infos.insert(table.table_id(), Arc::new(table));
6428        }
6429        let output = inserter
6430            .dispatch_direct_sparse_row_inserts(
6431                requests,
6432                infos,
6433                HashSet::new(),
6434                false,
6435                &QueryContext::arc(),
6436            )
6437            .await
6438            .unwrap();
6439        assert!(matches!(output.data, OutputData::AffectedRows(1)));
6440        assert_eq!(datanode_rx.try_recv().unwrap(), 1);
6441        let (_, mirrored) = tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6442            .await
6443            .unwrap()
6444            .unwrap();
6445        let timestamps = mirrored
6446            .requests
6447            .into_iter()
6448            .map(|request| {
6449                let table_id = RegionId::from(request.region_id).table_id();
6450                let rows = request.rows.unwrap();
6451                let has_timestamp = rows.schema.iter().any(|column| column.column_name == "ts");
6452                (table_id, has_timestamp)
6453            })
6454            .collect::<BTreeMap<_, _>>();
6455        assert_eq!(timestamps, BTreeMap::from([(10, true), (11, false)]));
6456        drop(inserter);
6457        assert!(
6458            tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6459                .await
6460                .unwrap()
6461                .is_none()
6462        );
6463    }
6464
6465    #[tokio::test]
6466    async fn test_exemplar_flow_mirror_and_instant_ttl_bypass() {
6467        let _guard = lock_mirror_metrics().await;
6468        let kv_backend = prepare_mocked_backend().await;
6469        let (inserter, mut datanode_rx, mut flownode_rx) = recording_inserter(&kv_backend).await;
6470        let inserter = inserter.with_pending_rows_batcher(Some(Arc::new(UnexpectedBatcher {
6471            allow_acquire: false,
6472        })));
6473
6474        let make_exemplar_table = |id: TableId, instant: bool| {
6475            test_exemplar_table_info(
6476                id,
6477                DEFAULT_CATALOG_NAME,
6478                DEFAULT_SCHEMA_NAME,
6479                &["job"],
6480                instant,
6481            )
6482        };
6483
6484        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
6485        ctx.set_batching_enabled(true);
6486        let ctx = Arc::new(ctx);
6487        let resolved = HashMap::from_iter([("cpu".to_string(), 100)]);
6488        let batch = |tag: &str| {
6489            ExemplarBatch::try_new(vec![Exemplar {
6490                metric: "cpu".into(),
6491                series_labels: BTreeMap::from([(tag.into(), "api".into())]).into(),
6492                timestamp: 1_000,
6493                value: 1.5,
6494                labels: BTreeMap::from([("trace_id".into(), "abc".into())]),
6495            }])
6496            .unwrap()
6497        };
6498
6499        // An unreconciled destination rejects the same missing tag with and without a Flow.
6500        for id in [11, 12] {
6501            let error = inserter
6502                .execute_exemplar_write(
6503                    batch("host"),
6504                    resolved.clone(),
6505                    make_exemplar_table(id, true),
6506                    true,
6507                    ctx.clone(),
6508                )
6509                .await
6510                .unwrap_err();
6511            assert!(error.to_string().contains("is missing tag host"), "{error}");
6512        }
6513        assert!(flownode_rx.try_recv().is_err());
6514
6515        // Normal subscribed exemplar table bypasses batcher, mirrors to flownode, and writes datanode.
6516        let normal_dest = make_exemplar_table(10, false);
6517        register_unpartitioned_table_route(&kv_backend, &normal_dest).await;
6518        let output = inserter
6519            .execute_exemplar_write(
6520                batch("job"),
6521                resolved.clone(),
6522                normal_dest,
6523                false,
6524                ctx.clone(),
6525            )
6526            .await
6527            .unwrap();
6528        assert!(matches!(output.data, OutputData::AffectedRows(1)));
6529        assert_eq!(datanode_rx.try_recv().unwrap(), 1);
6530        tokio::time::timeout(std::time::Duration::from_secs(5), flownode_rx.recv())
6531            .await
6532            .unwrap()
6533            .unwrap();
6534
6535        // Instant-TTL exemplar table mirrors to flownode and skips datanode storage.
6536        let instant_dest = make_exemplar_table(11, true);
6537        register_unpartitioned_table_route(&kv_backend, &instant_dest).await;
6538        let output = inserter
6539            .execute_exemplar_write(batch("job"), resolved, instant_dest, true, ctx)
6540            .await
6541            .unwrap();
6542        assert!(matches!(output.data, OutputData::AffectedRows(0)));
6543        assert!(datanode_rx.try_recv().is_err());
6544        tokio::time::timeout(std::time::Duration::from_secs(5), flownode_rx.recv())
6545            .await
6546            .unwrap()
6547            .unwrap();
6548
6549        drop(inserter);
6550        assert!(
6551            tokio::time::timeout(Duration::from_secs(5), flownode_rx.recv())
6552                .await
6553                .unwrap()
6554                .is_none()
6555        );
6556    }
6557}