diff --git a/Cargo.lock b/Cargo.lock index a5e8e050a72..67de9d76bab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10180,6 +10180,7 @@ dependencies = [ "ahash 0.8.12", "api", "arrow 59.2.0", + "arrow-schema 59.2.0", "async-stream", "async-trait", "axum 0.8.4", diff --git a/src/common/meta/src/ddl/create_table/template.rs b/src/common/meta/src/ddl/create_table/template.rs index 45fcd1a0148..766a32780ba 100644 --- a/src/common/meta/src/ddl/create_table/template.rs +++ b/src/common/meta/src/ddl/create_table/template.rs @@ -17,11 +17,16 @@ use std::collections::HashMap; use api::v1::column_def::try_as_column_def; use api::v1::meta::Partition; use api::v1::region::{CreateRequest, RegionColumnDef}; -use api::v1::{ColumnDef, CreateTableExpr, SemanticType}; +use api::v1::{ColumnDataType, ColumnDef, CreateTableExpr, SemanticType}; +use common_catalog::consts::{MITO_ENGINE, MITO2_ENGINE}; use common_telemetry::warn; use snafu::{OptionExt, ResultExt}; -use store_api::metric_engine_consts::LOGICAL_TABLE_METADATA_KEY; +use store_api::metric_engine_consts::{ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, + PRIMARY_KEY_ENCODING, +}; use store_api::region_request::RegionRequirements; +use store_api::storage::consts::ReservedColumnId; use store_api::storage::{RegionId, RegionNumber}; use table::metadata::{TableId, TableInfo}; @@ -135,6 +140,28 @@ pub fn build_template_from_raw_table_info_for_physical_table( } pub(crate) fn build_template(create_table_expr: &CreateTableExpr) -> Result { + // Explicit sparse identity columns use the same IDs as metric physical regions. + let reserved_prefix = matches!( + create_table_expr.engine.as_str(), + MITO_ENGINE | MITO2_ENGINE + ) && create_table_expr + .table_options + .get(PRIMARY_KEY_ENCODING) + .is_some_and(|value| value.eq_ignore_ascii_case("sparse")) + && create_table_expr.primary_keys.starts_with(&[ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME.into(), + DATA_SCHEMA_TSID_COLUMN_NAME.into(), + ]) + && [ + (DATA_SCHEMA_TABLE_ID_COLUMN_NAME, ColumnDataType::Uint32), + (DATA_SCHEMA_TSID_COLUMN_NAME, ColumnDataType::Uint64), + ] + .into_iter() + .all(|(name, data_type)| { + create_table_expr.column_defs.iter().any(|column| { + column.name == name && column.data_type == data_type as i32 && !column.is_nullable + }) + }); let column_defs = create_table_expr .column_defs .iter() @@ -159,7 +186,13 @@ pub(crate) fn build_template(create_table_expr: &CreateTableExpr) -> Result>(); @@ -280,6 +313,48 @@ mod tests { use super::*; use crate::key::test_utils; + #[test] + fn test_create_sparse_reserved_column_ids() { + let mut expr = CreateTableExpr { + engine: MITO_ENGINE.into(), + table_options: HashMap::from([(PRIMARY_KEY_ENCODING.into(), "sparse".into())]), + primary_keys: vec![ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME.into(), + DATA_SCHEMA_TSID_COLUMN_NAME.into(), + "job".into(), + ], + time_index: "ts".into(), + column_defs: [ + ("ts", ColumnDataType::TimestampMillisecond), + (DATA_SCHEMA_TABLE_ID_COLUMN_NAME, ColumnDataType::Uint32), + (DATA_SCHEMA_TSID_COLUMN_NAME, ColumnDataType::Uint64), + ("job", ColumnDataType::String), + ] + .into_iter() + .map(|(name, data_type)| ColumnDef { + name: name.into(), + data_type: data_type as i32, + is_nullable: false, + ..Default::default() + }) + .collect(), + ..Default::default() + }; + let template = build_template(&expr).unwrap(); + assert_eq!( + template.primary_key, + vec![ReservedColumnId::table_id(), ReservedColumnId::tsid(), 3] + ); + assert_eq!( + template.column_defs[1].column_id, + ReservedColumnId::table_id() + ); + assert_eq!(template.column_defs[2].column_id, ReservedColumnId::tsid()); + // The names alone must not change ordinary dense-table column allocation. + expr.table_options.clear(); + assert_eq!(build_template(&expr).unwrap().primary_key, vec![1, 2, 3]); + } + #[test] fn test_build_one_sets_partition_expr_per_region() { // minimal template diff --git a/src/common/query/src/prelude.rs b/src/common/query/src/prelude.rs index ca70bf5520f..8bb486a2d30 100644 --- a/src/common/query/src/prelude.rs +++ b/src/common/query/src/prelude.rs @@ -91,6 +91,12 @@ pub fn greptime_native_histogram() -> &'static str { const GREPTIME_TIMESTAMP: &str = "greptime_timestamp"; /// Default value column name constant for backward compatibility. const GREPTIME_VALUE: &str = "greptime_value"; +/// Shared exemplar destination within each source metric's schema. +pub const METRICS_EXEMPLARS_TABLE: &str = "metrics_exemplars"; +/// Query-visible source metric name stored in the exemplar table. +pub const EXEMPLAR_METRIC_COLUMN: &str = "greptime_metric"; +/// JSON2 object containing exemplar-owned labels. +pub const EXEMPLAR_LABELS_COLUMN: &str = "exemplar_labels"; /// Stored series label that opts ordinary float samples into raw-delta math. pub const OTLP_AGGREGATION_TEMPORALITY_LABEL: &str = "otlp_aggregation_temporality"; /// Authoritative raw-delta value for [`OTLP_AGGREGATION_TEMPORALITY_LABEL`]. diff --git a/src/frontend/src/instance/prom_store.rs b/src/frontend/src/instance/prom_store.rs index 94687238ed0..a5e4c30b832 100644 --- a/src/frontend/src/instance/prom_store.rs +++ b/src/frontend/src/instance/prom_store.rs @@ -514,6 +514,75 @@ impl Instance { #[async_trait] impl PromStoreProtocolHandler for Instance { + async fn prepare_metric_write( + &self, + request: RowInsertRequests, + ctx: QueryContextRef, + ) -> ServerResult { + let physical_table = ctx + .extension(PHYSICAL_TABLE_PARAM) + .unwrap_or(GREPTIME_PHYSICAL_TABLE) + .to_string(); + self.inserter + .prepare_metric_row_inserts(request, ctx, &self.statement_executor, physical_table) + .await + .map_err(BoxedError::new) + .context(error::ExecuteGrpcQuerySnafu) + } + + async fn write_prepared_metric( + &self, + request: operator::insert::PreparedMetricInserts, + ctx: QueryContextRef, + ) -> ServerResult { + self.inserter + .handle_prepared_metric_inserts(request, ctx) + .await + .map_err(BoxedError::new) + .context(error::ExecuteGrpcQuerySnafu) + } + + async fn check_exemplar_sources( + &self, + sources: &std::collections::BTreeSet, + ctx: QueryContextRef, + ) -> ServerResult<()> { + let targets = sources + .iter() + .map(|name| { + PermissionTableTarget::new(ctx.current_catalog(), ctx.current_schema(), name) + }) + .collect(); + self.check_table_permission( + &ctx, + PermissionReq::Action(PROM_STORE_WRITE), + PermissionTableTargets::resolved(targets), + ) + .context(AuthSnafu)?; + Ok(()) + } + + async fn write_exemplars_prepared( + &self, + request: RowInsertRequests, + ctx: QueryContextRef, + ) -> ServerResult { + self.write_exemplars_with_sources(request, ctx, &[]).await + } + + async fn write_exemplars_with_sources( + &self, + request: RowInsertRequests, + ctx: QueryContextRef, + sources: &[table::metadata::TableInfoRef], + ) -> ServerResult { + self.inserter + .handle_exemplar_inserts(request, ctx, &self.statement_executor, sources) + .await + .map_err(BoxedError::new) + .context(error::ExecuteGrpcQuerySnafu) + } + async fn pre_write( &self, request: &RowInsertRequests, diff --git a/src/metric-engine/src/row_modifier.rs b/src/metric-engine/src/row_modifier.rs index 7d68f94aa0f..04f82a199fd 100644 --- a/src/metric-engine/src/row_modifier.rs +++ b/src/metric-engine/src/row_modifier.rs @@ -196,25 +196,12 @@ impl RowModifier { } ts_id_gen.finish() } else { - // Slow path: row contains null, recompute label hash - let mut hasher = TsidGenerator::default(); - // 1. Find out label names with non-null values and get the hash. - for (name, value) in iter.primary_keys_with_name() { - // The type is checked before. So only null is ignored. - if let Some(ValueData::StringValue(_)) = &value.value_data { - hasher.write_str(name); - } - } - let label_name_hash = hasher.finish(); - - // 2. Use label name hash as seed and continue with label values. - let mut final_hasher = TsidGenerator::new(label_name_hash); - for (_, value) in iter.primary_keys_with_name() { - if let Some(ValueData::StringValue(value)) = &value.value_data { - final_hasher.write_str(value); - } - } - final_hasher.finish() + TsidGenerator::from_sorted_tags(iter.primary_keys_with_name().filter_map( + |(name, value)| match &value.value_data { + Some(ValueData::StringValue(value)) => Some((name.as_str(), value.as_str())), + _ => None, + }, + )) }; ( @@ -231,6 +218,19 @@ pub struct TsidGenerator { } impl TsidGenerator { + /// Computes the metric TSID from non-null tags sorted by name, retaining empty values. + pub fn from_sorted_tags<'a>(tags: impl Iterator + Clone) -> u64 { + let mut names = Self::default(); + for (name, _) in tags.clone() { + names.write_str(name); + } + let mut values = Self::new(names.finish()); + for (_, value) in tags { + values.write_str(value); + } + values.finish() + } + pub fn new(label_name_hash: u64) -> Self { let mut hasher = FxHasher::default(); hasher.write_u64(label_name_hash); @@ -376,7 +376,7 @@ pub struct RowIter<'a> { impl RowIter<'_> { /// Returns the primary keys with their names. - fn primary_keys_with_name(&self) -> impl Iterator { + fn primary_keys_with_name(&self) -> impl Iterator + Clone { self.index.indices[..self.index.num_primary_key_column] .iter() .map(|idx| { @@ -790,6 +790,34 @@ mod tests { ); } + #[test] + fn test_sorted_tags_match_metric_rows() { + let names = ["b", "a", "absent"]; + for values in [ + [Some("B"), Some(""), Some("C")], + [Some("B"), Some(""), None], + [None, Some("A"), None], + [None, None, None], + ] { + let tags = names + .into_iter() + .zip(values) + .filter_map(|(name, value)| value.map(|value| (name, value))) + .collect::>(); + let tsid = + TsidGenerator::from_sorted_tags(tags.iter().map(|(name, value)| (*name, *value))); + assert_eq!( + tsid, + extract_tsid( + create_multi_label_schema(&names), + create_row_with_nulls(&values), + &create_name_to_column_id(&names), + 42 + ) + ); + } + } + #[test] fn test_tsid_same_with_multiple_null_labels() { // Test with multiple null labels diff --git a/src/operator/Cargo.toml b/src/operator/Cargo.toml index b89bf4b13d3..56c18a15f11 100644 --- a/src/operator/Cargo.toml +++ b/src/operator/Cargo.toml @@ -22,6 +22,7 @@ workspace = true ahash.workspace = true api.workspace = true arrow.workspace = true +arrow-schema.workspace = true async-stream.workspace = true async-trait.workspace = true backon.workspace = true diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs index 5ecc01457a1..6e921577b7c 100644 --- a/src/operator/src/insert.rs +++ b/src/operator/src/insert.rs @@ -34,6 +34,7 @@ use api::v1::{ RowInsertRequest, RowInsertRequests, Rows, SemanticType, }; use arrow::datatypes::{DataType as ArrowDataType, Schema as ArrowSchema}; +use arrow_schema::extension::ExtensionType; use catalog::CatalogManagerRef; use client::{OutputData, OutputMeta}; use common_base::readable_size::ReadableSize; @@ -52,12 +53,17 @@ use common_meta::peer::Peer; use common_meta::rpc::ddl::TriggerReason; use common_query::Output; use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type}; -use common_query::prelude::{greptime_timestamp, greptime_value}; +use common_query::prelude::{ + EXEMPLAR_LABELS_COLUMN, EXEMPLAR_METRIC_COLUMN, METRICS_EXEMPLARS_TABLE, greptime_timestamp, + greptime_value, +}; use common_telemetry::tracing_context::TracingContext; use common_telemetry::{debug, error, warn}; use common_time::Timestamp; use common_time::timestamp::TimeUnit; -use datatypes::schema::{ColumnEncoding, CompressionOptions, SkippingIndexOptions}; +use datatypes::schema::{ + ColumnDefaultConstraint, ColumnEncoding, CompressionOptions, SkippingIndexOptions, +}; use futures_util::future; use meter_core::data::MeterRecord; use meter_macros::write_meter; @@ -69,12 +75,14 @@ use sql::partition::partition_rule_for_hexstring; use sql::statements::create::Partitions; use sql::statements::insert::Insert; use store_api::metric_engine_consts::{ - LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY, + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, + METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY, }; use store_api::mito_engine_options::{ APPEND_MODE_KEY, COMPACTION_OPTION_KEYS, COMPACTION_TWCS_PREFIX, COMPACTION_TYPE, COMPACTION_TYPE_TWCS, MERGE_MODE_KEY, TTL_KEY, }; +use store_api::storage::consts::ReservedColumnId; use store_api::storage::{RegionId, TableId}; use table::TableRef; use table::metadata::{TableInfo, TableInfoRef}; @@ -128,6 +136,8 @@ pub enum AutoCreateTableType { Logical(String), /// A physical table. Physical, + /// The ordinary sparse append table for metric exemplars. + Exemplar, /// A log table which is append-only. Log, /// A table that merges rows by `last_non_null` strategy. @@ -141,6 +151,7 @@ impl AutoCreateTableType { match self { AutoCreateTableType::Logical(_) => "logical", AutoCreateTableType::Physical => "physical", + AutoCreateTableType::Exemplar => "exemplar", AutoCreateTableType::Log => "log", AutoCreateTableType::LastNonNull => "last_non_null", AutoCreateTableType::Trace { .. } => "trace", @@ -163,7 +174,7 @@ impl AutoCreateTableType { /// and normal requests are requests with ttl set to other values. /// /// This is used to split requests for different processing. -#[derive(Clone)] +#[derive(Clone, Default)] pub struct InstantAndNormalInsertRequests { /// Requests with normal ttl. pub normal_requests: RegionInsertRequests, @@ -172,6 +183,20 @@ pub struct InstantAndNormalInsertRequests { pub instant_requests: RegionInsertRequests, } +/// Metric writes bound to the same resolved tables used by their exemplars. +#[derive(Default)] +pub struct PreparedMetricInserts { + requests: InstantAndNormalInsertRequests, + table_infos: HashMap, +} + +impl PreparedMetricInserts { + /// Returns the source tables captured during routing, including auto-created tables. + pub fn source_tables(&self) -> impl Iterator { + self.table_infos.values() + } +} + impl Inserter { /// Checks the assumptions of the logical bulk path without changing tables. /// Unsupported requests retain ordinary insertion, including schema policy, @@ -369,6 +394,119 @@ impl Inserter { .await } + /// Inserts exemplars using ordinary Mito storage and nanosecond auto-create defaults. + pub async fn handle_exemplar_inserts( + &self, + mut requests: RowInsertRequests, + ctx: QueryContextRef, + statement_executor: &StatementExecutor, + sources: &[TableInfoRef], + ) -> Result { + ensure!( + requests + .inserts + .iter() + .all(|r| r.table_name == METRICS_EXEMPLARS_TABLE), + InvalidInsertRequestSnafu { + reason: "invalid exemplar destination" + } + ); + self.bind_exemplar_table_ids(&mut requests, &ctx, sources) + .await?; + preprocess_row_insert_requests(&mut requests.inserts)?; + self.handle_row_inserts_with_create_type( + requests, + ctx, + statement_executor, + AutoCreateTableType::Exemplar, + false, + false, + ) + .await + } + + async fn bind_exemplar_table_ids( + &self, + requests: &mut RowInsertRequests, + ctx: &QueryContextRef, + sources: &[TableInfoRef], + ) -> Result<()> { + validate_column_count_match(requests)?; + let mut tables = HashMap::new(); + for info in sources.iter().filter(|info| { + info.catalog_name == ctx.current_catalog() && info.schema_name == ctx.current_schema() + }) { + if let Some(previous) = tables.insert(info.name.clone(), info.clone()) { + ensure!( + previous.table_id() == info.table_id(), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {} changed during write preparation", + info.name + ), + } + ); + } + } + for request in &mut requests.inserts { + let Some(rows) = request.rows.as_mut() else { + continue; + }; + ensure!( + !rows + .schema + .iter() + .any(|c| c.column_name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME), + InvalidInsertRequestSnafu { + reason: "exemplar table IDs must be resolved from their source tables", + } + ); + let metric_index = rows + .schema + .iter() + .position(|c| c.column_name == EXEMPLAR_METRIC_COLUMN) + .context(InvalidInsertRequestSnafu { + reason: "missing exemplar source metric", + })?; + for row in &mut rows.rows { + let Some(ValueData::StringValue(name)) = &row.values[metric_index].value_data + else { + return InvalidInsertRequestSnafu { + reason: "invalid exemplar source metric", + } + .fail(); + }; + if !tables.contains_key(name) { + let table = self.get_table(ctx.current_catalog(), &ctx.current_schema(), name).await? + .with_context(|| InvalidInsertRequestSnafu { + reason: format!("exemplar source {name} must be an existing logical metric-engine table"), + })?; + tables.insert(name.clone(), table.table_info()); + } + let info = &tables[name]; + ensure!( + info.meta.engine == METRIC_ENGINE_NAME + && info + .meta + .options + .extra_options + .contains_key(LOGICAL_TABLE_METADATA_KEY), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {name} must be an existing logical metric-engine table" + ), + } + ); + row.values.push(ValueData::U32Value(info.table_id()).into()); + } + rows.schema.push(api::v1::helper::tag_column_schema( + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + ColumnDataType::Uint32, + )); + } + Ok(()) + } + /// Handles row inserts request and creates a log table on demand. pub async fn handle_log_inserts( &self, @@ -437,6 +575,8 @@ impl Inserter { is_single_value: bool, ) -> Result { let skip_wal = ctx.skip_wal(); + let align_time_index_unit = + matches!(create_type, AutoCreateTableType::Exemplar).then_some(TimeUnit::Nanosecond); let batcher = self .pending_rows_batcher @@ -463,7 +603,7 @@ impl Inserter { statement_executor, accommodate_existing_schema, is_single_value, - None, + align_time_index_unit, ) .await?; @@ -610,11 +750,25 @@ impl Inserter { /// Existing targets retain their backing tables and time-index units. pub async fn handle_metric_row_inserts( &self, - mut requests: RowInsertRequests, + requests: RowInsertRequests, ctx: QueryContextRef, statement_executor: &StatementExecutor, physical_table: String, ) -> Result { + let prepared = self + .prepare_metric_row_inserts(requests, ctx.clone(), statement_executor, physical_table) + .await?; + self.handle_prepared_metric_inserts(prepared, ctx).await + } + + /// Resolves schemas and routes metric rows before dependent exemplar writes start. + pub async fn prepare_metric_row_inserts( + &self, + mut requests: RowInsertRequests, + ctx: QueryContextRef, + statement_executor: &StatementExecutor, + physical_table: String, + ) -> Result { let skip_wal = ctx.skip_wal(); // remove empty requests @@ -672,7 +826,20 @@ impl Inserter { .convert(requests, skip_wal) .await?; - self.do_request(inserts, &table_infos, &ctx).await + Ok(PreparedMetricInserts { + requests: inserts, + table_infos, + }) + } + + /// Dispatches metric rows using the source table definitions captured during preparation. + pub async fn handle_prepared_metric_inserts( + &self, + prepared: PreparedMetricInserts, + ctx: QueryContextRef, + ) -> Result { + self.do_request(prepared.requests, &prepared.table_infos, &ctx) + .await } fn table_batcher( @@ -779,6 +946,7 @@ pub async fn admit_row_insert_batches( for (ctx, requests) in batches.iter() { let catalog = ctx.current_catalog(); let schema = ctx.current_schema(); + if ctx.write_rows_to_admit(catalog, &schema, 1) == 0 { continue; } @@ -1123,6 +1291,7 @@ impl Inserter { is_single_value: bool, align_time_index_unit: Option, ) -> Result { + let is_exemplar = matches!(&auto_create_table_type, AutoCreateTableType::Exemplar); let _timer = crate::metrics::CREATE_ALTER_ON_DEMAND .with_label_values(&[auto_create_table_type.as_str()]) .start_timer(); @@ -1162,16 +1331,19 @@ impl Inserter { .fail(); } }; - // Metric path: an existing destination table keeps its own - // time index unit (it may be bound to another physical - // table than the one selected by this request). - if matches!(auto_create_table_type, AutoCreateTableType::Logical(_)) - && let Some(rows) = req.rows.as_mut() + // Existing metric and exemplar destinations keep their time index unit. + if matches!( + auto_create_table_type, + AutoCreateTableType::Logical(_) | AutoCreateTableType::Exemplar + ) && let Some(rows) = req.rows.as_mut() && let Some(target_unit) = table_time_index_unit(&table) { convert_rows_time_unit(rows, target_unit)?; } let table_info = table.table_info(); + if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) { + validate_exemplar_table(&table_info)?; + } if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) { validate_trace_table_model(&table_info, ctx)?; } @@ -1200,6 +1372,9 @@ impl Inserter { match self.get_table(catalog, &schema, &req.table_name).await? { Some(table) => { let table_info = table.table_info(); + if matches!(auto_create_table_type, AutoCreateTableType::Exemplar) { + validate_exemplar_table(&table_info)?; + } if matches!(auto_create_table_type, AutoCreateTableType::Trace { .. }) { validate_trace_table_model(&table_info, ctx)?; } @@ -1306,6 +1481,7 @@ impl Inserter { } } AutoCreateTableType::Physical + | AutoCreateTableType::Exemplar | AutoCreateTableType::Log | AutoCreateTableType::LastNonNull => { // note that auto create table shouldn't be ttl instant table @@ -1314,6 +1490,33 @@ 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) { + 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()); @@ -1484,9 +1687,32 @@ impl Inserter { ), })?; let table_info = table.table_info(); + if is_exemplar { + validate_exemplar_table(&table_info)?; + } table_infos.insert(table_info.table_id(), table.table_info()); } + if is_exemplar { + for info in table_infos.values() { + if let Some(unit) = info + .meta + .schema + .timestamp_column() + .and_then(|column| column.data_type.as_timestamp()) + .map(|timestamp| timestamp.unit()) + { + for request in &mut requests.inserts { + if request.table_name == info.name + && let Some(rows) = request.rows.as_mut() + { + convert_rows_time_unit(rows, unit)?; + } + } + } + } + } + Ok(CreateAlterTableResult { instant_table_ids, table_infos, @@ -1589,12 +1815,14 @@ impl Inserter { let schema = ctx.current_schema(); let mut table_options = std::collections::HashMap::with_capacity(4); fill_table_options_for_create(&mut table_options, create_type, ctx); - apply_per_table_semantic_options( - &mut table_options, - semantic_index, - ctx.current_schema().as_str(), - &req.table_name, - ); + if !matches!(create_type, AutoCreateTableType::Exemplar) { + apply_per_table_semantic_options( + &mut table_options, + semantic_index, + ctx.current_schema().as_str(), + &req.table_name, + ); + } let engine_name = if let AutoCreateTableType::Logical(_) = create_type { // engine should be metric engine when creating logical tables. @@ -1609,6 +1837,26 @@ impl Inserter { let mut create_table_expr = build_create_table_expr(&table_ref, request_schema, engine_name)?; + if matches!(create_type, AutoCreateTableType::Exemplar) { + // Preserve the stored schema order without shifting every incoming row. + create_table_expr + .column_defs + .sort_by_key(|column| column.name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME); + create_table_expr + .primary_keys + .sort_by_key(|name| name != DATA_SCHEMA_TABLE_ID_COLUMN_NAME); + for column in &mut create_table_expr.column_defs { + if [ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + DATA_SCHEMA_TSID_COLUMN_NAME, + ] + .contains(&column.name.as_str()) + { + column.is_nullable = false; + } + } + } + // extension set by the Splunk HEC handler for identity path if ctx.extension(SPLUNK_PK_METADATA_ORDER_KEY).is_some() { reorder_splunk_primary_keys(&mut create_table_expr.primary_keys); @@ -1947,6 +2195,145 @@ fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> { Ok(()) } +/// Validates the fixed exemplar contract before writing or scanning a shared table. +pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> { + let meta = &table.meta; + let options = &meta.options.extra_options; + ensure!( + meta.engine == default_engine() + && options + .get(APPEND_MODE_KEY) + .is_some_and(|v| v.eq_ignore_ascii_case("true")) + && options + .get(store_api::metric_engine_consts::PRIMARY_KEY_ENCODING) + .is_some_and(|v| v.eq_ignore_ascii_case("sparse")), + InvalidInsertRequestSnafu { + reason: "metrics_exemplars requires Mito, append_mode=true and primary_key_encoding=sparse" + } + ); + let columns = meta.schema.column_schemas(); + let lookup = |name: &str| { + columns + .iter() + .enumerate() + .find(|(_, c)| c.name == name) + .with_context(|| InvalidInsertRequestSnafu { + reason: format!("missing exemplar column {name}"), + }) + }; + let (_, timestamp) = lookup(greptime_timestamp())?; + for (position, name, id, data_type) in [ + ( + 0, + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + ReservedColumnId::table_id(), + datatypes::prelude::ConcreteDataType::uint32_datatype(), + ), + ( + 1, + DATA_SCHEMA_TSID_COLUMN_NAME, + ReservedColumnId::tsid(), + datatypes::prelude::ConcreteDataType::uint64_datatype(), + ), + ] { + let (index, column) = lookup(name)?; + ensure!( + meta.primary_key_indices.get(position) == Some(&index) + && meta.column_ids.get(index) == Some(&id) + && column.data_type == data_type + && !column.is_nullable() + && column.default_constraint().is_none(), + InvalidInsertRequestSnafu { + reason: format!("invalid exemplar source identity column {name}"), + } + ); + } + ensure!( + timestamp.is_time_index() && timestamp.data_type.is_timestamp(), + InvalidInsertRequestSnafu { + reason: "invalid exemplar time index" + } + ); + let (metric_index, metric) = lookup(EXEMPLAR_METRIC_COLUMN)?; + ensure!( + metric.data_type.is_string() && meta.primary_key_indices.contains(&metric_index), + InvalidInsertRequestSnafu { + reason: "exemplar metric name must be a string tag" + } + ); + let (value_index, value) = lookup(greptime_value())?; + ensure!( + value.data_type == datatypes::prelude::ConcreteDataType::float64_datatype() + && !meta.primary_key_indices.contains(&value_index), + InvalidInsertRequestSnafu { + reason: "exemplar value must be a DOUBLE field" + } + ); + let (labels_index, labels) = lookup(EXEMPLAR_LABELS_COLUMN)?; + ensure!( + labels.data_type.is_json2() && !meta.primary_key_indices.contains(&labels_index), + InvalidInsertRequestSnafu { + reason: "exemplar_labels must be a JSON2 field" + } + ); + if let Some(extension) = labels + .extension_type::() + .map_err(|error| { + InvalidInsertRequestSnafu { + reason: error.to_string(), + } + .build() + })? + { + ensure!( + extension + .metadata() + .json_settings() + .type_hints() + .iter() + .all(|hint| hint.path.len() == 1 && hint.data_type.is_string()), + InvalidInsertRequestSnafu { + reason: "exemplar JSON2 hints must preserve string labels" + } + ); + } + for (index, column) in columns.iter().enumerate() { + if [ + greptime_timestamp(), + greptime_value(), + EXEMPLAR_METRIC_COLUMN, + EXEMPLAR_LABELS_COLUMN, + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + DATA_SCHEMA_TSID_COLUMN_NAME, + ] + .contains(&column.name.as_str()) + { + continue; + } + ensure!( + meta.primary_key_indices.contains(&index) + && column.data_type.is_string() + && column.is_nullable(), + InvalidInsertRequestSnafu { + reason: "inherited exemplar labels must be nullable string tags" + } + ); + // An absent inherited label must remain absent from the source series identity. + ensure!( + matches!( + column.default_constraint(), + None | Some(ColumnDefaultConstraint::Value( + datatypes::value::Value::Null + )) + ), + InvalidInsertRequestSnafu { + reason: "inherited exemplar labels must not have non-NULL defaults" + } + ); + } + Ok(()) +} + /// Rejects writes from a different built-in trace model before schema mutation. /// Unstamped, explicitly created tables remain subject to normal schema validation. pub fn validate_trace_table_model(table_info: &TableInfo, ctx: &QueryContextRef) -> Result<()> { @@ -2010,6 +2397,21 @@ pub fn fill_table_options_for_create( physical_table.clone(), ); } + AutoCreateTableType::Exemplar => { + table_options.retain(|key, _| { + !is_semantic_option_key(key) + && key != SEMANTIC_PER_TABLE_INDEX_KEY + && key != LOGICAL_TABLE_METADATA_KEY + && key != PHYSICAL_TABLE_METADATA_KEY + && key != MERGE_MODE_KEY + && key != "otlp_metric_compat" + }); + table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string()); + table_options.insert( + store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.to_string(), + "sparse".to_string(), + ); + } AutoCreateTableType::Physical => { if let Some(append_mode) = ctx.extension(APPEND_MODE_KEY) { table_options.insert(APPEND_MODE_KEY.to_string(), append_mode.to_string()); @@ -3454,6 +3856,39 @@ mod tests { assert!(!table_options.contains_key("compaction.unknown")); } + #[test] + fn test_exemplar_create_options_isolate_metric_context() { + let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); + for (key, value) in [ + (APPEND_MODE_KEY, "false"), + (MERGE_MODE_KEY, "last_non_null"), + (PHYSICAL_TABLE_METADATA_KEY, "true"), + (LOGICAL_TABLE_METADATA_KEY, "physical_metrics"), + ("otlp_metric_compat", "prometheus"), + (table::requests::SEMANTIC_SIGNAL_TYPE, "metric"), + (SEMANTIC_PER_TABLE_INDEX_KEY, "{}"), + ("ttl", "7d"), + ("compaction.twcs.time_window", "1h"), + ] { + ctx.set_extension(key, value); + } + let mut options = Default::default(); + fill_table_options_for_create(&mut options, &AutoCreateTableType::Exemplar, &Arc::new(ctx)); + assert_eq!( + options, + std::collections::HashMap::from([ + (APPEND_MODE_KEY.into(), "true".into()), + ( + store_api::metric_engine_consts::PRIMARY_KEY_ENCODING.into(), + "sparse".into() + ), + ("ttl".into(), "7d".into()), + (COMPACTION_TYPE.into(), "twcs".into()), + ("compaction.twcs.time_window".into(), "1h".into()), + ]) + ); + } + #[test] fn test_skip_wal_does_not_change_table_options() { check_skip_wal_does_not_change_table_options(false); diff --git a/src/servers/src/batcher/logical_table.rs b/src/servers/src/batcher/logical_table.rs index 26277c43406..707afe2ea0f 100644 --- a/src/servers/src/batcher/logical_table.rs +++ b/src/servers/src/batcher/logical_table.rs @@ -19,7 +19,7 @@ mod pending_worker; mod region_write; mod tables; #[cfg(test)] -mod test_util; +pub(crate) mod test_util; use std::collections::{HashMap, HashSet}; use std::future::{Future, ready}; @@ -173,6 +173,10 @@ impl LogicalTablePendingRowsBatcher { } impl LogicalTablePendingRowsBatcher { + pub(crate) fn is_synchronous(&self) -> bool { + self.pending_rows_batch_sync + } + pub async fn submit(&self, requests: RowInsertRequests, ctx: QueryContextRef) -> Result { self.submit_with(requests, ctx, |_| ready(Ok(()))) .await @@ -210,9 +214,9 @@ impl LogicalTablePendingRowsBatcher { /// table. Time index units need no check here — the bulk encode converts /// each request to its destination's unit. Destinations are resolved /// once per distinct (schema, table). - pub(crate) async fn accepts_bulk_destinations( + pub(crate) async fn accepts_bulk_destinations<'a>( &self, - batches: impl Iterator, + batches: impl Iterator, ) -> bool { // One request can select different physical tables per batch (e.g. // per-series physical-table labels), so the dedupe key includes the @@ -469,9 +473,7 @@ impl Drop for LogicalTablePendingRowsBatcher { #[cfg(test)] mod tests { use std::future::ready; - use std::num::NonZeroUsize; use std::sync::Arc; - use std::time::Duration; use api::v1::value::ValueData; use api::v1::{ @@ -481,99 +483,27 @@ mod tests { use arrow::array::{StringArray, TimestampMillisecondArray}; use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema}; use arrow::record_batch::RecordBatch; - use catalog::memory::MemoryCatalogManager; use common_error::ext::{BoxedError, ErrorExt}; use common_error::status_code::StatusCode; - use common_meta::test_util::MockDatanodeManager; use common_query::WriteProgress; use common_query::prelude::greptime_timestamp; - use datatypes::prelude::ConcreteDataType; - use datatypes::schema::{ColumnSchema as DtColumnSchema, Schema as DtSchema}; - use operator::test_util::{create_partition_rule_manager, prepare_mocked_backend}; - use operator::write_dispatcher::WriteDispatcher; - use session::context::{QueryContext, QueryContextRef}; - use table::dist_table::DistTable; - use table::test_util::table_info::test_table_info; + use session::context::QueryContext; use crate::batcher::logical_table::batch_convert::{RecordBatchWithTsIdx, TableBatch}; use crate::batcher::logical_table::flow_notifier::extract_timestamps; use crate::batcher::logical_table::pending_worker::WorkerCommand; - use crate::batcher::logical_table::test_util::{mock_aligned_tag_batch, mock_tag_batch}; - use crate::batcher::logical_table::{ - LogicalTablePendingRowsBatcher, PendingRowsSchemaAlterer, batch_key_from_ctx, + use crate::batcher::logical_table::test_util::{ + mock_aligned_tag_batch, mock_tag_batch, submission_batcher, }; - use crate::batcher::test_util::mock_table_flownode_cache; use crate::error; - struct UnexpectedSchemaAlterer; - - #[async_trait::async_trait] - impl PendingRowsSchemaAlterer for UnexpectedSchemaAlterer { - async fn create_tables_if_missing_batch( - &self, - _: &str, - _: &str, - _: &[(&str, &[ColumnSchema])], - _: bool, - _: QueryContextRef, - ) -> error::Result<()> { - unreachable!() - } - - async fn add_missing_prom_tag_columns_batch( - &self, - _: &str, - _: &str, - _: &[(&str, &[String])], - _: QueryContextRef, - ) -> error::Result<()> { - unreachable!() - } - } - - async fn submission_batcher(sync: bool) -> Arc { - let schema = DtSchema::try_new(vec![ - DtColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ) - .with_time_index(true), - DtColumnSchema::new("value", ConcreteDataType::float64_datatype(), true), - ]) - .unwrap(); - let table = test_table_info(1, "cpu", "public", "greptime", Arc::new(schema)); - let catalog = MemoryCatalogManager::new_with_table(DistTable::table(Arc::new(table))); - let partitions = create_partition_rule_manager(prepare_mocked_backend().await).await; - let nodes = Arc::new(MockDatanodeManager::new(())); - let dispatcher = Arc::new(WriteDispatcher::new(nodes.clone(), partitions.clone())); - let mut batcher = LogicalTablePendingRowsBatcher::try_new( - partitions, - nodes, - dispatcher, - catalog, - mock_table_flownode_cache(1, vec![]).await, - true, - Arc::new(UnexpectedSchemaAlterer), - Duration::from_secs(1), - 2, - 1, - 1, - 1, - NonZeroUsize::new(1).unwrap(), - ) - .unwrap(); - Arc::get_mut(&mut batcher).unwrap().pending_rows_batch_sync = sync; - batcher - } - fn submission_requests() -> RowInsertRequests { RowInsertRequests { inserts: vec![RowInsertRequest { table_name: "cpu".to_string(), rows: Some(Rows { schema: vec![ColumnSchema { - column_name: "ts".to_string(), + column_name: "greptime_timestamp".to_string(), datatype: ColumnDataType::TimestampMillisecond as i32, semantic_type: SemanticType::Timestamp as i32, ..Default::default() @@ -610,18 +540,13 @@ mod tests { for confirmed in [false, true] { for sync in [false, true] { for affected_rows in [0, 1, 2] { - let batcher = submission_batcher(sync).await; + let (batcher, mut receiver) = submission_batcher(sync).await; let ctx = QueryContext::arc(); let ctx = if confirmed { Arc::new(ctx.with_confirmed_writes()) } else { ctx }; - let (_, receiver) = batcher - .workers - .get_or_create(batch_key_from_ctx(&ctx), 1) - .await; - let mut receiver = receiver.unwrap(); let submit = batcher.submit_with(submission_requests(), ctx, |_| ready(Ok(7))); tokio::pin!(submit); let mut early_result = None; @@ -663,13 +588,8 @@ mod tests { #[tokio::test] async fn test_submit_output_with_preserves_confirmed_partial_progress() { for sync in [false, true] { - let batcher = submission_batcher(sync).await; + let (batcher, mut receiver) = submission_batcher(sync).await; let ctx = Arc::new(QueryContext::arc().with_confirmed_writes()); - let (_, receiver) = batcher - .workers - .get_or_create(batch_key_from_ctx(&ctx), 1) - .await; - let mut receiver = receiver.unwrap(); let (output, prepared) = batcher .submit_output_with(submission_requests(), ctx, |_| ready(Ok(7))) .await diff --git a/src/servers/src/batcher/logical_table/test_util.rs b/src/servers/src/batcher/logical_table/test_util.rs index 491bd6ff2b3..364cf0c8f5a 100644 --- a/src/servers/src/batcher/logical_table/test_util.rs +++ b/src/servers/src/batcher/logical_table/test_util.rs @@ -13,8 +13,11 @@ // limitations under the License. use std::collections::HashMap; +use std::num::NonZeroUsize; use std::sync::Arc; +use std::time::Duration; +use api::v1::ColumnSchema; use api::v1::flow::{DirtyWindowRequests, FlowRequest, FlowResponse}; use api::v1::meta::Peer; use api::v1::region::InsertRequests; @@ -22,13 +25,106 @@ use arrow::array::{StringArray, TimestampMillisecondArray}; use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema}; use arrow::record_batch::RecordBatch; use async_trait::async_trait; +use catalog::memory::MemoryCatalogManager; use common_meta::error::Result as MetaResult; use common_meta::node_manager::{ DatanodeManager, DatanodeRef, Flownode, FlownodeManager, FlownodeRef, }; +use common_meta::test_util::MockDatanodeManager; +use common_query::prelude::GREPTIME_PHYSICAL_TABLE; +use datatypes::prelude::ConcreteDataType; +use datatypes::schema::{ColumnSchema as DtColumnSchema, Schema as DtSchema}; +use operator::test_util::{create_partition_rule_manager, prepare_mocked_backend}; +use operator::write_dispatcher::WriteDispatcher; +use session::context::{QueryContext, QueryContextRef}; +use store_api::metric_engine_consts::{LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME}; +use table::dist_table::DistTable; +use table::test_util::table_info::test_table_info; use tokio::sync::mpsc; use crate::batcher::logical_table::batch_convert::RecordBatchWithTsIdx; +pub(crate) use crate::batcher::logical_table::pending_worker::WorkerCommand; +use crate::batcher::logical_table::{ + LogicalTablePendingRowsBatcher, PendingRowsSchemaAlterer, batch_key_from_ctx, +}; +use crate::batcher::test_util::mock_table_flownode_cache; +use crate::error; + +struct UnexpectedSchemaAlterer; + +#[async_trait] +impl PendingRowsSchemaAlterer for UnexpectedSchemaAlterer { + async fn create_tables_if_missing_batch( + &self, + _: &str, + _: &str, + _: &[(&str, &[ColumnSchema])], + _: bool, + _: QueryContextRef, + ) -> error::Result<()> { + unreachable!() + } + + async fn add_missing_prom_tag_columns_batch( + &self, + _: &str, + _: &str, + _: &[(&str, &[String])], + _: QueryContextRef, + ) -> error::Result<()> { + unreachable!() + } +} + +pub(crate) async fn submission_batcher( + sync: bool, +) -> ( + Arc, + mpsc::Receiver, +) { + let schema = DtSchema::try_new(vec![ + DtColumnSchema::new( + "greptime_timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + DtColumnSchema::new("greptime_value", ConcreteDataType::float64_datatype(), true), + ]) + .unwrap(); + let mut table = test_table_info(1, "cpu", "public", "greptime", Arc::new(schema)); + table.meta.engine = METRIC_ENGINE_NAME.into(); + table.meta.options.extra_options.insert( + LOGICAL_TABLE_METADATA_KEY.into(), + GREPTIME_PHYSICAL_TABLE.into(), + ); + let catalog = MemoryCatalogManager::new_with_table(DistTable::table(Arc::new(table))); + let partitions = create_partition_rule_manager(prepare_mocked_backend().await).await; + let nodes = Arc::new(MockDatanodeManager::new(())); + let dispatcher = Arc::new(WriteDispatcher::new(nodes.clone(), partitions.clone())); + let mut batcher = LogicalTablePendingRowsBatcher::try_new( + partitions, + nodes, + dispatcher, + catalog, + mock_table_flownode_cache(1, vec![]).await, + true, + Arc::new(UnexpectedSchemaAlterer), + Duration::from_secs(1), + 2, + 1, + 1, + 1, + NonZeroUsize::new(1).unwrap(), + ) + .unwrap(); + Arc::get_mut(&mut batcher).unwrap().pending_rows_batch_sync = sync; + let (_, receiver) = batcher + .workers + .get_or_create(batch_key_from_ctx(&QueryContext::arc()), 1) + .await; + (batcher, receiver.unwrap()) +} pub(in crate::batcher::logical_table) fn mock_tag_batch( tag_name: &str, diff --git a/src/servers/src/exemplar.rs b/src/servers/src/exemplar.rs new file mode 100644 index 00000000000..40599f14ab0 --- /dev/null +++ b/src/servers/src/exemplar.rs @@ -0,0 +1,310 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Normalized metric exemplars shared by Remote Write and OTLP conversion. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use api::v1::value::ValueData; +use api::v1::{ColumnDataType, Row, RowInsertRequests, Value}; +use common_grpc::precision::Precision; +use common_query::prelude::{ + EXEMPLAR_LABELS_COLUMN, EXEMPLAR_METRIC_COLUMN, METRICS_EXEMPLARS_TABLE, greptime_timestamp, + greptime_value, +}; +use datatypes::json; +use metric_engine::row_modifier::TsidGenerator; +use snafu::{OptionExt, ensure}; +use store_api::metric_engine_consts::{ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, +}; +use store_api::storage::consts::is_internal_column; + +use crate::error::{InvalidPromRemoteRequestSnafu, Result}; +use crate::row_writer::{self, MultiTableData}; + +/// One observation belonging to a query-visible metric series. +/// Metric names and inherited labels are shared until row construction. +#[derive(Debug, Clone, PartialEq)] +pub struct Exemplar { + pub metric: Arc, + pub series_labels: Arc>, + pub timestamp: i64, + pub value: f64, + pub labels: BTreeMap, +} + +/// Exemplars grouped by the source series' optional database routing control. +pub type ExemplarRequests = BTreeMap, Vec>; + +/// Bounds row capacity after each database's metrics share one exemplar schema. +pub(crate) fn estimated_row_bytes(requests: &ExemplarRequests) -> Option { + requests.values().try_fold(0usize, |total, exemplars| { + let mut tags = BTreeSet::new(); + let mut payload = 0usize; + // Shared series data is copied into each output row. + for exemplar in exemplars { + tags.extend(exemplar.series_labels.keys()); + payload = payload.checked_add(exemplar.metric.len().checked_mul(4)?)?; + for (name, value) in exemplar.series_labels.iter().chain(&exemplar.labels) { + // Include owned strings, label-map entries and JSON2 encoding scratch. + payload = payload.checked_add( + name.len() + .checked_add(value.len())? + .checked_mul(4)? + .checked_add(256)?, + )?; + } + } + // Include the source table ID attached after conversion, and Vec growth. + let columns = tags.len().checked_add(6)?; + let values = exemplars + .len() + .checked_mul(columns)? + .checked_mul(2 * std::mem::size_of::())?; + let rows = exemplars + .len() + .checked_mul(2 * std::mem::size_of::() + std::mem::size_of::())?; + total + .checked_add(values)? + .checked_add(rows)? + .checked_add(columns.checked_mul(512)?)? + .checked_add(payload) + }) +} + +/// Validates labels with the protocol's name policy, preserving duplicates as errors. +pub fn labels( + labels: I, + exemplar_owned: bool, + validate_name: impl Fn(&[u8]) -> bool, +) -> Result> +where + I: IntoIterator, +{ + let mut result = BTreeMap::new(); + let mut length = 0usize; + for (name, value) in labels { + ensure!( + validate_name(name.as_bytes()), + InvalidPromRemoteRequestSnafu { + msg: format!("invalid exemplar label name: {name}"), + } + ); + if exemplar_owned { + ensure!( + name != json::JSON2_REMAINDER_FIELD_NAME, + InvalidPromRemoteRequestSnafu { + msg: "exemplar label name is reserved by JSON2", + } + ); + } else { + ensure!( + ![ + greptime_timestamp(), + greptime_value(), + EXEMPLAR_METRIC_COLUMN, + EXEMPLAR_LABELS_COLUMN, + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + DATA_SCHEMA_TSID_COLUMN_NAME, + ] + .contains(&name.as_str()) + && !is_internal_column(&name), + InvalidPromRemoteRequestSnafu { + msg: format!("inherited exemplar label collides with reserved column: {name}"), + } + ); + } + length = length + .checked_add(name.chars().count()) + .and_then(|n| n.checked_add(value.chars().count())) + .context(InvalidPromRemoteRequestSnafu { + msg: "exemplar label length overflow", + })?; + ensure!( + !exemplar_owned || length <= 128, + InvalidPromRemoteRequestSnafu { + msg: "exemplar label names and values exceed 128 characters", + } + ); + ensure!( + result.insert(name.clone(), value).is_none(), + InvalidPromRemoteRequestSnafu { + msg: format!("duplicate exemplar label: {name}"), + } + ); + } + Ok(result) +} + +/// Converts Remote Write milliseconds without losing overflow information. +pub fn timestamp_from_millis(timestamp: i64) -> Result { + timestamp + .checked_mul(1_000_000) + .context(InvalidPromRemoteRequestSnafu { + msg: "exemplar timestamp is outside the signed nanosecond range", + }) +} + +/// Builds ordinary-table rows and retains source targets for authorization. +pub fn into_rows(exemplars: Vec) -> Result<(RowInsertRequests, BTreeSet)> { + let mut tables = MultiTableData::default(); + let mut sources = BTreeSet::new(); + for exemplar in exemplars { + ensure!( + !exemplar.metric.is_empty() && exemplar.metric.as_ref() != METRICS_EXEMPLARS_TABLE, + InvalidPromRemoteRequestSnafu { + msg: "invalid or reserved exemplar source metric name" + } + ); + sources.insert(exemplar.metric.to_string()); + let table = tables.get_or_default_table_data( + METRICS_EXEMPLARS_TABLE, + exemplar.series_labels.len() + 6, + 1, + ); + let mut row = table.alloc_one_row(); + let tsid = TsidGenerator::from_sorted_tags( + exemplar + .series_labels + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())), + ); + row_writer::write_by_schema( + table, + std::iter::once(( + api::v1::helper::tag_column_schema( + DATA_SCHEMA_TSID_COLUMN_NAME, + ColumnDataType::Uint64, + ), + Some(ValueData::U64Value(tsid)), + )), + &mut row, + )?; + row_writer::write_tag(table, EXEMPLAR_METRIC_COLUMN, &exemplar.metric, &mut row)?; + row_writer::write_tags( + table, + exemplar + .series_labels + .iter() + .map(|(name, value)| (name.as_str(), value.clone())), + &mut row, + )?; + row_writer::write_fields( + table, + std::iter::once(( + greptime_value().to_string(), + ColumnDataType::Float64, + Some(ValueData::F64Value(exemplar.value)), + )), + &mut row, + )?; + row_writer::write_ts_to_nanos( + table, + greptime_timestamp(), + Some(exemplar.timestamp), + Precision::Nanosecond, + &mut row, + )?; + row_writer::write_by_schema( + table, + std::iter::once(( + row_writer::build_json2_column_schema(EXEMPLAR_LABELS_COLUMN)?, + Some(row_writer::encode_json2(exemplar.labels)?), + )), + &mut row, + )?; + table.add_row(row); + } + Ok((tables.into_row_insert_requests().0, sources)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prom_remote_write::validation::validate_label_name; + + #[test] + fn test_exemplar_labels_and_timestamp_validation() { + assert!( + labels( + [(String::from("traceID"), String::from("abc"))], + true, + validate_label_name + ) + .is_ok() + ); + assert!( + labels( + [ + (String::from("job"), String::new()), + (String::from("job"), String::new()) + ], + false, + validate_label_name, + ) + .is_err() + ); + assert!( + labels( + [(EXEMPLAR_METRIC_COLUMN.into(), "x".into())], + false, + validate_label_name + ) + .is_err() + ); + assert!(labels([("id".into(), "x".repeat(127))], true, validate_label_name).is_err()); + for name in ["", "request.method", "请求"] { + assert!(labels([(name.into(), "x".into())], true, validate_label_name).is_err()); + } + for name in [ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + DATA_SCHEMA_TSID_COLUMN_NAME, + ] { + assert!(labels([(name.into(), "x".into())], false, validate_label_name).is_err()); + } + assert_eq!(timestamp_from_millis(-1).unwrap(), -1_000_000); + assert!(timestamp_from_millis(i64::MAX).is_err()); + } + + #[test] + fn test_exemplar_tsid_uses_only_source_labels() { + let exemplar = Exemplar { + metric: "cpu".into(), + series_labels: BTreeMap::from([("job".into(), "api".into())]).into(), + timestamp: 1, + value: 2.0, + labels: BTreeMap::from([("trace_id".into(), "a".into())]), + }; + let mut other = exemplar.clone(); + other.metric = "memory".into(); + other.labels.insert("trace_id".into(), "b".into()); + let (requests, _) = into_rows(vec![exemplar, other]).unwrap(); + let rows = requests.inserts[0].rows.as_ref().unwrap(); + let index = rows + .schema + .iter() + .position(|c| c.column_name == DATA_SCHEMA_TSID_COLUMN_NAME) + .unwrap(); + let expected = ValueData::U64Value(TsidGenerator::from_sorted_tags( + [("job", "api")].into_iter(), + )); + assert!( + rows.rows + .iter() + .all(|row| row.values[index].value_data.as_ref() == Some(&expected)) + ); + } +} diff --git a/src/servers/src/http/prom_store.rs b/src/servers/src/http/prom_store.rs index 5a1be58502e..eb7f0898411 100644 --- a/src/servers/src/http/prom_store.rs +++ b/src/servers/src/http/prom_store.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod exemplar; + use std::sync::Arc; use api::prom_store::remote::ReadRequest; @@ -33,6 +35,7 @@ use prometheus::HistogramTimer; use prost::Message; use serde::{Deserialize, Serialize}; use session::context::{Channel, QueryContext, QueryContextRef}; +use snafu::IntoError; use snafu::prelude::*; use table::requests::{ METADATA_QUALITY_INFERRED, SEMANTIC_METRIC_METADATA_QUALITY, SEMANTIC_PER_TABLE_INDEX_KEY, @@ -51,7 +54,7 @@ use crate::prom_remote_write::decode::PromSeriesProcessor; use crate::prom_remote_write::v2::decode_remote_write_v2; use crate::prom_remote_write::validation::PromValidationMode; use crate::prom_remote_write::{ - REMOTE_WRITE_V1_VERSION, REMOTE_WRITE_V2_VERSION, decode_remote_write_request, + self, REMOTE_WRITE_V1_VERSION, REMOTE_WRITE_V2_VERSION, decode_remote_write_request, }; use crate::prom_store::{MAX_DECOMPRESSED_REQUEST_SIZE, snappy_decompress_limited}; use crate::query_handler::{PipelineHandlerRef, PromStoreProtocolHandlerRef, PromStoreResponse}; @@ -117,20 +120,29 @@ pub async fn remote_write( body: Bytes, ) -> Result { let is_zstd = content_encoding.contains(VM_ENCODING); + // Read after Bytes has collected every frame, including chunked-body reservations. + let body_reserved_bytes = extensions + .get::() + .map_or(0, BodyMemoryAccounting::reserved_bytes); match remote_write_proto(content_type) { RemoteWriteProto::V1 => { - remote_write_v1(state, params, query_ctx, pipeline_info, is_zstd, body).await + remote_write_v1( + state, + params, + query_ctx, + pipeline_info, + is_zstd, + body, + body_reserved_bytes, + ) + .await } RemoteWriteProto::V2 => { if let Some(response) = unsupported_remote_write_v2_encoding_response(&content_encoding) { return Ok(response); } - // Read after Bytes has collected every frame, including chunked-body reservations. - let body_reserved_bytes = extensions - .get::() - .map_or(0, BodyMemoryAccounting::reserved_bytes); remote_write_v2( state, params, @@ -157,6 +169,7 @@ async fn remote_write_v1( pipeline_info: PipelineInfo, is_zstd: bool, body: Bytes, + body_reserved_bytes: u64, ) -> Result { let PromStoreState { prom_store_handler, @@ -208,6 +221,7 @@ async fn remote_write_v1( // borrowing `col_indexes` dies inside `as_insert_requests`. Nothing below // references the buffer, so it need not span the write — the same goes for // the decode guards charged against the aggregate memory quota. + let exemplars = std::mem::take(&mut decoded.exemplars); let req = if processor.use_pipeline { drop(decoded); processor.exec_pipeline().await? @@ -217,7 +231,52 @@ async fn remote_write_v1( req }; drop(decode_guards); - let batches = into_prom_write_batches(req, query_ctx); + let query_ctx = if exemplars.is_empty() { + query_ctx + } else { + // Reserve for row expansion before copying shared metric names and series labels. + let bytes = crate::exemplar::estimated_row_bytes(&exemplars) + .and_then(|bytes| u64::try_from(bytes).ok()) + .ok_or_else(|| { + error::MemoryLimitExceededSnafu.into_error( + common_memory_manager::Error::MemoryLimitExceeded { + requested_bytes: u64::MAX, + limit_bytes: memory_limiter.limit_bytes(), + }, + ) + })?; + memory_limiter.check_request_fits(bytes, body_reserved_bytes)?; + let reservation = Arc::new( + memory_limiter + .acquire(bytes) + .await + .map_err(prom_remote_write::map_memory_acquire_timeout)?, + ); + let mut ctx = query_ctx.fork(); + ctx.set_write_progress(Arc::new( + session::write_progress::WriteProgress::with_reservation(reservation), + )); + Arc::new(ctx) + }; + let batches = into_prom_write_batches(req, query_ctx.clone()); + if !exemplars.is_empty() { + let outcome = exemplar::write( + prom_store_handler, + pending_rows_batcher, + prom_store_with_metric_engine, + batches, + Vec::new(), + exemplars, + query_ctx, + ) + .await; + record_remote_write_samples(&db, REMOTE_WRITE_V1_VERSION, outcome.written[0]); + record_remote_write_exemplars(&db, REMOTE_WRITE_V1_VERSION, outcome.written[2]); + if let Some(error) = outcome.error { + return Err(error); + } + return Ok((StatusCode::NO_CONTENT, write_cost_header_map(outcome.cost)).into_response()); + } let outcome = match write_prometheus_rows_with_progress( prom_store_handler, @@ -266,7 +325,7 @@ async fn remote_write_v2( // Pipeline processing is not supported for remote write v2 yet. Ignore the // optional pipeline parameter and ingest samples directly. - let _ = pipeline_info; + let has_pipeline = pipeline_info.pipeline_name.is_some(); let (db, mut query_ctx, _timer) = prepare_remote_write_context(¶ms, query_ctx, REMOTE_WRITE_V2_VERSION); @@ -276,15 +335,34 @@ async fn remote_write_v2( Ok(req) => req, Err(error) => return Ok(remote_write_v2_error_response(error, 0, 0, 0)), }; + if has_pipeline && req.exemplar_count > 0 { + return Ok(remote_write_v2_error_response( + error::NotSupportedSnafu { + feat: "pipelines with exemplars", + } + .build(), + 0, + 0, + 0, + )); + } // The v2 per-series metadata upgrades the written tables' semantic options // (metric type/unit, declared quality) at auto-create time. if let Some(index) = req.semantic_index.encode(&query_ctx.current_schema()) { query_ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, index); } + if req.exemplar_count > 0 { + let counter = crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS + .with_label_values(&[&db, REMOTE_WRITE_V2_VERSION]); + query_ctx.set_write_progress(Arc::new( + session::write_progress::WriteProgress::with_reservation(req.memory_guard.clone()) + .with_observer(move |rows| counter.inc_by(rows)), + )); + } let query_ctx = Arc::new(query_ctx); let (sample_count, histogram_count) = (req.sample_count, req.histogram_count); let mut sample_batches = into_prom_write_batches(req.samples, query_ctx.clone()); - let mut histogram_batches = into_prom_write_batches(req.histograms, query_ctx); + let mut histogram_batches = into_prom_write_batches(req.histograms, query_ctx.clone()); for (batches, histogram) in [(&mut sample_batches, false), (&mut histogram_batches, true)] { let counter = if histogram { crate::metrics::PROM_STORE_REMOTE_WRITE_HISTOGRAMS @@ -303,6 +381,39 @@ async fn remote_write_v2( *ctx = Arc::new(fork); } } + if req.exemplar_count > 0 { + let outcome = exemplar::write( + prom_store_handler, + pending_rows_batcher, + prom_store_with_metric_engine, + sample_batches, + histogram_batches, + req.exemplars, + query_ctx, + ) + .await; + if let Some(error) = outcome.error { + return Ok(remote_write_v2_error_response( + error, + outcome.written[0], + outcome.written[1], + outcome.written[2], + )); + } + let mut headers = write_cost_header_map(outcome.cost); + append_remote_write_v2_written_headers( + &mut headers, + outcome.written[0], + outcome.written[1], + outcome.written[2], + ); + let status = if outcome.accepted { + StatusCode::ACCEPTED + } else { + StatusCode::NO_CONTENT + }; + return Ok((status, headers).into_response()); + } let outcome = match write_prometheus_v2_rows_with_progress( prom_store_handler, pending_rows_batcher, @@ -462,7 +573,10 @@ async fn write_prometheus_rows_with_progress( // ordinary insert path, which routes per destination; time index // units need no check — the bulk encode converts each request to // its destination's unit. - if batcher.accepts_bulk_destinations(batches.iter()).await { + if batcher + .accepts_bulk_destinations(batches.iter().map(|(ctx, request)| (ctx, request))) + .await + { let mut rows_written = 0; for (temp_ctx, reqs) in batches { let rows = @@ -570,7 +684,9 @@ async fn write_prometheus_v2_rows_with_progress( })?; let batcher = if prom_store_with_metric_engine && let Some(batcher) = pending_rows_batcher.as_ref() - && batcher.accepts_bulk_destinations(batches.iter()).await + && batcher + .accepts_bulk_destinations(batches.iter().map(|(ctx, request)| (ctx, request))) + .await { Some(batcher.as_ref() as &dyn PromWriteBatcher) } else { @@ -699,6 +815,14 @@ fn record_remote_write_samples(db: &str, version: &str, rows: u64) { .inc_by(rows); } +fn record_remote_write_exemplars(db: &str, version: &str, rows: u64) { + if rows != 0 { + crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS + .with_label_values(&[db, version]) + .inc_by(rows); + } +} + fn remote_write_v2_error_response( error: error::Error, samples: u64, @@ -1206,6 +1330,284 @@ mod tests { } } + struct ExemplarMemoryHandler { + limiter: ServerMemoryLimiter, + progress: Mutex>>, + } + + #[async_trait] + impl PromStoreProtocolHandler for ExemplarMemoryHandler { + async fn pre_write(&self, request: &RowInsertRequests, _: QueryContextRef) -> Result<()> { + let capacity: usize = request + .inserts + .iter() + .flat_map(|request| &request.rows.as_ref().unwrap().rows) + .map(|row| row.values.capacity() * std::mem::size_of::()) + .sum(); + assert!(self.limiter.used_bytes() >= capacity as u64); + Ok(()) + } + + async fn check_exemplar_sources( + &self, + _: &std::collections::BTreeSet, + _: QueryContextRef, + ) -> Result<()> { + Ok(()) + } + + async fn write_exemplars_prepared( + &self, + request: RowInsertRequests, + ctx: QueryContextRef, + ) -> Result { + *self.progress.lock().unwrap() = Some(ctx.write_progress().unwrap().clone()); + Ok(Output::new_with_affected_rows( + prom_write_row_count(&request) as usize, + )) + } + + async fn write_prepared( + &self, + _: RowInsertRequests, + _: QueryContextRef, + _: bool, + ) -> Result { + unreachable!() + } + + async fn write(&self, _: RowInsertRequests, _: QueryContextRef, _: bool) -> Result { + unreachable!() + } + + async fn write_all(&self, _: Vec, _: bool) -> Result>> { + unreachable!() + } + + async fn read(&self, _: ReadRequest, _: QueryContextRef) -> Result { + unreachable!() + } + } + + #[tokio::test] + async fn test_v1_exemplar_shared_series_expansion_is_charged() { + use api::prom_store::remote; + + use crate::http::{HttpOptions, HttpServerBuilder}; + + for large_field in ["__name__", "host"] { + for count in [128, 1] { + let request = remote::WriteRequest { + timeseries: vec![remote::TimeSeries { + labels: ["__name__", "host"] + .into_iter() + .map(|name| remote::Label { + name: name.into(), + value: if name == large_field { + "x".repeat(64 * 1024) + } else { + "metric".into() + }, + }) + .collect(), + exemplars: vec![remote::Exemplar::default(); count], + ..Default::default() + }], + ..Default::default() + }; + let limiter = ServerMemoryLimiter::new(1024 * 1024, OnExhaustedPolicy::Fail); + let handler = Arc::new(ExemplarMemoryHandler { + limiter: limiter.clone(), + progress: Mutex::new(None), + }); + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_memory_limiter(limiter.clone()) + .with_prom_handler( + handler.clone(), + None, + true, + PromValidationMode::Strict, + None, + ) + .build(); + let response = server + .build(server.make_app()) + .unwrap() + .oneshot( + Request::post("/v1/prometheus/write") + .header(header::CONTENT_TYPE, "application/x-protobuf") + .header(header::CONTENT_ENCODING, DEFAULT_ENCODING) + .body(Body::from( + crate::prom_store::snappy_compress(&request.encode_to_vec()) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let progress = handler.progress.lock().unwrap().take(); + if count == 1 { + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert!(progress.is_some()); + assert!(limiter.used_bytes() >= 64 * 1024); + } else { + assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(progress.is_none()); + } + drop(progress); + assert_eq!(limiter.used_bytes(), 0); + } + } + } + + #[tokio::test(start_paused = true)] + async fn test_exemplar_row_memory_is_charged_and_retained() { + use api::greptime_proto::io::prometheus::write::v2; + use api::prom_store::remote; + + use crate::http::{HttpOptions, HttpServerBuilder}; + + for version in [1, 2] { + for policy in [OnExhaustedPolicy::Fail, OnExhaustedPolicy::default()] { + for (distinct_tags, contended, expire) in [ + (true, false, false), + (false, false, false), + (false, true, false), + (false, true, true), + ] { + let mut v1 = remote::WriteRequest::default(); + let mut v2 = v2::Request { + symbols: vec![String::new()], + timeseries: vec![], + }; + for index in 0..1024 { + let labels = vec![ + remote::Label { + name: "__name__".into(), + value: format!("metric_{index}"), + }, + remote::Label { + name: format!("tag_{}", if distinct_tags { index } else { 0 }), + value: "value".into(), + }, + ]; + let mut labels_refs = Vec::new(); + for label in &labels { + labels_refs + .extend([v2.symbols.len() as u32, v2.symbols.len() as u32 + 1]); + v2.symbols.extend([label.name.clone(), label.value.clone()]); + } + v1.timeseries.push(remote::TimeSeries { + labels, + samples: if expire { + vec![remote::Sample::default()] + } else { + vec![] + }, + exemplars: vec![remote::Exemplar::default()], + ..Default::default() + }); + v2.timeseries.push(v2::TimeSeries { + labels_refs, + samples: if expire { + vec![v2::Sample::default()] + } else { + vec![] + }, + exemplars: vec![v2::Exemplar::default()], + ..Default::default() + }); + } + let (content_type, wire) = if version == 1 { + ("application/x-protobuf", v1.encode_to_vec()) + } else { + ( + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + v2.encode_to_vec(), + ) + }; + let limiter = ServerMemoryLimiter::new(16 * 1024 * 1024, policy); + let mut occupied = contended + .then(|| limiter.try_acquire(16 * 1024 * 1024 - 256 * 1024).unwrap()); + let handler = Arc::new(ExemplarMemoryHandler { + limiter: limiter.clone(), + progress: Mutex::new(None), + }); + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_memory_limiter(limiter.clone()) + .with_prom_handler( + handler.clone(), + None, + true, + PromValidationMode::Strict, + None, + ) + .build(); + let response = server.build(server.make_app()).unwrap().oneshot( + Request::post("/v1/prometheus/write") + .header(header::CONTENT_TYPE, content_type) + .header(header::CONTENT_ENCODING, DEFAULT_ENCODING) + .body(Body::from( + crate::prom_store::snappy_compress(&wire).unwrap(), + )) + .unwrap(), + ); + let started = tokio::time::Instant::now(); + tokio::pin!(response); + if contended && matches!(policy, OnExhaustedPolicy::Wait { .. }) { + assert!(futures::poll!(response.as_mut()).is_pending()); + if !expire { + drop(occupied.take()); + } + } + let response = response.await.unwrap(); + let timed_out = expire && matches!(policy, OnExhaustedPolicy::Wait { .. }); + let rejected = distinct_tags + || timed_out + || (contended && matches!(policy, OnExhaustedPolicy::Fail)); + assert_eq!( + response.status(), + if timed_out { + StatusCode::INTERNAL_SERVER_ERROR + } else if rejected { + StatusCode::TOO_MANY_REQUESTS + } else { + StatusCode::NO_CONTENT + }, + "version={version}, distinct={distinct_tags}, contended={contended}, expire={expire}, policy={policy:?}" + ); + if let OnExhaustedPolicy::Wait { timeout } = policy + && timed_out + { + assert_eq!(started.elapsed(), timeout); + } else { + assert_eq!(started.elapsed(), Duration::ZERO); + } + let progress = handler.progress.lock().unwrap().take(); + if !rejected { + assert!(progress.is_some()); + assert!(limiter.used_bytes() > 0); + if version == 2 { + assert_eq!( + response.headers()[REMOTE_WRITE_V2_EXEMPLARS_WRITTEN_HEADER], + "1024" + ); + } + } else { + assert!(progress.is_none()); + } + drop(progress); + assert_eq!( + limiter.used_bytes(), + occupied.as_ref().map_or(0, |guard| guard.granted_bytes()) + ); + drop(occupied); + assert_eq!(limiter.used_bytes(), 0); + } + } + } + } + fn memory_limited_prom_write_app(limiter: ServerMemoryLimiter) -> Router { let mut state = test_state(); state.memory_limiter = limiter.clone(); @@ -1219,6 +1621,54 @@ mod tests { )) } + #[tokio::test(start_paused = true)] + async fn test_exemplar_v1_reservation_accounts_for_chunked_body() { + use api::prom_store::remote; + + let wire = remote::WriteRequest { + timeseries: vec![remote::TimeSeries { + labels: vec![ + remote::Label { + name: "__name__".into(), + value: "metric".into(), + }, + remote::Label { + name: "job".into(), + value: "api".into(), + }, + ], + exemplars: vec![remote::Exemplar::default()], + ..Default::default() + }], + ..Default::default() + } + .encode_to_vec(); + let body = crate::prom_store::snappy_compress(&wire).unwrap(); + // Each frame retains a 1 KiB body permit. The rows fit alone, but not alongside both. + let frames = body + .chunks(body.len().div_ceil(2)) + .map(Bytes::copy_from_slice) + .collect::>(); + assert_eq!(frames.len(), 2); + let limiter = ServerMemoryLimiter::new(5 * 1024, OnExhaustedPolicy::default()); + let started = tokio::time::Instant::now(); + let response = memory_limited_prom_write_app(limiter.clone()) + .oneshot( + Request::post("/write") + .header(header::CONTENT_TYPE, "application/x-protobuf") + .header(header::CONTENT_ENCODING, DEFAULT_ENCODING) + .body(Body::from_stream(futures::stream::iter( + frames.into_iter().map(Ok::<_, std::io::Error>), + ))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(started.elapsed(), Duration::ZERO); + assert_eq!(limiter.used_bytes(), 0); + } + #[tokio::test(start_paused = true)] async fn test_remote_write_v2_accounts_for_body_when_rejecting_or_waiting() { let wire = api::greptime_proto::io::prometheus::write::v2::Request { diff --git a/src/servers/src/http/prom_store/exemplar.rs b/src/servers/src/http/prom_store/exemplar.rs new file mode 100644 index 00000000000..d6524e9ce71 --- /dev/null +++ b/src/servers/src/http/prom_store/exemplar.rs @@ -0,0 +1,811 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashSet; +use std::sync::Arc; + +use api::v1::RowInsertRequests; +use common_error::ext::BoxedError; +use futures::future::ready; +use operator::insert::PreparedMetricInserts; +use session::context::QueryContextRef; +use snafu::ResultExt; + +use crate::batcher::logical_table::LogicalTablePendingRowsBatcher; +use crate::error::{self, Result}; +use crate::exemplar::{ExemplarRequests, into_rows}; +use crate::http::prom_store::PromWriteBatch; +use crate::query_handler::PromStoreProtocolHandlerRef; + +#[derive(Default)] +pub(super) struct Outcome { + pub cost: usize, + pub accepted: bool, + /// Accepted rows on success; confirmed storage writes on error. + pub written: [u64; 3], + pub error: Option, +} + +enum PreparedWrite { + Metric(PreparedMetricInserts), + Rows(RowInsertRequests), +} + +/// Preflights all destinations together, retaining per-kind write progress. +pub(super) async fn write( + handler: PromStoreProtocolHandlerRef, + batcher: Option>, + metric_engine: bool, + samples: Vec, + histograms: Vec, + exemplars: ExemplarRequests, + ctx: QueryContextRef, +) -> Outcome { + match prepare(&handler, samples, histograms, exemplars, ctx).await { + Ok((writes, targets)) => { + let mut sources = Vec::new(); + let mut prepared = Vec::new(); + let mut source_preparation_failed = false; + for (kind, ctx, request) in writes { + if kind != 2 && metric_engine { + let (pinned, other): (Vec<_>, Vec<_>) = + request.inserts.into_iter().partition(|request| { + targets.contains(&( + ctx.current_catalog().to_string(), + ctx.current_schema(), + request.table_name.clone(), + )) + }); + if !other.is_empty() { + prepared.push(( + kind, + ctx.clone(), + Ok(PreparedWrite::Rows(RowInsertRequests { inserts: other })), + )); + } + if !pinned.is_empty() { + let result = handler + .prepare_metric_write( + RowInsertRequests { inserts: pinned }, + ctx.clone(), + ) + .await; + if let Ok(request) = &result { + sources.extend(request.source_tables().cloned()); + } else { + source_preparation_failed = true; + } + prepared.push((kind, ctx, result.map(PreparedWrite::Metric))); + } + } else { + prepared.push((kind, ctx, Ok(PreparedWrite::Rows(request)))); + } + } + // A failed source preparation must not fall back to a newer table with the same name. + if source_preparation_failed { + prepared.retain(|(kind, _, _)| *kind != 2); + } + let sample_batches = prepared.iter().filter_map(|(kind, ctx, request)| { + if *kind == 0 + && let Ok(PreparedWrite::Rows(request)) = request + { + Some((ctx, request)) + } else { + None + } + }); + let batcher = if metric_engine + && let Some(batcher) = batcher.as_ref() + && batcher.accepts_bulk_destinations(sample_batches).await + { + Some(batcher) + } else { + None + }; + let mut outputs = Vec::with_capacity(prepared.len()); + // Serialize schema preparation across batches that resolve to the same table. + for (kind, ctx, request) in prepared { + let mut deferred = false; + let output = match request { + Err(error) => Err(error), + Ok(PreparedWrite::Metric(request)) => { + handler.write_prepared_metric(request, ctx).await + } + Ok(PreparedWrite::Rows(request)) => { + if kind == 2 && !metric_engine { + error::NotSupportedSnafu { + feat: "exemplars require metric-engine ingestion", + } + .fail() + } else if kind == 2 { + handler + .write_exemplars_with_sources(request, ctx, &sources) + .await + } else if kind == 0 + && let Some(batcher) = batcher + { + deferred = !batcher.is_synchronous(); + batcher + .submit_output_with(request, ctx, |_| ready(Ok(()))) + .await + .map(|(output, ())| output) + } else { + handler.write_prepared(request, ctx, metric_engine).await + } + } + }; + outputs.push((kind, output, deferred)); + } + let mut outcome = Outcome::default(); + let mut pending_samples = Vec::new(); + for (kind, output, deferred) in outputs { + match output { + Ok(output) => { + outcome.cost += output.meta.cost; + if deferred && !output.meta.write_completions.is_empty() { + pending_samples.push(output); + continue; + } + let progress = output.write_progress().await; + outcome.written[kind] += progress.affected_rows as u64; + if let Err(error) = + progress.into_result().context(error::ExecuteGrpcQuerySnafu) + { + outcome.error.get_or_insert(error); + } + } + Err(error) => { + outcome.error.get_or_insert(error); + } + } + } + if outcome.error.is_none() { + outcome.accepted = !pending_samples.is_empty(); + outcome.written[0] += pending_samples + .iter() + .map(|output| output.extract_rows_and_cost().0 as u64) + .sum::(); + } else { + // Split submissions may share a counter; each completion owns its row count. + for output in pending_samples { + outcome.written[0] += output.write_progress().await.affected_rows as u64; + } + } + outcome + } + Err(error) => Outcome { + error: Some(error), + ..Default::default() + }, + } +} + +async fn prepare( + handler: &PromStoreProtocolHandlerRef, + samples: Vec, + histograms: Vec, + exemplars: ExemplarRequests, + ctx: QueryContextRef, +) -> Result<( + Vec<(usize, QueryContextRef, RowInsertRequests)>, + HashSet<(String, String, String)>, +)> { + let mut kinds = Vec::new(); + let mut prepared = Vec::new(); + let mut targets = HashSet::new(); + for (kind, batches) in [samples, histograms].into_iter().enumerate() { + for (ctx, request) in batches { + handler.pre_write(&request, ctx.clone()).await?; + kinds.push(kind); + // Keep per-batch routing options when admitting database-wide totals. + prepared.push((Arc::new(ctx.with_confirmed_writes()), request)); + } + } + for (schema, exemplars) in exemplars { + let target = ctx.fork(); + if let Some(schema) = schema { + target.set_current_schema(&schema); + } + let (request, sources) = into_rows(exemplars)?; + let target = Arc::new(target); + handler.pre_write(&request, target.clone()).await?; + let target = Arc::new(target.with_confirmed_writes()); + if !sources.is_empty() { + handler + .check_exemplar_sources(&sources, target.clone()) + .await?; + } + targets.extend(sources.into_iter().map(|name| { + ( + target.current_catalog().to_string(), + target.current_schema(), + name, + ) + })); + kinds.push(2); + prepared.push((target, request)); + } + operator::insert::admit_row_insert_batches(&mut prepared) + .await + .map_err(BoxedError::new) + .context(error::ExecuteGrpcQuerySnafu)?; + let writes = kinds + .into_iter() + .zip(prepared) + .map(|(kind, (ctx, request))| (kind, ctx, request)) + .collect(); + Ok((writes, targets)) +} + +#[cfg(test)] +mod tests { + use std::collections::{BTreeMap, BTreeSet}; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, Ordering}; + + use api::prom_store::remote::ReadRequest; + use api::v1::{Row, RowInsertRequest, Rows}; + use async_trait::async_trait; + use common_query::{Output, OutputData, OutputMeta, WriteCompletion, WriteProgress}; + use session::context::QueryContext; + use tokio::sync::Notify; + + use super::*; + use crate::exemplar::Exemplar; + use crate::query_handler::{PromStoreProtocolHandler, PromStoreResponse}; + + #[derive(Default)] + struct Handler { + events: Mutex>, + exemplar_done: Arc, + deny_schema: bool, + fail_preparation: bool, + successful_writes: bool, + check_serial: bool, + writing: AtomicBool, + } + + #[async_trait] + impl PromStoreProtocolHandler for Handler { + async fn prepare_metric_write( + &self, + _: RowInsertRequests, + _: QueryContextRef, + ) -> Result { + if self.fail_preparation { + return error::InvalidPromRemoteRequestSnafu { + msg: "source preparation failed", + } + .fail(); + } + Ok(PreparedMetricInserts::default()) + } + + async fn write_prepared_metric( + &self, + _: PreparedMetricInserts, + ctx: QueryContextRef, + ) -> Result { + self.write_prepared(RowInsertRequests::default(), ctx, true) + .await + } + + async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()> { + self.events + .lock() + .unwrap() + .push(format!("pre:{}", ctx.current_schema())); + assert!(!request.inserts.is_empty()); + if self.deny_schema && ctx.current_schema() == "other" { + return error::InvalidPromRemoteRequestSnafu { + msg: "denied destination", + } + .fail(); + } + if let Some(schema) = ctx.extension("resolved_schema") { + ctx.set_current_schema(schema); + } + Ok(()) + } + + async fn check_exemplar_sources( + &self, + sources: &BTreeSet, + ctx: QueryContextRef, + ) -> Result<()> { + assert_eq!(sources, &BTreeSet::from(["metric".into()])); + self.events + .lock() + .unwrap() + .push(format!("source:{}", ctx.current_schema())); + Ok(()) + } + + async fn write_prepared( + &self, + _request: RowInsertRequests, + ctx: QueryContextRef, + _: bool, + ) -> Result { + if self.check_serial { + assert!(!self.writing.swap(true, Ordering::SeqCst)); + tokio::task::yield_now().await; + self.writing.store(false, Ordering::SeqCst); + } + assert!(ctx.confirmed_writes()); + assert_eq!( + ctx.write_rows_to_admit(ctx.current_catalog(), &ctx.current_schema(), 3), + 0 + ); + self.events.lock().unwrap().push("metric".into()); + if self.successful_writes { + if let Some(counter) = ctx.write_progress() { + counter.add_written(2); + } + return Ok(Output::new_with_affected_rows(2)); + } + let done = self.exemplar_done.clone(); + let counter = ctx.write_progress().cloned(); + let completion = WriteCompletion::with_progress(async move { + done.notified().await; + if let Some(counter) = counter { + counter.add_written(1); + } + WriteProgress { + affected_rows: 1, + error: Some(Arc::new(BoxedError::new( + error::InternalSnafu { + err_msg: "late metric failure", + } + .build(), + ))), + } + }); + Ok(Output::new( + OutputData::AffectedRows(2), + OutputMeta { + cost: 2, + write_completions: vec![completion], + ..Default::default() + }, + )) + } + + async fn write_exemplars_prepared( + &self, + _: RowInsertRequests, + ctx: QueryContextRef, + ) -> Result { + assert!(ctx.confirmed_writes()); + assert_eq!( + ctx.write_rows_to_admit(ctx.current_catalog(), &ctx.current_schema(), 1), + 0 + ); + self.events.lock().unwrap().push("exemplar".into()); + if let Some(counter) = ctx.write_progress() { + counter.add_written(1); + } + self.exemplar_done.notify_one(); + Ok(Output::new( + OutputData::AffectedRows(1), + OutputMeta::new_with_cost(1), + )) + } + + async fn write(&self, _: RowInsertRequests, _: QueryContextRef, _: bool) -> Result { + unreachable!() + } + async fn write_all( + &self, + _: Vec<(QueryContextRef, RowInsertRequests)>, + _: bool, + ) -> Result>> { + unreachable!() + } + async fn read(&self, _: ReadRequest, _: QueryContextRef) -> Result { + unreachable!() + } + } + + #[tokio::test] + async fn exemplar_requires_successful_metric_engine_source_preparation() { + for metric_engine in [false, true] { + let handler = Arc::new(Handler { + fail_preparation: true, + ..Default::default() + }); + let ctx = QueryContext::arc(); + let samples = if metric_engine { + vec![( + ctx.clone(), + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: "metric".into(), + rows: Some(Rows { + schema: vec![], + rows: vec![Row { values: vec![] }], + }), + }], + }, + )] + } else { + vec![] + }; + let exemplars = ExemplarRequests::from([( + None, + vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + labels: BTreeMap::new(), + timestamp: 1, + value: 1.0, + }], + )]); + let outcome = write( + handler.clone(), + None, + metric_engine, + samples, + vec![], + exemplars, + ctx, + ) + .await; + assert!(outcome.error.is_some()); + assert_eq!(outcome.written, [0, 0, 0]); + assert!( + !handler + .events + .lock() + .unwrap() + .iter() + .any(|e| e == "metric" || e == "exemplar") + ); + } + } + + #[tokio::test] + async fn exemplar_preserves_batch_routing_after_preflight() { + use crate::http::prom_store::PHYSICAL_TABLE_PARAM; + + let handler: PromStoreProtocolHandlerRef = Arc::new(Handler::default()); + let mut ctx = QueryContext::with("greptime", "public"); + ctx.set_extension("resolved_schema", "tenant"); + let ctx = Arc::new(ctx); + let batch = |physical: Option<&str>| { + let mut target = ctx.fork(); + if let Some(physical) = physical { + target.set_extension(PHYSICAL_TABLE_PARAM, physical); + } + ( + Arc::new(target), + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: "metric".into(), + rows: Some(Rows { + schema: vec![], + rows: vec![Row { values: vec![] }], + }), + }], + }, + ) + }; + let exemplars = ExemplarRequests::from([( + None, + vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + labels: BTreeMap::new(), + timestamp: 1, + value: 1.0, + }], + )]); + let (writes, targets) = prepare( + &handler, + vec![ + batch(Some("physical_a")), + batch(Some("physical_b")), + batch(None), + ], + vec![batch(Some("histogram_physical"))], + exemplars, + ctx, + ) + .await + .unwrap(); + assert_eq!( + targets, + HashSet::from([("greptime".into(), "tenant".into(), "metric".into())]) + ); + let expected = [ + (0, Some("physical_a")), + (0, Some("physical_b")), + (0, None), + (1, Some("histogram_physical")), + (2, None), + ]; + assert_eq!(writes.len(), expected.len()); + for ((kind, ctx, request), (expected_kind, physical)) in writes.into_iter().zip(expected) { + assert_eq!(kind, expected_kind); + assert_eq!(ctx.extension(PHYSICAL_TABLE_PARAM), physical); + assert_eq!(ctx.current_schema(), "tenant"); + assert!(ctx.confirmed_writes()); + assert_eq!(ctx.write_rows_to_admit("greptime", "tenant", 1), 0); + assert_eq!(request.inserts.len(), 1); + } + } + + #[tokio::test] + async fn exemplar_submits_metric_batches_sequentially() { + let handler = Arc::new(Handler { + successful_writes: true, + check_serial: true, + ..Default::default() + }); + let ctx = QueryContext::arc(); + let samples = ["metric", "other", "other"] + .into_iter() + .map(|name| { + ( + Arc::new(ctx.fork()), + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: name.into(), + rows: Some(Rows { + schema: vec![], + rows: vec![Row { values: vec![] }; 2], + }), + }], + }, + ) + }) + .collect(); + let exemplars = ExemplarRequests::from([( + None, + vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + labels: BTreeMap::new(), + timestamp: 1, + value: 1.0, + }], + )]); + let outcome = write(handler, None, true, samples, vec![], exemplars, ctx).await; + assert!(outcome.error.is_none()); + assert_eq!(outcome.written, [6, 0, 1]); + } + + #[tokio::test] + async fn exemplar_v2_batching_acknowledgement_and_partial_counts() { + use api::greptime_proto::io::prometheus::write::v2; + use common_memory_manager::OnExhaustedPolicy; + use prost::Message; + + use crate::batcher::logical_table::test_util::{WorkerCommand, submission_batcher}; + use crate::http::extractor::PipelineInfo; + use crate::http::prom_store::{PromStoreState, RemoteWriteQuery, remote_write_v2}; + use crate::prom_remote_write::REMOTE_WRITE_V2_VERSION; + use crate::prom_remote_write::validation::PromValidationMode; + use crate::request_memory_limiter::ServerMemoryLimiter; + + for (sync, successful_writes) in + [(false, false), (false, true), (true, false), (true, true)] + { + let (batcher, mut receiver) = submission_batcher(sync).await; + let limiter = ServerMemoryLimiter::new(1024 * 1024, OnExhaustedPolicy::Fail); + let db = "exemplar_confirmed_counts"; + let counters = [ + &*crate::metrics::PROM_STORE_REMOTE_WRITE_SAMPLES, + &*crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS, + ] + .map(|counter| counter.with_label_values(&[db, REMOTE_WRITE_V2_VERSION])); + let before = counters.each_ref().map(|counter| counter.get()); + let request = v2::Request { + symbols: vec![ + String::new(), + "__name__".into(), + "metric".into(), + "cpu".into(), + ], + timeseries: vec![ + v2::TimeSeries { + labels_refs: vec![1, 2], + samples: vec![ + v2::Sample { + timestamp: 1, + value: 1.0, + ..Default::default() + }; + 2 + ], + exemplars: vec![v2::Exemplar { + labels_refs: vec![], + value: 0.25, + timestamp: 1, + }], + ..Default::default() + }, + v2::TimeSeries { + labels_refs: vec![1, 3], + samples: vec![ + v2::Sample { + timestamp: 1, + value: 1.0, + ..Default::default() + }; + 2 + ], + ..Default::default() + }, + ], + }; + let response = remote_write_v2( + PromStoreState { + prom_store_handler: Arc::new(Handler { + successful_writes, + ..Default::default() + }), + pipeline_handler: None, + prom_store_with_metric_engine: true, + prom_validation_mode: PromValidationMode::Strict, + pending_rows_batcher: Some(batcher), + memory_limiter: limiter.clone(), + }, + RemoteWriteQuery { + db: Some(db.into()), + ..Default::default() + }, + QueryContext::with("greptime", "public"), + PipelineInfo { + pipeline_name: None, + pipeline_version: None, + pipeline_params: Default::default(), + }, + false, + crate::prom_store::snappy_compress(&request.encode_to_vec()) + .unwrap() + .into(), + 0, + ); + tokio::pin!(response); + let mut early_response = None; + let command = tokio::select! { + biased; + result = &mut response => { + early_response = Some(result.unwrap()); + receiver.try_recv().unwrap() + } + command = receiver.recv() => command.unwrap(), + }; + assert_eq!(early_response.is_some(), !sync && successful_writes); + assert!(limiter.used_bytes() > 0); + let WorkerCommand::Submit { + ctx, + response_tx, + _completion, + .. + } = command + else { + panic!("expected sample submission") + }; + let affected_rows = if successful_writes { 2 } else { 1 }; + ctx.write_progress().unwrap().add_written(affected_rows); + let progress = WriteProgress { + affected_rows, + error: (!successful_writes).then(|| { + Arc::new(BoxedError::new( + error::InternalSnafu { + err_msg: "partial queued write", + } + .build(), + )) + }), + }; + assert_eq!( + response_tx.send(progress).is_ok(), + sync || !successful_writes + ); + drop(_completion); + let response = match early_response { + Some(response) => response, + None => response.await.unwrap(), + }; + if successful_writes { + assert_eq!(response.status(), if sync { 204 } else { 202 }); + } else { + assert!(response.status().is_server_error()); + } + let samples = if successful_writes { "4" } else { "2" }; + for (kind, count) in [ + ("samples", samples), + ("histograms", "0"), + ("exemplars", "1"), + ] { + assert_eq!( + response.headers()[format!("x-prometheus-remote-write-{kind}-written")], + count + ); + } + for ((counter, before), count) in counters + .into_iter() + .zip(before) + .zip([if successful_writes { 4 } else { 2 }, 1]) + { + assert_eq!(counter.get() - before, count); + } + drop(ctx); + assert_eq!(limiter.used_bytes(), 0); + } + } + + #[tokio::test] + async fn exemplar_preflights_all_databases_and_retains_delayed_partial_progress() { + for denied in [false, true] { + let handler = Arc::new(Handler { + deny_schema: denied, + ..Default::default() + }); + let mut exemplars = ExemplarRequests::new(); + for schema in if denied { + vec![None, Some("other".into())] + } else { + vec![None] + } { + exemplars.insert( + schema, + vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + labels: BTreeMap::new(), + timestamp: 1, + value: 1.0, + }], + ); + } + let ctx = QueryContext::arc(); + let samples = vec![( + ctx.clone(), + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: "metric".into(), + rows: Some(Rows { + schema: vec![], + rows: vec![Row { values: vec![] }; 2], + }), + }], + }, + )]; + let outcome = write(handler.clone(), None, true, samples, vec![], exemplars, ctx).await; + assert!(outcome.error.is_some()); + let events = handler.events.lock().unwrap(); + if denied { + assert_eq!(outcome.written, [0, 0, 0]); + assert!(!events.iter().any(|e| e == "metric" || e == "exemplar")); + } else { + assert_eq!(outcome.written, [1, 0, 1]); + assert_eq!(outcome.cost, 3); + assert_eq!( + *events, + [ + "pre:public", + "pre:public", + "source:public", + "metric", + "exemplar" + ] + ); + } + } + } +} diff --git a/src/servers/src/lib.rs b/src/servers/src/lib.rs index 2fed3d43de0..2b0d0515a5b 100644 --- a/src/servers/src/lib.rs +++ b/src/servers/src/lib.rs @@ -23,6 +23,7 @@ pub mod batcher; pub mod configurator; pub(crate) mod elasticsearch; pub mod error; +pub mod exemplar; pub mod grpc; mod hint_headers; diff --git a/src/servers/src/metrics.rs b/src/servers/src/metrics.rs index 963ab51b1e2..ef5f30ba0b5 100644 --- a/src/servers/src/metrics.rs +++ b/src/servers/src/metrics.rs @@ -123,6 +123,16 @@ lazy_static! { &[METRIC_DB_LABEL, METRIC_VERSION_LABEL] ) .unwrap(); + pub static ref PROM_STORE_REMOTE_WRITE_EXEMPLARS: IntCounterVec = register_int_counter_vec!( + "greptime_servers_prometheus_remote_write_exemplars", + "Acknowledged Prometheus remote write exemplars", + &[METRIC_DB_LABEL, METRIC_VERSION_LABEL] + ).unwrap(); + pub static ref EXEMPLARS_DROPPED_TOTAL: IntCounterVec = register_int_counter_vec!( + "greptime_servers_exemplars_dropped_total", + "Exemplars dropped during input validation", + &["protocol"] + ).unwrap(); /// The native histograms count of Prometheus remote write per protocol version. pub static ref PROM_STORE_REMOTE_WRITE_HISTOGRAMS: IntCounterVec = register_int_counter_vec!( "greptime_servers_prometheus_remote_write_histograms", diff --git a/src/servers/src/otlp/trace/v2.rs b/src/servers/src/otlp/trace/v2.rs index dd43037822f..185beb43183 100644 --- a/src/servers/src/otlp/trace/v2.rs +++ b/src/servers/src/otlp/trace/v2.rs @@ -91,13 +91,13 @@ impl FixedTraceColumnIndexes { })?, span_attributes: writer.ensure_column(row_writer::build_json2_column_schema( SPAN_ATTRIBUTES_COLUMN, - ))?, + )?)?, scope_attributes: writer.ensure_column(row_writer::build_json2_column_schema( SCOPE_ATTRIBUTES_COLUMN, - ))?, + )?)?, resource_attributes: writer.ensure_column(row_writer::build_json2_column_schema( RESOURCE_ATTRIBUTES_COLUMN, - ))?, + )?)?, span_events: writer .ensure_column(row_writer::build_json_column_schema(SPAN_EVENTS_COLUMN))?, span_links: writer diff --git a/src/servers/src/prom_remote_write/decode.rs b/src/servers/src/prom_remote_write/decode.rs index f7324b4be6e..580fc5c57a3 100644 --- a/src/servers/src/prom_remote_write/decode.rs +++ b/src/servers/src/prom_remote_write/decode.rs @@ -14,10 +14,11 @@ //! Decoding of Prometheus remote write protobuf payloads. -use std::collections::BTreeMap; use std::collections::btree_map::Entry; +use std::collections::{BTreeMap, HashSet}; +use std::sync::Arc; -use api::prom_store::remote::Sample; +use api::prom_store::remote::{Exemplar, Sample}; use bytes::Buf; use common_query::prelude::{greptime_timestamp, greptime_value}; use pipeline::{ContextReq, GreptimePipelineParams, PipelineContext, PipelineDefinition}; @@ -33,8 +34,8 @@ use crate::error::InternalSnafu; use crate::http::event::PipelineIngestRequest; use crate::pipeline::run_pipeline; use crate::prom_remote_write::row_builder::{PromCtx, TablesBuilder}; -use crate::prom_remote_write::types::PromLabel; -use crate::prom_remote_write::validation::PromValidationMode; +use crate::prom_remote_write::types::{PromLabel, RawBytes}; +use crate::prom_remote_write::validation::{PromValidationMode, validate_label_name}; #[allow(deprecated)] use crate::prom_store::{ DATABASE_LABEL_ALT_BYTES, DATABASE_LABEL_BYTES, METRIC_NAME_LABEL_BYTES, @@ -51,6 +52,9 @@ pub(crate) struct PromTimeSeries { pub(crate) labels: RepeatedField, pub(crate) samples: RepeatedField, + exemplars: Vec, + label_names: HashSet, + duplicate_labels: bool, } impl Clear for PromTimeSeries { @@ -64,6 +68,9 @@ impl Clear for PromTimeSeries { } self.labels.clear(); self.samples.clear(); + self.exemplars.clear(); + self.label_names.clear(); + self.duplicate_labels = false; } } @@ -98,6 +105,7 @@ impl PromTimeSeries { return Err(DecodeError::new("delimited length exceeded")); } + self.duplicate_labels |= !self.label_names.insert(label.name); #[allow(deprecated)] let is_special_label = match label.name { METRIC_NAME_LABEL_BYTES => { @@ -138,7 +146,12 @@ impl PromTimeSeries { )?; Ok(()) } - 3u32 => prost::encoding::skip_field(wire_type, tag, buf, Default::default()), + 3u32 => { + let mut exemplar = Exemplar::default(); + merge(wire_type, &mut exemplar, buf, Default::default())?; + self.exemplars.push(exemplar); + Ok(()) + } 4u32 => Err(DecodeError::new( "remote write v1 native histogram ingestion is unsupported; use remote write v2", )), @@ -154,6 +167,66 @@ impl PromTimeSeries { let label_num = self.labels.len(); let row_num = self.samples.len(); + if !self.exemplars.is_empty() { + if self.duplicate_labels || self.table_name.is_empty() { + return Err(DecodeError::new( + "exemplar series requires a metric name and unique labels", + )); + } + let inherited = self + .labels + .iter() + .map(|label| { + Ok(( + prom_validation_mode + .decode_label_name(label.name)? + .to_string(), + prom_validation_mode.decode_string(label.value)?, + )) + }) + .collect::, DecodeError>>()?; + let inherited = Arc::new( + crate::exemplar::labels(inherited, false, validate_label_name) + .map_err(|error| DecodeError::new(error.to_string()))?, + ); + let metric: Arc = self.table_name.as_str().into(); + for exemplar in self.exemplars.drain(..) { + let observation: crate::error::Result<_> = (|| { + let labels = crate::exemplar::labels( + exemplar + .labels + .into_iter() + .map(|label| (label.name, label.value)), + true, + validate_label_name, + )?; + Ok(crate::exemplar::Exemplar { + metric: metric.clone(), + series_labels: inherited.clone(), + timestamp: crate::exemplar::timestamp_from_millis(exemplar.timestamp)?, + value: exemplar.value, + labels, + }) + })(); + let observation = match observation { + Ok(observation) => observation, + Err(_) => { + crate::metrics::EXEMPLARS_DROPPED_TOTAL + .with_label_values(&["prometheus_v1"]) + .inc(); + continue; + } + }; + table_builders + .exemplars + .entry(self.schema.clone()) + .or_default() + .push(observation); + } + } + if row_num == 0 { + return Ok(()); + } let prom_ctx = PromCtx { schema: self.schema.take(), physical_table: self.physical_table.take(), @@ -237,6 +310,11 @@ impl<'a> PromWriteRequest<'a> { return Err(DecodeError::new("delimited length exceeded")); } + if processor.use_pipeline && !self.series.exemplars.is_empty() { + return Err(DecodeError::new( + "Remote Write pipelines with exemplars are unsupported", + )); + } if processor.use_pipeline { processor.consume_series_to_pipeline_map( &mut self.series, @@ -469,6 +547,193 @@ mod tests { } } + #[test] + fn test_exemplar_decoder_shares_series_data_before_row_expansion() { + let metric = "m".repeat(64 * 1024); + let label = "x".repeat(64 * 1024); + let count = 128; + let wire = WriteRequest { + timeseries: vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: metric.clone(), + }, + Label { + name: "host".into(), + value: label.clone(), + }, + ], + exemplars: vec![Exemplar::default(); count], + ..Default::default() + }], + ..Default::default() + } + .encode_to_vec(); + assert!(wire.len() < 256 * 1024); + let mut decoder = PromWriteRequest::default(); + decoder + .decode( + wire, + PromValidationMode::Strict, + &mut PromSeriesProcessor::default_processor(), + ) + .unwrap(); + let requests = std::mem::take(&mut decoder.table_data.exemplars); + drop(decoder); + + let observations = &requests[&None]; + assert_eq!(observations.len(), count); + let first = &observations[0]; + for observation in observations { + assert_eq!(&*observation.metric, metric.as_str()); + assert_eq!(observation.series_labels["host"], label); + // Decoding retains one copy of series strings regardless of exemplar count. + assert_eq!(observation.metric.as_ptr(), first.metric.as_ptr()); + assert_eq!( + observation.series_labels["host"].as_ptr(), + first.series_labels["host"].as_ptr() + ); + } + assert!( + crate::exemplar::estimated_row_bytes(&requests).unwrap() + >= count * (metric.len() + label.len()) + ); + } + + #[test] + fn test_exemplar_decoder_preserves_data_across_requests() { + let valid = Exemplar { + timestamp: -1, + value: 0.5, + labels: vec![Label { + name: "traceID".into(), + value: "abc".into(), + }], + }; + let series = TimeSeries { + labels: vec![Label { + name: "__name__".into(), + value: "metric".into(), + }], + exemplars: vec![valid.clone()], + ..Default::default() + }; + let encode = |series| { + WriteRequest { + timeseries: vec![series], + ..Default::default() + } + .encode_to_vec() + }; + let sample = Sample { + timestamp: 2, + value: 1.0, + }; + let mut decoder = PromWriteRequest::default(); + let mut processor = PromSeriesProcessor::default_processor(); + for invalid in [ + Exemplar { + labels: vec![valid.labels[0].clone(); 2], + ..valid.clone() + }, + Exemplar { + labels: vec![Label { + name: "traceID".into(), + value: "x".repeat(128), + }], + ..valid.clone() + }, + Exemplar { + timestamp: i64::MAX, + ..valid.clone() + }, + ] { + for (exemplars, samples, expected) in [ + (vec![valid.clone()], vec![], 1), + (vec![invalid.clone()], vec![], 0), + ( + vec![invalid.clone(), valid.clone(), invalid, valid.clone()], + vec![sample], + 2, + ), + ] { + let sample_count = samples.len(); + decoder + .decode( + encode(TimeSeries { + exemplars, + samples, + ..series.clone() + }), + PromValidationMode::Strict, + &mut processor, + ) + .unwrap(); + let observations = decoder + .table_data + .exemplars + .get(&None) + .map(Vec::as_slice) + .unwrap_or_default(); + assert_eq!(observations.len(), expected); + for observation in observations { + assert_eq!(observation.timestamp, -1_000_000); + assert_eq!(observation.value, 0.5); + assert_eq!(observation.labels["traceID"], "abc"); + } + assert_eq!( + decoder + .as_row_insert_requests() + .all_req() + .map(|r| r.rows.unwrap().rows.len()) + .sum::(), + sample_count + ); + } + for name in ["__name__", "job"] { + let mut invalid = series.clone(); + invalid.labels.extend([ + Label { + name: name.into(), + value: "a".into(), + }, + Label { + name: name.into(), + value: "b".into(), + }, + ]); + assert!( + decoder + .decode(encode(invalid), PromValidationMode::Strict, &mut processor) + .is_err() + ); + } + // A pooled decoder must not leak rejected exemplars into its next request. + decoder + .decode( + encode(TimeSeries { + samples: vec![sample], + exemplars: vec![], + ..series.clone() + }), + PromValidationMode::Strict, + &mut processor, + ) + .unwrap(); + assert!(decoder.table_data.exemplars.is_empty()); + assert_eq!(decoder.as_row_insert_requests().all_req().count(), 1); + } + processor.use_pipeline = true; + assert!( + decoder + .decode(encode(series), PromValidationMode::Strict, &mut processor) + .unwrap_err() + .to_string() + .contains("pipelines with exemplars") + ); + } + #[test] fn test_decode_rejects_remote_write_v1_native_histograms() { for samples in [ diff --git a/src/servers/src/prom_remote_write/mod.rs b/src/servers/src/prom_remote_write/mod.rs index a54b50ad55b..2b67304b620 100644 --- a/src/servers/src/prom_remote_write/mod.rs +++ b/src/servers/src/prom_remote_write/mod.rs @@ -27,10 +27,11 @@ pub(crate) mod v2; pub mod validation; use bytes::Bytes; +use common_error::ext::BoxedError; use common_memory_manager::MemoryGuard; use lazy_static::lazy_static; use object_pool::Pool; -use snafu::ResultExt; +use snafu::{IntoError, ResultExt}; use crate::error; use crate::prom_remote_write::decode::{PromSeriesProcessor, PromWriteRequest}; @@ -137,3 +138,14 @@ pub async fn decode_remote_write_request( let tables = std::mem::take(&mut request.table_data); Ok((tables, guards)) } + +/// Maps memory wait timeouts to 5xx responses so Remote Write senders retry. +pub(crate) fn map_memory_acquire_timeout(error: error::Error) -> error::Error { + match error { + error::Error::MemoryLimitExceeded { + source: source @ common_memory_manager::Error::MemoryAcquireTimeout { .. }, + .. + } => error::OtherSnafu.into_error(BoxedError::new(source)), + error => error, + } +} diff --git a/src/servers/src/prom_remote_write/row_builder.rs b/src/servers/src/prom_remote_write/row_builder.rs index 08f5da61326..a87041b2eb0 100644 --- a/src/servers/src/prom_remote_write/row_builder.rs +++ b/src/servers/src/prom_remote_write/row_builder.rs @@ -37,12 +37,14 @@ pub struct PromCtx { pub struct TablesBuilder<'a> { pub tables: HashMap>>, pub(crate) raw_data: Vec, + pub(crate) exemplars: crate::exemplar::ExemplarRequests, } impl<'a> Clear for TablesBuilder<'a> { fn clear(&mut self) { self.tables.clear(); self.raw_data.clear(); + self.exemplars.clear(); } } diff --git a/src/servers/src/prom_remote_write/v2.rs b/src/servers/src/prom_remote_write/v2.rs index 3c36370fa2a..a8e11fc65e6 100644 --- a/src/servers/src/prom_remote_write/v2.rs +++ b/src/servers/src/prom_remote_write/v2.rs @@ -30,7 +30,6 @@ use api::v1::ColumnSchema; use api::v1::value::ValueData; use api::v1::{ColumnDataType, RowInsertRequest, Rows, SemanticType, Value}; use bytes::{Buf, Bytes}; -use common_error::ext::BoxedError; use common_memory_manager::{MemoryGuard, OnExhaustedPolicy}; #[cfg(test)] use common_query::native_histogram::*; @@ -51,7 +50,7 @@ use table::requests::{ use crate::error::{self, Result}; use crate::prom_remote_write::row_builder::PromCtx; -use crate::prom_remote_write::{REMOTE_WRITE_V2_VERSION, decompress_remote_write_body}; +use crate::prom_remote_write::{self, REMOTE_WRITE_V2_VERSION, decompress_remote_write_body}; #[allow(deprecated)] use crate::prom_store::{ DATABASE_LABEL, DATABASE_LABEL_ALT, METRIC_NAME_LABEL, PHYSICAL_TABLE_LABEL, @@ -125,6 +124,8 @@ pub(crate) struct RemoteWriteV2WriteRequests { pub histograms: ContextReq, pub sample_count: u64, pub histogram_count: u64, + pub exemplars: crate::exemplar::ExemplarRequests, + pub exemplar_count: u64, /// Per-table semantic metadata from the series' inline `Metadata`, folded /// into table options at auto-create time. pub semantic_index: SemanticIndexes, @@ -237,16 +238,7 @@ pub(crate) async fn decode_remote_write_v2( } OnExhaustedPolicy::Fail => decode.await, }; - result.map_err(|error| match error { - error::Error::MemoryLimitExceeded { - source: source @ common_memory_manager::Error::MemoryAcquireTimeout { .. }, - .. - } => { - // Prometheus retries 5xx; 429 may discard a request delayed by other writes. - error::OtherSnafu.into_error(BoxedError::new(source)) - } - error => error, - }) + result.map_err(prom_remote_write::map_memory_acquire_timeout) } async fn decode_remote_write_v2_once( @@ -335,6 +327,8 @@ fn convert_remote_write_v2( let mut label_names = HashSet::new(); let mut sample_count_total = 0; let mut histogram_count_total = 0; + let mut exemplar_count_total = 0; + let mut exemplars = crate::exemplar::ExemplarRequests::new(); let mut labels_refs = Vec::new(); let mut metadata = Metadata::default(); let mut scratch = LeafScratch::default(); @@ -343,8 +337,13 @@ fn convert_remote_write_v2( for series in request.timeseries { let counts = scan_series(series, &mut labels_refs, &mut metadata) .context(error::DecodePromRemoteRequestSnafu)?; + budget.reserve( + counts + .exemplars + .checked_mul(2 * std::mem::size_of::()), + )?; - if counts.samples == 0 && counts.histograms == 0 { + if counts.samples == 0 && counts.histograms == 0 && counts.exemplars == 0 { decode_series_leaves(series, None, Vec::new(), 0, &mut scratch)?; continue; } @@ -359,39 +358,52 @@ fn convert_remote_write_v2( }))?; let (prom_ctx, table_name, tags) = resolve_series_labels(&request.symbols, &labels_refs, &mut label_names)?; - ensure_no_internal_histogram_labels(&tags)?; - budget.reserve( - request - .symbols - .get(metadata.unit_ref as usize) - .map_or(Some(0), |unit| unit.len().checked_mul(4)), - )?; - record_series_metadata( - &mut semantic_index, - &request.symbols, - &metadata, - &prom_ctx, - &table_name, - )?; - let has_other_value_type = if counts.samples > 0 { - counts.histograms > 0 - || histogram_tables + let inherited = if counts.exemplars > 0 { + crate::exemplar::labels( + tags.iter() + .map(|(key, value)| ((*key).to_string(), value.clone())), + false, + |name| !name.is_empty(), + )? + } else { + Default::default() + }; + let exemplar_metric = table_name.clone(); + let exemplar_schema = prom_ctx.schema.clone(); + if counts.samples > 0 || counts.histograms > 0 { + ensure_no_internal_histogram_labels(&tags)?; + budget.reserve( + request + .symbols + .get(metadata.unit_ref as usize) + .map_or(Some(0), |unit| unit.len().checked_mul(4)), + )?; + record_series_metadata( + &mut semantic_index, + &request.symbols, + &metadata, + &prom_ctx, + &table_name, + )?; + let has_other_value_type = if counts.samples > 0 { + counts.histograms > 0 + || histogram_tables + .get(&prom_ctx) + .is_some_and(|tables| tables.contains_key(&table_name)) + } else { + sample_tables .get(&prom_ctx) .is_some_and(|tables| tables.contains_key(&table_name)) - } else { - sample_tables - .get(&prom_ctx) - .is_some_and(|tables| tables.contains_key(&table_name)) - }; - ensure!( - !has_other_value_type, - error::InvalidPromRemoteRequestSnafu { - msg: format!( - "remote write v2 metric `{table_name}` contains both samples and native histograms" - ), - } - ); - + }; + ensure!( + !has_other_value_type, + error::InvalidPromRemoteRequestSnafu { + msg: format!( + "remote write v2 metric `{table_name}` contains both samples and native histograms" + ), + } + ); + } let column_count = tags.len() .checked_add(2) @@ -450,39 +462,114 @@ fn convert_remote_write_v2( })())?; let (writer, row_count) = if counts.samples > 0 { ( - SeriesWriter::Samples(get_or_create_table_data( + Some(SeriesWriter::Samples(get_or_create_table_data( &mut sample_tables, prom_ctx, table_name, column_count, counts.samples, - )), + ))), counts.samples, ) - } else { + } else if counts.histograms > 0 { ( - SeriesWriter::Histograms(get_or_create_table_data( + Some(SeriesWriter::Histograms(get_or_create_table_data( &mut histogram_tables, prom_ctx, table_name, column_count, counts.histograms, - )), + ))), counts.histograms, ) + } else { + (None, 0) }; - decode_series_leaves(series, Some(writer), tags, row_count, &mut scratch)?; + decode_series_leaves(series, writer, tags, row_count, &mut scratch)?; + if !scratch.exemplars.is_empty() { + let inherited = Arc::new(inherited); + let exemplar_metric: Arc = exemplar_metric.into(); + for exemplar in scratch.exemplars.drain(..) { + ensure!( + exemplar.labels_refs.len() % 2 == 0, + error::InvalidPromRemoteRequestSnafu { + msg: "exemplar label references must contain name/value pairs", + } + ); + let exemplar_label_bytes = + exemplar + .labels_refs + .iter() + .try_fold(0usize, |bytes, index| { + bytes.checked_add( + request.symbols.get(*index as usize).map_or(0, |s| s.len()), + ) + }); + // Symbol references can expand into repeated owned labels for every exemplar. + budget.reserve((|| { + label_bytes? + .checked_add(exemplar_label_bytes?)? + .checked_mul(4)? + .checked_add( + labels_refs + .len() + .checked_add(exemplar.labels_refs.len())? + .checked_mul(128)?, + )? + .checked_add(2 * std::mem::size_of::()) + })())?; + let labels = exemplar + .labels_refs + .as_chunks::<2>() + .0 + .iter() + .map(|pair| { + Ok(( + symbol_ref(&request.symbols, pair[0], "exemplar label")?.to_string(), + symbol_ref(&request.symbols, pair[1], "exemplar value")?.to_string(), + )) + }) + .collect::>>()?; + let observation: Result<_> = (|| { + Ok(crate::exemplar::Exemplar { + metric: exemplar_metric.clone(), + series_labels: inherited.clone(), + timestamp: crate::exemplar::timestamp_from_millis(exemplar.timestamp)?, + value: exemplar.value, + labels: crate::exemplar::labels(labels, true, |name| !name.is_empty())?, + }) + })(); + let observation = match observation { + Ok(observation) => observation, + Err(_) => { + crate::metrics::EXEMPLARS_DROPPED_TOTAL + .with_label_values(&["prometheus_v2"]) + .inc(); + continue; + } + }; + exemplars + .entry(exemplar_schema.clone()) + .or_default() + .push(observation); + exemplar_count_total = checked_total(exemplar_count_total, 1, "exemplar")?; + } + } sample_count_total = checked_total(sample_count_total, counts.samples, "sample")?; histogram_count_total = checked_total(histogram_count_total, counts.histograms, "histogram")?; } + budget.reserve(crate::exemplar::estimated_row_bytes(&exemplars))?; + Ok(RemoteWriteV2WriteRequests { samples: into_context_req(sample_tables), histograms: into_context_req(histogram_tables), sample_count: sample_count_total, histogram_count: histogram_count_total, + exemplar_count: exemplar_count_total, + exemplars, semantic_index, memory_guard: Arc::new(budget.guard), }) @@ -555,6 +642,7 @@ fn metric_type_value(wire_type: i32) -> Option<&'static str> { #[derive(Default)] struct SeriesCounts { + exemplars: usize, samples: usize, histograms: usize, } @@ -598,6 +686,10 @@ fn scan_series( } TIME_SERIES_EXEMPLARS_TAG => { take_length_delimited(wire_type, &mut buf)?; + counts.exemplars = counts + .exemplars + .checked_add(1) + .ok_or_else(|| DecodeError::new("exemplar count overflow"))?; } TIME_SERIES_METADATA_TAG => { message::merge(wire_type, metadata, &mut buf, DecodeContext::default()).map_err( @@ -619,6 +711,7 @@ struct LeafScratch { sample: Sample, histogram: Histogram, exemplar: Exemplar, + exemplars: Vec, } enum SeriesWriter<'a> { @@ -635,6 +728,7 @@ fn decode_series_leaves( ) -> Result<()> { let mut sample_row_template = None; let mut histogram_row_template = None; + scratch.exemplars.clear(); while buf.has_remaining() { let (tag, wire_type) = decode_key(&mut buf).context(error::DecodePromRemoteRequestSnafu)?; @@ -781,6 +875,9 @@ fn decode_series_leaves( error }) .context(error::DecodePromRemoteRequestSnafu)?; + scratch + .exemplars + .push(std::mem::take(&mut scratch.exemplar)); } TIME_SERIES_METADATA_TAG => { take_length_delimited(wire_type, &mut buf) @@ -1357,7 +1454,7 @@ mod tests { } #[test] - fn test_fused_decoder_ignores_exemplar_symbol_refs() { + fn test_fused_decoder_rejects_invalid_exemplar_symbol_refs() { let request = Request { symbols: vec![ String::new(), @@ -1375,7 +1472,66 @@ mod tests { }], }; - assert_eq!(decode_test_request(request).unwrap().sample_count, 1); + assert!(decode_test_request(request).is_err()); + } + + #[test] + fn test_invalid_exemplars_preserve_samples_and_counts() { + let valid = Exemplar { + labels_refs: vec![3, 4], + timestamp: 1, + value: 0.5, + }; + for invalid in [ + Exemplar { + labels_refs: vec![3, 4, 3, 4], + ..valid.clone() + }, + Exemplar { + labels_refs: vec![3, 5], + ..valid.clone() + }, + Exemplar { + timestamp: i64::MAX, + ..valid.clone() + }, + Exemplar { + labels_refs: vec![6, 4], + ..valid.clone() + }, + ] { + for retain_valid in [false, true] { + let mut observations = vec![invalid.clone()]; + if retain_valid { + observations.extend([valid.clone(), invalid.clone(), valid.clone()]); + } + let request = Request { + symbols: vec![ + "".into(), + METRIC_NAME_LABEL.into(), + "metric".into(), + "trace_id".into(), + "abc".into(), + "x".repeat(128), + datatypes::json::JSON2_REMAINDER_FIELD_NAME.into(), + ], + timeseries: vec![TimeSeries { + labels_refs: vec![1, 2], + samples: vec![Sample::default()], + exemplars: observations, + ..Default::default() + }], + }; + let converted = decode_test_request(request).unwrap(); + assert_eq!(converted.sample_count, 1); + let expected = if retain_valid { 2 } else { 0 }; + assert_eq!(converted.exemplar_count, expected); + assert_eq!( + converted.exemplars.values().map(Vec::len).sum::(), + expected as usize + ); + } + } } #[test] @@ -1634,6 +1790,38 @@ mod tests { assert!(budget.reserve(usize::MAX.checked_mul(2)).is_err()); } + #[tokio::test] + async fn test_exemplar_conversion_reserves_repeated_labels() { + let limiter = ServerMemoryLimiter::new(128 * 1024, OnExhaustedPolicy::Fail); + let label = "x".repeat(4096); + let mut request = + request_with_sample(vec![(METRIC_NAME_LABEL, "metric"), ("host", &label)]); + request.timeseries[0].samples.clear(); + request.timeseries[0].exemplars = vec![Exemplar::default(); 128]; + let body = + Bytes::from(crate::prom_store::snappy_compress(&request.encode_to_vec()).unwrap()); + assert!(matches!( + decode_remote_write_v2(false, body, &limiter, 0).await, + Err(error::Error::MemoryLimitExceeded { .. }) + )); + assert_eq!(limiter.used_bytes(), 0); + + request.timeseries[0].exemplars.truncate(1); + let body = + Bytes::from(crate::prom_store::snappy_compress(&request.encode_to_vec()).unwrap()); + let decoded = decode_remote_write_v2(false, body, &limiter, 0) + .await + .unwrap(); + assert_eq!(decoded.exemplar_count, 1); + assert!(limiter.used_bytes() >= label.len() as u64); + let progress = + session::write_progress::WriteProgress::with_reservation(decoded.memory_guard.clone()); + drop(decoded); + assert!(limiter.used_bytes() >= label.len() as u64); + drop(progress); + assert_eq!(limiter.used_bytes(), 0); + } + #[tokio::test] async fn test_large_symbols_do_not_reserve_body_multiples_or_retain_scratch() { let limiter = ServerMemoryLimiter::new(64 * 1024 * 1024, OnExhaustedPolicy::Fail); @@ -1757,7 +1945,17 @@ mod tests { ("区域", "西"), ("has-dash", "value"), ]; - let sample = request_with_sample(labels.clone()); + let mut sample = request_with_sample(labels.clone()); + let name = push_test_symbol(&mut sample.symbols, "trace.id"); + let value = push_test_symbol(&mut sample.symbols, "abc"); + sample.timeseries[0].exemplars = vec![Exemplar { + labels_refs: vec![name, value], + ..Default::default() + }]; + let decoded = decode_test_request(sample.clone()).unwrap(); + assert_eq!(decoded.exemplar_count, 1); + assert_eq!(decoded.exemplars[&None][0].series_labels["区域"], "西"); + assert_eq!(decoded.exemplars[&None][0].labels["trace.id"], "abc"); let (requests, _, _, _) = test_util::write_requests(sample).unwrap(); let sample_rows = requests[0].rows.as_ref().unwrap(); assert_eq!(sample_rows.schema[3].column_name, "区域"); @@ -2225,7 +2423,7 @@ mod tests { } #[test] - fn test_into_context_req_converts_histograms_and_ignores_exemplars() { + fn test_into_context_req_preserves_histogram_exemplars() { let request = Request { symbols: vec![ "".to_string(), @@ -2256,6 +2454,11 @@ mod tests { assert_eq!(ctx_req.sample_count, 1); assert_eq!(ctx_req.histogram_count, 1); + assert_eq!(ctx_req.exemplar_count, 1); + assert_eq!( + ctx_req.exemplars[&None][0].metric.as_ref(), + "histogram_metric" + ); assert_eq!(ctx_req.samples.all_req().count(), 1); assert_eq!(ctx_req.histograms.all_req().count(), 1); } diff --git a/src/servers/src/query_handler.rs b/src/servers/src/query_handler.rs index 57f55855ac1..c0d1d7c9b0b 100644 --- a/src/servers/src/query_handler.rs +++ b/src/servers/src/query_handler.rs @@ -39,6 +39,7 @@ use headers::HeaderValue; use log_query::LogQuery; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use operator::insert::PreparedMetricInserts; use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; use pipeline::{GreptimePipelineParams, Pipeline, PipelineInfo, PipelineVersion, PipelineWay}; use serde_json::Value; @@ -109,6 +110,64 @@ pub struct PromStoreResponse { #[async_trait] pub trait PromStoreProtocolHandler { + /// Resolves metric destinations before source identities are attached to exemplars. + /// Requires pre-write checks and admission to have succeeded for the entire request. + async fn prepare_metric_write( + &self, + _request: RowInsertRequests, + _ctx: QueryContextRef, + ) -> Result { + crate::error::NotSupportedSnafu { + feat: "metric write preparation", + } + .fail() + } + + /// Executes the same routed metric writes used to resolve exemplar source identities. + async fn write_prepared_metric( + &self, + _request: PreparedMetricInserts, + _ctx: QueryContextRef, + ) -> Result { + crate::error::NotSupportedSnafu { + feat: "prepared metric ingestion", + } + .fail() + } + + /// Writes exemplars using table identities captured while preparing the source metrics. + async fn write_exemplars_with_sources( + &self, + request: RowInsertRequests, + ctx: QueryContextRef, + _sources: &[TableInfoRef], + ) -> Result { + self.write_exemplars_prepared(request, ctx).await + } + + /// Authorizes source series, including inputs with no metric samples. + async fn check_exemplar_sources( + &self, + _sources: &std::collections::BTreeSet, + _ctx: QueryContextRef, + ) -> Result<()> { + crate::error::NotSupportedSnafu { + feat: "exemplar source authorization", + } + .fail() + } + + async fn write_exemplars_prepared( + &self, + _request: RowInsertRequests, + _ctx: QueryContextRef, + ) -> Result { + crate::error::NotSupportedSnafu { + feat: "exemplar ingestion", + } + .fail() + } + /// Runs pre-write checks/hooks for prometheus remote write requests. async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()>; diff --git a/src/servers/src/row_writer.rs b/src/servers/src/row_writer.rs index 74ef6cedc0d..95a6f34260a 100644 --- a/src/servers/src/row_writer.rs +++ b/src/servers/src/row_writer.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::sync::Arc; use ahash::{HashMap as AHashMap, HashMapExt}; -use api::helper::encode_json_value; +use api::helper::{ColumnDataTypeWrapper, encode_json_value}; use api::v1::column_data_type_extension::TypeExt; use api::v1::helper::time_index_column_schema; use api::v1::value::ValueData; @@ -33,6 +33,8 @@ use common_time::timestamp::TimeUnit; use common_time::timestamp::TimeUnit::Nanosecond; use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; use datatypes::json::JsonSettings; +use datatypes::prelude::ConcreteDataType; +use datatypes::types::json_type::JsonNativeType; use datatypes::value::Value as DataValue; use serde::Serialize; use snafu::{OptionExt, ResultExt, ensure}; @@ -356,7 +358,7 @@ pub fn write_json( ) } -pub(crate) fn build_json2_column_schema(name: impl ToString) -> ColumnSchema { +pub(crate) fn build_json2_column_schema(name: impl ToString) -> Result { let extension = Json2ExtensionType::new(Arc::new(JsonMetadata::new(JsonSettings::new_v2()))); let mut options = ColumnOptions::default(); options.options.insert( @@ -369,13 +371,23 @@ pub(crate) fn build_json2_column_schema(name: impl ToString) -> ColumnSchema { .insert(EXTENSION_TYPE_METADATA_KEY.to_string(), metadata); } - ColumnSchema { + Ok(ColumnSchema { column_name: name.to_string(), datatype: ColumnDataType::Json as i32, semantic_type: SemanticType::Field as i32, + datatype_extension: ColumnDataTypeWrapper::try_from(ConcreteDataType::json2( + JsonNativeType::Null, + )) + .map_err(|error| { + InternalSnafu { + err_msg: error.to_string(), + } + .build() + })? + .into_parts() + .1, options: Some(options), - ..Default::default() - } + }) } /// Encodes a JSON2 field without constructing its column schema. diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index c1f886c6ed7..86bd1409c1a 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -50,7 +50,7 @@ async fn test_sparse_primary_key_schema_validation(instance: Arc { + add(&mut request, &[("__name__", "unpinned")]); + request.timeseries[1].samples.clear(); + request.timeseries[1].histograms.push(v2::Histogram { + count: Some(v2::histogram::Count::CountInt(0)), + timestamp: 1000, + ..Default::default() + }); + } + "schema_alias" => { + add( + &mut request, + &[("__name__", "unpinned"), ("left_tag", "left")], + ); + add( + &mut request, + &[ + ("__name__", "unpinned"), + ("__schema__", "public"), + ("right_tag", "right"), + ], + ); + } + "physical_conflict" => { + for (physical, job) in [("physical_a", "one"), ("physical_b", "two")] { + execute_sql(frontend, &format!( + "CREATE TABLE {physical} (greptime_timestamp TIMESTAMP TIME INDEX, greptime_value DOUBLE, job STRING PRIMARY KEY) ENGINE=metric WITH ('physical_metric_table'='')" + )).await; + add( + &mut request, + &[ + ("__name__", "unpinned"), + ("__physical_table__", physical), + ("job", job), + ], + ); + } + } + _ => unreachable!(), + } + let response = app + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header( + "Content-Type", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + ) + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + assert_eq!( + response.headers()["x-prometheus-remote-write-samples-written"], + if kind == "histogram" { "1" } else { "3" } + ); + assert_eq!( + response.headers()["x-prometheus-remote-write-histograms-written"], + if kind == "histogram" { "1" } else { "0" } + ); + assert_eq!( + response.headers()["x-prometheus-remote-write-exemplars-written"], + "1" + ); + let filter = match kind { + "histogram" => "greptime_native_histogram IS NOT NULL", + "schema_alias" => "left_tag = 'left' OR right_tag = 'right'", + "physical_conflict" => "job IN ('one', 'two')", + _ => unreachable!(), + }; + let output = execute_sql( + frontend, + &format!("SELECT count(*) FROM unpinned WHERE {filter}"), + ) + .await; + check_output_stream( + output.data, + &format!( + "+----------+\n| count(*) |\n+----------+\n| {} |\n+----------+", + if kind == "histogram" { 1 } else { 2 } + ), + ) + .await; +} + +#[rstest] +#[case::lowercase("sparse", true, true, 9)] +#[case::uppercase("SPARSE", true, true, 9)] +#[case::mixed_case("SpArSe", true, true, 9)] +#[case::dense("dense", true, false, 9)] +#[case::not_append_only("sparse", false, false, 9)] +#[case::seconds("sparse", true, true, 0)] +#[case::milliseconds("sparse", true, true, 3)] +#[case::microseconds("sparse", true, true, 6)] +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_precreated_table_options( + #[case] encoding: &str, + #[case] append_mode: bool, + #[case] accepted: bool, + #[case] precision: u32, +) { + use std::collections::BTreeMap; + + use servers::exemplar::{Exemplar, into_rows}; + use servers::query_handler::PromStoreProtocolHandler; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("exemplar_precreated_table_options") + .build() + .await; + let frontend = instance.fe_instance(); + execute_sql(frontend, "CREATE TABLE source_physical (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')").await; + execute_sql(frontend, "CREATE TABLE metric_source (job STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('on_physical_table'='source_physical')").await; + execute_sql(frontend, &format!( + "CREATE TABLE metrics_exemplars (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_metric STRING, greptime_timestamp TIMESTAMP({precision}) TIME INDEX, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) ENGINE=mito WITH ('append_mode'='{append_mode}', 'primary_key_encoding'='{encoding}', 'compaction.type'='twcs')" + )).await; + let (request, _) = into_rows(vec![Exemplar { + metric: "metric_source".into(), + series_labels: BTreeMap::from([("job".into(), "api".into())]).into(), + timestamp: 1_234_567_890, + value: 2.0, + labels: BTreeMap::new(), + }]) + .unwrap(); + let result = frontend + .write_exemplars_prepared(request, QueryContext::arc()) + .await; + if accepted { + assert_eq!(result.unwrap().extract_rows_and_cost().0, 1); + } else { + let error = result.unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!( + error.output_msg().contains( + "metrics_exemplars requires Mito, append_mode=true and primary_key_encoding=sparse" + ), + "{error:?}" + ); + } + let table = frontend + .catalog_manager() + .table("greptime", "public", "metrics_exemplars", None) + .await + .unwrap() + .unwrap(); + // Invalid destinations must fail before auto-ALTER adds the inherited label. + assert_eq!( + table.schema().column_schema_by_name("job").is_some(), + accepted + ); + let sql = if accepted { + let timestamp = 1_234_567_890 / 10_i64.pow(9 - precision); + format!( + "SELECT count(*) FROM metrics_exemplars WHERE job = 'api' AND greptime_value = 2.0 AND CAST(greptime_timestamp AS BIGINT) = {timestamp}" + ) + } else { + "SELECT count(*) FROM metrics_exemplars".into() + }; + let output = execute_sql(frontend, &sql).await; + check_output_stream( + output.data, + &format!( + "+----------+\n| count(*) |\n+----------+\n| {} |\n+----------+", + usize::from(accepted) + ), + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_source_identity_policy() { + use std::collections::BTreeMap; + + use servers::exemplar::{Exemplar, into_rows}; + use servers::query_handler::PromStoreProtocolHandler; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("exemplar_source_identity") + .build() + .await; + let frontend = instance.fe_instance(); + let request = |name: &str| { + into_rows(vec![Exemplar { + metric: name.into(), + series_labels: BTreeMap::from([("job".into(), "api".into())]).into(), + timestamp: 1, + value: 2.0, + labels: BTreeMap::new(), + }]) + .unwrap() + .0 + }; + execute_sql( + frontend, + "CREATE TABLE ordinary_source (ts TIMESTAMP TIME INDEX, val DOUBLE)", + ) + .await; + for name in ["missing_source", "ordinary_source"] { + let error = frontend + .write_exemplars_prepared(request(name), QueryContext::arc()) + .await + .unwrap_err(); + assert!( + error + .output_msg() + .contains("existing logical metric-engine table"), + "{error:?}" + ); + } + assert!( + frontend + .catalog_manager() + .table("greptime", "public", "metrics_exemplars", None) + .await + .unwrap() + .is_none() + ); + execute_sql(frontend, "CREATE TABLE source_physical (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')").await; + let create = "CREATE TABLE metric_source (job STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('on_physical_table'='source_physical')"; + execute_sql(frontend, create).await; + let source = frontend + .catalog_manager() + .table("greptime", "public", "metric_source", None) + .await + .unwrap() + .unwrap() + .table_info(); + // A metric write's captured table ID must not be replaced by a later name lookup. + execute_sql(frontend, "DROP TABLE metric_source").await; + execute_sql(frontend, create).await; + let replacement = frontend + .catalog_manager() + .table("greptime", "public", "metric_source", None) + .await + .unwrap() + .unwrap() + .table_info(); + assert_ne!(source.table_id(), replacement.table_id()); + frontend + .write_exemplars_with_sources( + request("metric_source"), + QueryContext::arc(), + std::slice::from_ref(&source), + ) + .await + .unwrap(); + frontend + .write_exemplars_prepared(request("metric_source"), QueryContext::arc()) + .await + .unwrap(); + let table = frontend + .catalog_manager() + .table("greptime", "public", "metrics_exemplars", None) + .await + .unwrap() + .unwrap(); + let info = table.table_info(); + assert_eq!( + info.meta + .schema + .column_schemas() + .iter() + .map(|column| column.name.as_str()) + .collect::>(), + [ + "__table_id", + "__tsid", + "greptime_metric", + "job", + "greptime_value", + "greptime_timestamp", + "exemplar_labels", + ] + ); + assert_eq!(info.meta.primary_key_indices, [0, 1, 2, 3]); + let output = execute_sql( + frontend, + "SELECT __table_id FROM metrics_exemplars ORDER BY __table_id", + ) + .await; + let OutputData::Stream(stream) = output.data else { + panic!("expected stream") + }; + let batches = util::collect_batches(stream).await.unwrap(); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .to_vec() + }) + .collect::>(); + assert_eq!(ids, vec![source.table_id(), replacement.table_id()]); +} diff --git a/tests/compatibility/cases/exemplar_sparse/case.toml b/tests/compatibility/cases/exemplar_sparse/case.toml new file mode 100644 index 00000000000..d245bc00b20 --- /dev/null +++ b/tests/compatibility/cases/exemplar_sparse/case.toml @@ -0,0 +1,8 @@ +name = "exemplar_sparse" +reason = "Preserve reserved sparse source identity keys, append duplicates and nanosecond timestamps across restart." +introduced_by = "persistent_metric_exemplars" +topologies = ["standalone", "distributed"] +from_range = [">=v1.4.0-alpha.0"] +to_range = [">=v1.4.0-alpha.0"] +features = ["sparse", "table", "read"] +owner = "mito2" diff --git a/tests/compatibility/cases/exemplar_sparse/setup.sql b/tests/compatibility/cases/exemplar_sparse/setup.sql new file mode 100644 index 00000000000..dc1a09b4b48 --- /dev/null +++ b/tests/compatibility/cases/exemplar_sparse/setup.sql @@ -0,0 +1,15 @@ +CREATE TABLE exemplar_source_ids ( + __table_id INT UNSIGNED NOT NULL, + __tsid BIGINT UNSIGNED NOT NULL, + greptime_metric STRING, + greptime_timestamp TIMESTAMP(9) TIME INDEX, + greptime_value DOUBLE, + PRIMARY KEY (__table_id, __tsid, greptime_metric) +) WITH ('append_mode'='true', 'primary_key_encoding'='sparse'); +INSERT INTO exemplar_source_ids VALUES + (42, 18446744073709551615, 'cpu', 20, 1.0), + (42, 18446744073709551615, 'cpu', 20, 1.0), + (43, 18446744073709551615, 'memory', 10, 2.0); +ADMIN FLUSH_TABLE('exemplar_source_ids'); +ALTER TABLE exemplar_source_ids ADD COLUMN job STRING PRIMARY KEY; +INSERT INTO exemplar_source_ids VALUES (42, 7, 'cpu', 30, 3.0, 'api'); diff --git a/tests/compatibility/cases/exemplar_sparse/verify.result b/tests/compatibility/cases/exemplar_sparse/verify.result new file mode 100644 index 00000000000..67e016ea127 --- /dev/null +++ b/tests/compatibility/cases/exemplar_sparse/verify.result @@ -0,0 +1,42 @@ +SELECT * FROM exemplar_source_ids ORDER BY __tsid, greptime_timestamp; + ++------------+----------------------+-----------------+-------------------------------+----------------+-----+ +| __table_id | __tsid | greptime_metric | greptime_timestamp | greptime_value | job | ++------------+----------------------+-----------------+-------------------------------+----------------+-----+ +| 42 | 7 | cpu | 1970-01-01T00:00:00.000000030 | 3.0 | api | +| 43 | 18446744073709551615 | memory | 1970-01-01T00:00:00.000000010 | 2.0 | | +| 42 | 18446744073709551615 | cpu | 1970-01-01T00:00:00.000000020 | 1.0 | | +| 42 | 18446744073709551615 | cpu | 1970-01-01T00:00:00.000000020 | 1.0 | | ++------------+----------------------+-----------------+-------------------------------+----------------+-----+ + +ADMIN FLUSH_TABLE('exemplar_source_ids'); + ++------------------------------------------+ +| ADMIN FLUSH_TABLE('exemplar_source_ids') | ++------------------------------------------+ +| 0 | ++------------------------------------------+ + +ADMIN COMPACT_TABLE('exemplar_source_ids', 'swcs', '86400'); + ++-------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('exemplar_source_ids', 'swcs', '86400') | ++-------------------------------------------------------------+ +| 0 | ++-------------------------------------------------------------+ + +SELECT COUNT(*) FROM exemplar_source_ids WHERE __table_id = 42 AND __tsid = 18446744073709551615 AND job IS NULL; + ++----------+ +| count(*) | ++----------+ +| 2 | ++----------+ + +SELECT COUNT(*) FROM exemplar_source_ids WHERE __table_id = 43 AND __tsid = 18446744073709551615; + ++----------+ +| count(*) | ++----------+ +| 1 | ++----------+ diff --git a/tests/compatibility/cases/exemplar_sparse/verify.sql b/tests/compatibility/cases/exemplar_sparse/verify.sql new file mode 100644 index 00000000000..71f1112bd9d --- /dev/null +++ b/tests/compatibility/cases/exemplar_sparse/verify.sql @@ -0,0 +1,5 @@ +SELECT * FROM exemplar_source_ids ORDER BY __tsid, greptime_timestamp; +ADMIN FLUSH_TABLE('exemplar_source_ids'); +ADMIN COMPACT_TABLE('exemplar_source_ids', 'swcs', '86400'); +SELECT COUNT(*) FROM exemplar_source_ids WHERE __table_id = 42 AND __tsid = 18446744073709551615 AND job IS NULL; +SELECT COUNT(*) FROM exemplar_source_ids WHERE __table_id = 43 AND __tsid = 18446744073709551615;