From ef1d505c2e72f0a993e6fad0b3e45dab8a4f81c6 Mon Sep 17 00:00:00 2001 From: dayan02dev Date: Mon, 30 Nov 2026 18:21:37 +0000 Subject: [PATCH] fix(operator): reconcile inserts with auto-created tables (#10718) * test: cover writes that need columns missing from the target table Each case writes columns that the table it reaches does not have: - a gRPC write to a new mito table whose CREATE loses to a concurrent writer, held after the DDL executor's existence check; - the same for a logical metric table, where the winner uses a nanosecond physical table and the losing write selected a millisecond one; - one gRPC batch with three entries for one new logical table and overlapping new tags; - one gRPC batch with two entries that need different new tags on an existing logical table; - an Elasticsearch _bulk request whose third document adds a field. Signed-off-by: dayan02dev * fix(operator): check every auto-create request against the created table create_or_alter_tables_on_demand planned one CREATE for each request whose table was missing, and never checked the requests against the table that existed after the CREATE: - repeated entries for a new table in one batch sent one CREATE each. The later ones returned the first table without their columns, and repeated logical table names allocated several table IDs; - a CREATE that lost to a concurrent writer returned its own schema with the winner's table ID, so rows were converted against columns the region does not have; - a logical CREATE that lost returned the winner's table, but only tables found during planning were altered. Now the first request for a missing table defines its CREATE. A mito table is read back from the catalog after the CREATE, as logical tables already are, and every request for it is checked against that table. Missing columns go into one AddColumns per table, including tables found during planning, because an ALTER LOGICAL TABLES procedure reads each table once. Rows for a new logical table keep their timestamps until the table that exists is known, and are converted once. Signed-off-by: dayan02dev --------- Signed-off-by: dayan02dev Co-authored-by: dennis zhuang --- src/operator/src/insert.rs | 221 ++++++++++------ tests-integration/src/grpc.rs | 431 +++++++++++++++++++++++++++++++- tests-integration/tests/http.rs | 54 ++++ 3 files changed, 622 insertions(+), 84 deletions(-) diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs index 489ac11339f..2840cd4332b 100644 --- a/src/operator/src/insert.rs +++ b/src/operator/src/insert.rs @@ -1980,9 +1980,13 @@ impl Inserter { } /// Creates or alter tables on demand: - /// - if table does not exist, create table by inferred CreateExpr + /// - if table does not exist, create table by inferred CreateExpr from the first request for it, + /// then check every request for it against the table that exists after the CREATE, which a + /// concurrent writer may have created with other columns /// - if table exist, check if schema matches. If any new column found, alter table by inferred `AlterExpr` /// + /// Each altered table gets one `AlterExpr` with the new columns of all its requests. + /// /// Returns a mapping from table name to table id, where table name is the table name involved in the requests. /// This mapping is used in the conversion of RowToRegion. /// @@ -1995,7 +1999,9 @@ impl Inserter { /// `align_time_index_unit` supplies the selected physical table's time-index /// unit for new logical tables. Existing logical targets always use their /// own unit, even when this argument is `None` because no new target needs - /// the selected backing table. + /// the selected backing table. Rows for a new table keep their unit until + /// the CREATE returns, and are then converted once to the unit of the table + /// that exists. #[allow(clippy::too_many_arguments)] async fn create_or_alter_tables_on_demand( &self, @@ -2080,8 +2086,11 @@ impl Inserter { let mut need_refresh_table_infos = HashSet::new(); let mut instant_table_ids = HashSet::new(); let mut per_table_semantics: Option> = None; + // Requests whose tables are created below, by index. They are checked + // against the table that exists after the CREATE. + let mut created_table_requests = vec![]; - for req in &mut requests.inserts { + for (index, req) in requests.inserts.iter_mut().enumerate() { // Mixed batches need a per-table decision so an exempt table cannot authorize others. let auto_create_allowed = auto_create_disabled_reason.is_none() || Self::is_auto_create_exempt_private_table(&schema, &req.table_name); @@ -2116,7 +2125,7 @@ impl Inserter { auto_create_table_type.alter_existing(), )? { - alter_tables.push(alter_expr); + merge_alter_table_expr(&mut alter_tables, alter_expr); need_refresh_table_infos.insert(( catalog.to_string(), schema.clone(), @@ -2151,50 +2160,47 @@ impl Inserter { .fail(); } None => { - // Metric path: a new table uses the selected physical - // table's unit; convert before the create expression is - // derived from the request schema. - if let Some(physical_unit) = align_time_index_unit - && let Some(rows) = req.rows.as_mut() + // The first request for a missing table defines its CREATE. + if !create_tables + .iter() + .any(|expr: &CreateTableExpr| expr.table_name == req.table_name) { - convert_rows_time_unit(rows, physical_unit)?; + let semantic_index = per_table_semantics + .get_or_insert_with(|| parse_per_table_semantic_index(ctx)) + .as_ref(); + let mut create_expr = self.get_create_table_expr_on_demand( + req, + &auto_create_table_type, + ctx, + semantic_index, + )?; + // Metric path: a new table uses the selected physical + // table's unit. The rows keep their own unit until the + // table that exists after the CREATE is known. + if let Some(physical_unit) = align_time_index_unit { + set_time_index_unit(&mut create_expr, physical_unit); + } + create_tables.push(create_expr); } - let semantic_index = per_table_semantics - .get_or_insert_with(|| parse_per_table_semantic_index(ctx)) - .as_ref(); - let create_expr = self.get_create_table_expr_on_demand( - req, - &auto_create_table_type, - ctx, - semantic_index, - )?; - create_tables.push(create_expr); + created_table_requests.push(index); } } } + let mut created_tables = HashMap::with_capacity(create_tables.len()); match auto_create_table_type { AutoCreateTableType::Logical(_) => { if !create_tables.is_empty() { - // Creates logical tables in batch. + // Creates logical tables in batch. They are read back from the + // catalog, so a table that a concurrent writer created comes + // with its actual schema. let tables = self .create_logical_tables(create_tables, ctx, statement_executor) .await?; - for table in tables { - let table_info = table.table_info(); - if table_info.is_ttl_instant_table() { - instant_table_ids.insert(table_info.table_id()); - } - table_infos.insert(table_info.table_id(), table.table_info()); + created_tables.insert(table.table_info().name.clone(), table); } } - if !alter_tables.is_empty() { - // Alter logical tables in batch. - statement_executor - .alter_logical_tables(alter_tables, ctx.clone(), TriggerReason::AutoAlter) - .await?; - } } AutoCreateTableType::Physical | AutoCreateTableType::Exemplar @@ -2206,43 +2212,10 @@ impl Inserter { let table = self .create_physical_table(create_table, None, ctx, statement_executor) .await?; - // A concurrent CREATE can return our proposed schema with the winner's ID. - let table = if is_exemplar { - let name = table.table_info().name.clone(); - self.get_table(catalog, &schema, &name) - .await? - .context(TableNotFoundSnafu { table_name: name })? - } else { - table - }; - if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) { + if is_exemplar { validate_exemplar_table(&table.table_info())?; - if let Some(req) = requests - .inserts - .iter_mut() - .find(|r| r.table_name == table.table_info().name) - && let Some(alter) = self.get_alter_table_expr_on_demand( - req, &table, ctx, false, false, true, - )? - { - alter_tables.push(alter); - need_refresh_table_infos.insert(( - catalog.to_string(), - schema.clone(), - req.table_name.clone(), - )); - } } - let table_info = table.table_info(); - if table_info.is_ttl_instant_table() { - instant_table_ids.insert(table_info.table_id()); - } - table_infos.insert(table_info.table_id(), table.table_info()); - } - for alter_expr in alter_tables.into_iter() { - statement_executor - .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter) - .await?; + created_tables.insert(table.table_info().name.clone(), table); } } @@ -2284,11 +2257,7 @@ impl Inserter { let table = self .create_physical_table(create_table, None, ctx, statement_executor) .await?; - let table_info = table.table_info(); - if table_info.is_ttl_instant_table() { - instant_table_ids.insert(table_info.table_id()); - } - table_infos.insert(table_info.table_id(), table.table_info()); + created_tables.insert(table.table_info().name.clone(), table); } else { // prebuilt partition rules for uuid data: see the function // for more information @@ -2375,14 +2344,59 @@ impl Inserter { statement_executor, ) .await?; - let table_info = table.table_info(); - if table_info.is_ttl_instant_table() { - instant_table_ids.insert(table_info.table_id()); - } - table_infos.insert(table_info.table_id(), table.table_info()); + created_tables.insert(table.table_info().name.clone(), table); } } - for alter_expr in alter_tables.into_iter() { + } + } + + for index in created_table_requests { + let req = &mut requests.inserts[index]; + let table = created_tables + .get(&req.table_name) + .context(TableNotFoundSnafu { + table_name: &req.table_name, + })?; + // Metric path: convert the rows once, to the unit of the table that + // exists after the CREATE. + if matches!(auto_create_table_type, AutoCreateTableType::Logical(_)) + && let Some(rows) = req.rows.as_mut() + && let Some(target_unit) = table_time_index_unit(table) + { + convert_rows_time_unit(rows, target_unit)?; + } + if let Some(alter_expr) = self.get_alter_table_expr_on_demand( + req, + table, + ctx, + accommodate_existing_schema, + is_single_value, + auto_create_table_type.alter_existing(), + )? { + merge_alter_table_expr(&mut alter_tables, alter_expr); + need_refresh_table_infos.insert(( + catalog.to_string(), + schema.clone(), + req.table_name.clone(), + )); + } + } + for table in created_tables.into_values() { + let table_info = table.table_info(); + if table_info.is_ttl_instant_table() { + instant_table_ids.insert(table_info.table_id()); + } + table_infos.insert(table_info.table_id(), table_info); + } + + if !alter_tables.is_empty() { + if matches!(auto_create_table_type, AutoCreateTableType::Logical(_)) { + // Alter logical tables in batch. + statement_executor + .alter_logical_tables(alter_tables, ctx.clone(), TriggerReason::AutoAlter) + .await?; + } else { + for alter_expr in alter_tables { statement_executor .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter) .await?; @@ -2706,6 +2720,9 @@ impl Inserter { } /// Creates a table with options. + /// + /// Returns the table read back from the catalog: a CREATE that loses to a + /// concurrent writer returns its own schema with the winner's table ID. async fn create_physical_table( &self, mut create_table_expr: CreateTableExpr, @@ -2729,7 +2746,13 @@ impl Inserter { ); match res { - Ok(table) => { + Ok(_) => { + let table = self + .get_table(table_ref.catalog, table_ref.schema, table_ref.table) + .await? + .with_context(|| TableNotFoundSnafu { + table_name: table_ref.to_string(), + })?; validate_trace_table_model(&table.table_info(), ctx)?; Ok(table) } @@ -2790,6 +2813,32 @@ impl Inserter { } } +/// Merges `alter_expr` into the pending ALTER of the same table, so each table +/// gets one `AddColumns`. An ALTER LOGICAL TABLES procedure reads the metadata +/// of each table once and fails on a second ALTER of the same table. +fn merge_alter_table_expr(alter_tables: &mut Vec, alter_expr: AlterTableExpr) { + let pending = alter_tables + .iter_mut() + .find(|pending| pending.table_name == alter_expr.table_name) + .and_then(|pending| pending.kind.as_mut()); + if let Some(Kind::AddColumns(pending)) = pending + && let Some(Kind::AddColumns(add_columns)) = alter_expr.kind + { + for add_column in add_columns.add_columns { + let name = add_column.column_def.as_ref().map(|def| &def.name); + if !pending + .add_columns + .iter() + .any(|column| column.column_def.as_ref().map(|def| &def.name) == name) + { + pending.add_columns.push(add_column); + } + } + } else { + alter_tables.push(alter_expr); + } +} + fn request_is_native_histogram(request_schema: &[ColumnSchema]) -> bool { let mut fields = request_schema .iter() @@ -2818,6 +2867,18 @@ fn table_time_index_unit(table: &TableRef) -> Option { .and_then(|col| col.data_type.as_timestamp().map(|ts| ts.unit())) } +fn set_time_index_unit(create_table_expr: &mut CreateTableExpr, unit: TimeUnit) { + if let Some(column) = create_table_expr + .column_defs + .iter_mut() + .find(|column| column.name == create_table_expr.time_index) + { + column.data_type = api::helper::timestamp_datatype(unit) as i32; + // Timestamp columns never carry a datatype extension. + column.datatype_extension = None; + } +} + fn convert_rows_time_unit(rows: &mut Rows, target_unit: TimeUnit) -> Result<()> { let Some(ts_index) = rows .schema diff --git a/tests-integration/src/grpc.rs b/tests-integration/src/grpc.rs index 904cd0f1116..fca51f24697 100644 --- a/tests-integration/src/grpc.rs +++ b/tests-integration/src/grpc.rs @@ -43,12 +43,14 @@ async fn query_and_expect(instance: &Instance, sql: &str, expected: &str) { #[cfg(test)] mod test { use std::collections::HashMap; - use std::sync::Arc; + use std::sync::{Arc, Mutex}; use api::v1::column::Values; use api::v1::column_data_type_extension::TypeExt; use api::v1::ddl_request::Expr as DdlExpr; use api::v1::greptime_request::Request; + use api::v1::helper::{field_column_schema, row, tag_column_schema, time_index_column_schema}; + use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse}; use api::v1::query_request::Query; use api::v1::region::QueryRequest as RegionQueryRequest; use api::v1::{ @@ -61,30 +63,42 @@ mod test { DefaultPermissionChecker, Identity, Password, PermissionCheckerRef, UserProvider, static_user_provider_from_option, }; + use catalog::process_manager::ProcessManager; use client::OutputData; use common_base::Plugins; use common_catalog::consts::{ DEFAULT_CATALOG_NAME, DEFAULT_PRIVATE_SCHEMA_NAME, MITO_ENGINE, SEMANTIC_RELATIONSHIPS_DECLARED_TABLE_NAME, }; + use common_meta::cache::LayeredCacheRegistryBuilder; + use common_meta::procedure_executor::{ + ExecutorContext, ProcedureExecutor, ProcedureExecutorRef, + }; + use common_meta::rpc::ddl::{DdlTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse}; + use common_meta::rpc::procedure::{ + MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse, + }; use common_meta::rpc::router::region_distribution; use common_query::Output; use common_query::logical_plan::breakup_insert_plan; use common_recordbatch::RecordBatches; use frontend::instance::Instance; + use frontend::instance::builder::FrontendBuilder; use query::parser::QueryLanguageParser; use query::query_engine::DefaultSerializer; use rstest::rstest; use rstest_reuse::apply; + use servers::http::prom_store::PHYSICAL_TABLE_PARAM; use servers::query_handler::grpc::GrpcQueryHandler; - use session::context::{QueryContext, QueryContextBuilder}; + use session::context::{QueryContext, QueryContextBuilder, QueryContextRef}; use store_api::mito_engine_options::TWCS_TIME_WINDOW; use store_api::storage::RegionId; use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan}; + use tokio::sync::oneshot; use super::*; - use crate::standalone::GreptimeDbStandaloneBuilder; - use crate::test_util::execute_sql_and_expect; + use crate::standalone::{GreptimeDbStandalone, GreptimeDbStandaloneBuilder}; + use crate::test_util::{execute_sql, execute_sql_and_expect}; use crate::tests; use crate::tests::MockDistributedInstance; use crate::tests::test_util::{MockInstance, both_instances_cases, distributed, standalone}; @@ -1512,4 +1526,413 @@ CREATE TABLE {table_name} ( let msg = common_error::ext::ErrorExt::output_msg(&err); assert!(msg.contains("auto_create_table"), "unexpected error: {msg}"); } + + /// One row of `table` with a nanosecond timestamp, a value and string tags. + fn metric_row_insert( + table: &str, + ts: i64, + value: f64, + tags: &[(&str, &str)], + ) -> api::v1::RowInsertRequest { + use api::v1::value::ValueData; + use api::v1::{RowInsertRequest, Rows}; + + let mut schema = vec![ + time_index_column_schema("greptime_timestamp", ColumnDataType::TimestampNanosecond), + field_column_schema("greptime_value", ColumnDataType::Float64), + ]; + let mut values = vec![ + ValueData::TimestampNanosecondValue(ts), + ValueData::F64Value(value), + ]; + for (name, value) in tags { + schema.push(tag_column_schema(name, ColumnDataType::String)); + values.push(ValueData::StringValue(value.to_string())); + } + RowInsertRequest { + table_name: table.to_string(), + rows: Some(Rows { + schema, + rows: vec![row(values)], + }), + } + } + + fn row_inserts(inserts: Vec) -> Request { + Request::RowInserts(api::v1::RowInsertRequests { inserts }) + } + + fn row_insert_ctx(physical_table: Option<&str>) -> QueryContextRef { + let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, "public"); + if let Some(physical_table) = physical_table { + ctx.set_extension(PHYSICAL_TABLE_PARAM, physical_table); + } + Arc::new(ctx) + } + + async fn sorted_column_names(instance: &Instance, table: &str) -> Vec { + let table = instance + .catalog_manager() + .table(DEFAULT_CATALOG_NAME, "public", table, None) + .await + .unwrap() + .unwrap(); + let mut names = table + .table_info() + .meta + .schema + .column_schemas() + .iter() + .map(|column| column.name.clone()) + .collect::>(); + names.sort_unstable(); + names + } + + /// Holds the CREATE of `table` after the DDL executor's own existence check + /// until the test releases it. + struct CreateGate { + table: String, + started: oneshot::Sender<()>, + release: oneshot::Receiver<()>, + } + + struct GatedProcedureExecutor { + inner: ProcedureExecutorRef, + gate: Mutex>, + } + + #[async_trait::async_trait] + impl ProcedureExecutor for GatedProcedureExecutor { + async fn submit_ddl_task( + &self, + ctx: ExecutorContext, + request: SubmitDdlTaskRequest, + ) -> common_meta::error::Result { + let creates = match &request.task { + DdlTask::CreateTable(task) => std::slice::from_ref(task), + DdlTask::CreateLogicalTables(tasks) => tasks.as_slice(), + _ => &[], + }; + let gate = { + let mut gate = self.gate.lock().unwrap(); + let gated = gate.as_ref().is_some_and(|gate| { + creates + .iter() + .any(|task| task.create_table.table_name == gate.table) + }); + if gated { gate.take() } else { None } + }; + if let Some(gate) = gate { + gate.started.send(()).unwrap(); + gate.release.await.unwrap(); + } + self.inner.submit_ddl_task(ctx, request).await + } + + async fn migrate_region( + &self, + ctx: &ExecutorContext, + request: MigrateRegionRequest, + ) -> common_meta::error::Result { + self.inner.migrate_region(ctx, request).await + } + + async fn reconcile( + &self, + ctx: &ExecutorContext, + request: ReconcileRequest, + ) -> common_meta::error::Result { + self.inner.reconcile(ctx, request).await + } + + async fn query_procedure_state( + &self, + ctx: &ExecutorContext, + pid: &str, + ) -> common_meta::error::Result { + self.inner.query_procedure_state(ctx, pid).await + } + + async fn list_procedures( + &self, + ctx: &ExecutorContext, + ) -> common_meta::error::Result { + self.inner.list_procedures(ctx).await + } + } + + /// Sends `losing` through a second frontend whose CREATE of `table` waits after + /// the existence check until `winning` has created the table, and returns the + /// result of the losing write. + async fn write_after_losing_create( + standalone: &GreptimeDbStandalone, + table: &str, + (losing, losing_ctx): (api::v1::RowInsertRequest, QueryContextRef), + (winning, winning_ctx): (api::v1::RowInsertRequest, QueryContextRef), + ) -> Output { + let source = standalone.fe_instance(); + let (started, started_rx) = oneshot::channel(); + let (release, release_rx) = oneshot::channel(); + let procedure_executor = Arc::new(GatedProcedureExecutor { + inner: source.procedure_executor().clone(), + gate: Mutex::new(Some(CreateGate { + table: table.to_string(), + started, + release: release_rx, + })), + }); + let cache_registry = Arc::new( + cache::with_default_composite_cache_registry( + LayeredCacheRegistryBuilder::default().add_cache_registry( + cache::build_fundamental_cache_registry(standalone.kv_backend.clone()), + ), + ) + .unwrap() + .build(), + ); + let losing_frontend = FrontendBuilder::new( + standalone.opts.frontend_options(), + standalone.kv_backend.clone(), + cache_registry, + source.catalog_manager().clone(), + source.node_manager().clone(), + procedure_executor, + Arc::new(ProcessManager::new("losing_create".into(), None)), + ) + .try_build() + .await + .unwrap(); + + let mut losing_write = tokio::spawn(async move { + GrpcQueryHandler::do_query(&losing_frontend, row_inserts(vec![losing]), losing_ctx) + .await + }); + tokio::select! { + _ = started_rx => {} + result = &mut losing_write => panic!("the losing write finished before its CREATE: {result:?}"), + } + let output = + GrpcQueryHandler::do_query(source.as_ref(), row_inserts(vec![winning]), winning_ctx) + .await + .unwrap(); + assert!(matches!(output.data, OutputData::AffectedRows(1))); + release.send(()).unwrap(); + losing_write.await.unwrap().unwrap() + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_row_inserts_after_losing_create() { + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("test_row_inserts_after_losing_create") + .build() + .await; + let output = write_after_losing_create( + &standalone, + "race_mito", + ( + metric_row_insert("race_mito", 1_000_000_000, 1.0, &[("host", "a")]), + row_insert_ctx(None), + ), + ( + metric_row_insert("race_mito", 2_000_000_000, 2.0, &[("region", "r")]), + row_insert_ctx(None), + ), + ) + .await; + assert!(matches!(output.data, OutputData::AffectedRows(1))); + + let expected = "\ ++---------------------+----------------+------+--------+ +| greptime_timestamp | greptime_value | host | region | ++---------------------+----------------+------+--------+ +| 1970-01-01T00:00:01 | 1.0 | a | | +| 1970-01-01T00:00:02 | 2.0 | | r | ++---------------------+----------------+------+--------+"; + execute_sql_and_expect( + standalone.fe_instance(), + "SELECT greptime_timestamp, greptime_value, host, region FROM race_mito ORDER BY greptime_timestamp", + expected, + ) + .await; + } + + /// The winner creates the logical table on a nanosecond physical table while + /// the losing write selected a millisecond one. + #[tokio::test(flavor = "multi_thread")] + async fn test_metric_row_inserts_after_losing_create() { + common_telemetry::init_default_ut_logging(); + let standalone = + GreptimeDbStandaloneBuilder::new("test_metric_row_inserts_after_losing_create") + .build() + .await; + let instance = standalone.fe_instance(); + for (table, precision) in [("race_physical_ms", 3), ("race_physical_ns", 9)] { + execute_sql( + instance, + &format!( + "CREATE TABLE {table} (greptime_timestamp TIMESTAMP({precision}) NOT NULL, \ + greptime_value DOUBLE NULL, TIME INDEX (greptime_timestamp)) \ + ENGINE = metric WITH ('physical_metric_table' = 'true')" + ), + ) + .await; + } + let output = write_after_losing_create( + &standalone, + "race_metric", + ( + metric_row_insert("race_metric", 1_000_000_123, 1.0, &[("host", "a")]), + row_insert_ctx(Some("race_physical_ms")), + ), + ( + metric_row_insert("race_metric", 2_000_000_000, 2.0, &[("region", "r")]), + row_insert_ctx(Some("race_physical_ns")), + ), + ) + .await; + assert!(matches!(output.data, OutputData::AffectedRows(1))); + + // The losing row is converted once, to the winner's unit, so it keeps its nanoseconds. + let expected = "\ ++-------------------------------+----------------+------+--------+ +| greptime_timestamp | greptime_value | host | region | ++-------------------------------+----------------+------+--------+ +| 1970-01-01T00:00:01.000000123 | 1.0 | a | | +| 1970-01-01T00:00:02 | 2.0 | | r | ++-------------------------------+----------------+------+--------+"; + execute_sql_and_expect( + instance, + "SELECT greptime_timestamp, greptime_value, host, region FROM race_metric ORDER BY greptime_timestamp", + expected, + ) + .await; + assert_eq!( + sorted_column_names(instance, "race_metric").await, + ["greptime_timestamp", "greptime_value", "host", "region"] + ); + assert_eq!( + sorted_column_names(instance, "race_physical_ns").await, + [ + "__table_id", + "__tsid", + "greptime_timestamp", + "greptime_value", + "host", + "region" + ] + ); + } + + /// Three entries of one batch target the same new logical table, and the + /// later ones bring overlapping new tags. + #[apply(both_instances_cases)] + async fn test_metric_row_inserts_repeated_new_table(instance: Arc) { + let instance = instance.frontend(); + let request = row_inserts(vec![ + metric_row_insert("repeated_metric", 1_000_000_000, 1.0, &[("host", "a")]), + metric_row_insert( + "repeated_metric", + 2_000_000_000, + 2.0, + &[("host", "b"), ("region", "r")], + ), + metric_row_insert( + "repeated_metric", + 3_000_000_000, + 3.0, + &[("region", "s"), ("zone", "z")], + ), + ]); + let output = GrpcQueryHandler::do_query( + instance.as_ref(), + request, + row_insert_ctx(Some("repeated_physical")), + ) + .await + .unwrap(); + assert!(matches!(output.data, OutputData::AffectedRows(3))); + + let expected = "\ ++---------------------+----------------+------+--------+------+ +| greptime_timestamp | greptime_value | host | region | zone | ++---------------------+----------------+------+--------+------+ +| 1970-01-01T00:00:01 | 1.0 | a | | | +| 1970-01-01T00:00:02 | 2.0 | b | r | | +| 1970-01-01T00:00:03 | 3.0 | | s | z | ++---------------------+----------------+------+--------+------+"; + execute_sql_and_expect( + &instance, + "SELECT greptime_timestamp, greptime_value, host, region, zone FROM repeated_metric ORDER BY greptime_timestamp", + expected, + ) + .await; + assert_eq!( + sorted_column_names(&instance, "repeated_metric").await, + [ + "greptime_timestamp", + "greptime_value", + "host", + "region", + "zone" + ] + ); + assert_eq!( + sorted_column_names(&instance, "repeated_physical").await, + [ + "__table_id", + "__tsid", + "greptime_timestamp", + "greptime_value", + "host", + "region", + "zone" + ] + ); + } + + /// Two entries of one batch need different new tags on an existing logical + /// table. Both go into one ALTER, which may name each table once. + #[apply(both_instances_cases)] + async fn test_metric_row_inserts_existing_table_new_tags(instance: Arc) { + let instance = instance.frontend(); + let ctx = row_insert_ctx(Some("existing_physical")); + let requests = [ + vec![metric_row_insert( + "existing_metric", + 1_000_000_000, + 1.0, + &[("host", "a")], + )], + vec![ + metric_row_insert( + "existing_metric", + 2_000_000_000, + 2.0, + &[("host", "b"), ("region", "r")], + ), + metric_row_insert("existing_metric", 3_000_000_000, 3.0, &[("zone", "z")]), + ], + ]; + for request in requests { + GrpcQueryHandler::do_query(instance.as_ref(), row_inserts(request), ctx.clone()) + .await + .unwrap(); + } + + let expected = "\ ++---------------------+----------------+------+--------+------+ +| greptime_timestamp | greptime_value | host | region | zone | ++---------------------+----------------+------+--------+------+ +| 1970-01-01T00:00:01 | 1.0 | a | | | +| 1970-01-01T00:00:02 | 2.0 | b | r | | +| 1970-01-01T00:00:03 | 3.0 | | | z | ++---------------------+----------------+------+--------+------+"; + execute_sql_and_expect( + &instance, + "SELECT greptime_timestamp, greptime_value, host, region, zone FROM existing_metric ORDER BY greptime_timestamp", + expected, + ) + .await; + } } diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 82fa7fd04aa..b003001083a 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -264,6 +264,7 @@ macro_rules! http_tests { test_loki_json_logs_with_pipeline, test_elasticsearch_logs, test_elasticsearch_logs_with_index, + test_elasticsearch_logs_with_new_field, test_elasticsearch_pipeline_version, test_splunk_logs, test_splunk_raw, @@ -16741,6 +16742,59 @@ pub async fn test_elasticsearch_logs_with_index(store_type: StorageType) { guard.remove_all().await; } +pub async fn test_elasticsearch_logs_with_new_field(store_type: StorageType) { + common_telemetry::init_default_ut_logging(); + let (app, mut guard) = + setup_test_http_app_with_frontend(store_type, "test_elasticsearch_logs_with_new_field") + .await; + + let client = TestClient::new(app).await; + + // Every document is its own insert request. The first one creates the table, + // the third one needs a column that table lacks. + let body = r#" + {"create":{"_index":"es_new_field"}} + {"a":"1"} + {"create":{"_index":"es_new_field"}} + {"a":"2"} + {"create":{"_index":"es_new_field"}} + {"b":"3"} + {"create":{"_index":"es_new_field"}} + {"a":"4"} + "#; + + let res = send_req( + &client, + vec![( + HeaderName::from_static("content-type"), + HeaderValue::from_static("application/json"), + )], + "/v1/elasticsearch/_bulk", + body.as_bytes().to_vec(), + false, + ) + .await; + + assert_eq!(StatusCode::OK, res.status()); + let response: Value = serde_json::from_str(&res.text().await).unwrap(); + assert_eq!(response["errors"], json!(false)); + assert_eq!( + response["items"], + json!(vec![json!({"create": {"status": 201}}); 4]) + ); + + let expected = r#"[["1",null],["2",null],[null,"3"],["4",null]]"#; + validate_data( + "test_elasticsearch_logs_with_new_field", + &client, + "select a, b from es_new_field order by coalesce(a, b);", + expected, + ) + .await; + + guard.remove_all().await; +} + pub async fn test_elasticsearch_pipeline_version(store_type: StorageType) { common_telemetry::init_default_ut_logging(); let (app, mut guard) =