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