Skip to main content

servers/otlp/
metrics.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use ahash::HashSet;
16use api::greptime_proto::io::prometheus::write::v2::histogram::{
17    Count as PromCount, ResetHint, ZeroCount as PromZeroCount,
18};
19use api::greptime_proto::io::prometheus::write::v2::{BucketSpan, Histogram as PromHistogram};
20use api::v1::value::ValueData;
21use api::v1::{ColumnSchema, RowInsertRequests, SemanticType, Value};
22use common_grpc::precision::Precision;
23use common_query::native_histogram::{
24    encode_native_histogram, native_histogram_column_schema, native_histogram_value_type,
25};
26use common_query::prelude::{
27    GREPTIME_TEMPORALITY_DELTA, OTLP_AGGREGATION_TEMPORALITY_LABEL, greptime_timestamp,
28    greptime_value,
29};
30use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
31use lazy_static::lazy_static;
32use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
33use otel_arrow_rust::proto::opentelemetry::common::v1::{AnyValue, KeyValue, any_value};
34use otel_arrow_rust::proto::opentelemetry::metrics::v1::{metric, number_data_point, *};
35use session::protocol_ctx::{MetricType, OtlpMetricCtx};
36use snafu::OptionExt;
37use table::requests::{
38    METADATA_QUALITY_DECLARED, METRIC_TEMPORALITY_CUMULATIVE, METRIC_TEMPORALITY_DELTA,
39    SEMANTIC_METRIC_METADATA_QUALITY, SEMANTIC_METRIC_ORIGINAL_NAME, SEMANTIC_METRIC_TEMPORALITY,
40    SEMANTIC_METRIC_TYPE, SEMANTIC_METRIC_UNIT,
41};
42
43use crate::error::{self, Result};
44use crate::metrics::OTLP_EXPONENTIAL_HISTOGRAM_REJECTED_DATA_POINTS;
45use crate::otlp::trace::{KEY_SERVICE_INSTANCE_ID, KEY_SERVICE_NAME, KEY_SERVICE_NAMESPACE};
46use crate::query_handler::MetricsIngestOutcome;
47use crate::row_writer::{self, MultiTableData, TableData};
48pub use crate::semantic::SemanticIndex;
49use crate::semantic::{
50    METRIC_TYPE_COUNTER, METRIC_TYPE_GAUGE, METRIC_TYPE_HISTOGRAM, METRIC_TYPE_SUMMARY,
51    METRIC_TYPE_UPDOWN_COUNTER,
52};
53
54mod exemplars;
55mod prepare;
56mod resource_info;
57
58pub use prepare::{PreparedMetrics, prepare_metrics};
59mod translator;
60
61pub use resource_info::OTEL_RESOURCE_INFO_TABLE_NAME;
62use resource_info::ResourceInfoData;
63pub(crate) use translator::ucum_to_openmetrics_unit;
64use translator::{translate_label_name, translate_metric_name};
65
66/// the default column count for table writer
67const APPROXIMATE_COLUMN_COUNT: usize = 8;
68
69const COUNT_TABLE_SUFFIX: &str = "_count";
70const SUM_TABLE_SUFFIX: &str = "_sum";
71const BUCKET_TABLE_SUFFIX: &str = "_bucket";
72
73const JOB_KEY: &str = "job";
74const INSTANCE_KEY: &str = "instance";
75
76// see: https://prometheus.io/docs/guides/opentelemetry/#promoting-resource-attributes
77const DEFAULT_PROMOTE_ATTRS: [&str; 19] = [
78    "service.instance.id",
79    "service.name",
80    "service.namespace",
81    "service.version",
82    "cloud.availability_zone",
83    "cloud.region",
84    "container.name",
85    "deployment.environment",
86    "deployment.environment.name",
87    "k8s.cluster.name",
88    "k8s.container.name",
89    "k8s.cronjob.name",
90    "k8s.daemonset.name",
91    "k8s.deployment.name",
92    "k8s.job.name",
93    "k8s.namespace.name",
94    "k8s.pod.name",
95    "k8s.replicaset.name",
96    "k8s.statefulset.name",
97];
98
99lazy_static! {
100    static ref DEFAULT_PROMOTE_ATTRS_SET: HashSet<String> =
101        HashSet::from_iter(DEFAULT_PROMOTE_ATTRS.iter().map(|s| s.to_string()));
102}
103
104const OTEL_SCOPE_NAME: &str = "name";
105const OTEL_SCOPE_VERSION: &str = "version";
106const OTEL_SCOPE_SCHEMA_URL: &str = "schema_url";
107const MIN_EXPONENTIAL_HISTOGRAM_SCALE: i32 = -4;
108const MAX_EXPONENTIAL_HISTOGRAM_SCALE: i32 = 8;
109const MAX_REJECTION_MESSAGE_BYTES: usize = 512;
110
111/// Result of converting one OTLP metrics request.
112#[derive(Debug)]
113pub struct MetricsConversion {
114    /// Kept normalized until the frontend reserves memory for row expansion.
115    pub exemplars: Vec<crate::exemplar::Exemplar>,
116    pub requests: RowInsertRequests,
117    /// Row count of `requests`; the resource descriptor is not counted.
118    pub rows: usize,
119    /// Per-table semantic index for the auto-create path to stamp as table
120    /// options; covers the descriptor table too.
121    pub semantic_index: SemanticIndex,
122    /// The synthesized resource descriptor, written separately from the
123    /// metric data. See [`resource_info`].
124    pub resource_info: Option<RowInsertRequests>,
125    pub outcome: MetricsIngestOutcome,
126}
127
128struct MetricMetadata {
129    name: String,
130    original_name: String,
131    native_schema: Option<ColumnSchema>,
132    semantics: SemanticIndex,
133}
134
135impl MetricMetadata {
136    fn new(metric: &Metric, ctx: &OtlpMetricCtx) -> Result<Self> {
137        let name = translate_metric_name(metric, &ctx.metric_type, ctx.metric_translation_strategy);
138        let emitted = emitted_semantic_tables(&ctx.metric_type, &name);
139        let mut semantics = SemanticIndex::default();
140        record_metric_semantics(&mut semantics, metric, &name, &emitted);
141        let native_schema = matches!(metric.data, Some(metric::Data::ExponentialHistogram(_)))
142            .then(native_histogram_column_schema)
143            .transpose()
144            .map_err(|error| {
145                error::InternalSnafu {
146                    err_msg: error.to_string(),
147                }
148                .build()
149            })?;
150        Ok(Self {
151            name,
152            original_name: metric.name.clone(),
153            native_schema,
154            semantics,
155        })
156    }
157}
158
159/// Converts OpenTelemetry metrics without validating destination table schemas.
160/// Ingestion callers use [`prepare_metrics`], run destination preflight, then call
161/// [`PreparedMetrics::finish`] to apply rejections and merge surviving points.
162///
163/// See
164/// <https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto>
165/// for data structure of OTLP metrics.
166pub fn to_grpc_insert_requests(
167    request: ExportMetricsServiceRequest,
168    metric_ctx: &mut OtlpMetricCtx,
169) -> Result<MetricsConversion> {
170    let prepared = prepare_metrics(request, metric_ctx)?;
171    let rejections = vec![None; prepared.num_points()];
172    prepared.finish(rejections, &std::collections::HashMap::new())
173}
174
175fn validate_sample_kind(table_name: &str, schema: &[ColumnSchema]) -> Result<()> {
176    let field_count = schema
177        .iter()
178        .filter(|column| column.semantic_type == SemanticType::Field as i32)
179        .count();
180    let has_native_histogram = schema.iter().any(|column| {
181        column.semantic_type == SemanticType::Field as i32
182            && api::helper::is_column_type_value_eq(
183                column.datatype,
184                column.datatype_extension.clone(),
185                native_histogram_value_type(),
186            )
187    });
188    if has_native_histogram && field_count != 1 {
189        return Err(error::InvalidParameterSnafu {
190            reason: format!(
191                "OTLP metric `{}` cannot mix native histogram and float sample fields",
192                table_name
193            ),
194        }
195        .build());
196    }
197    Ok(())
198}
199
200/// The tables a metric emits and their per-table `metric.type`. Histogram fans
201/// out into `_bucket` (the histogram) plus `_sum`/`_count` counters; summary
202/// fans out into the quantile table plus `_count`/`_sum` counters.
203fn emitted_semantic_tables(metric_type: &MetricType, base: &str) -> Vec<(String, &'static str)> {
204    match metric_type {
205        MetricType::Gauge => vec![(base.to_string(), METRIC_TYPE_GAUGE)],
206        MetricType::MonotonicSum => vec![(base.to_string(), METRIC_TYPE_COUNTER)],
207        MetricType::NonMonotonicSum => vec![(base.to_string(), METRIC_TYPE_UPDOWN_COUNTER)],
208        MetricType::Histogram => vec![
209            (
210                format!("{base}{BUCKET_TABLE_SUFFIX}"),
211                METRIC_TYPE_HISTOGRAM,
212            ),
213            (format!("{base}{SUM_TABLE_SUFFIX}"), METRIC_TYPE_COUNTER),
214            (format!("{base}{COUNT_TABLE_SUFFIX}"), METRIC_TYPE_COUNTER),
215        ],
216        MetricType::Summary => vec![
217            (base.to_string(), METRIC_TYPE_SUMMARY),
218            (format!("{base}{COUNT_TABLE_SUFFIX}"), METRIC_TYPE_COUNTER),
219            (format!("{base}{SUM_TABLE_SUFFIX}"), METRIC_TYPE_COUNTER),
220        ],
221        MetricType::ExponentialHistogram => {
222            vec![(base.to_string(), METRIC_TYPE_HISTOGRAM)]
223        }
224        MetricType::Init => vec![],
225    }
226}
227
228/// Maps OTLP `aggregation_temporality` to the semantic value, or `None` when the
229/// instrument has no temporality (gauge/summary) or it is unspecified.
230fn temporality_value(data: &metric::Data) -> Option<&'static str> {
231    let raw = match data {
232        metric::Data::Sum(sum) => sum.aggregation_temporality,
233        metric::Data::Histogram(hist) => hist.aggregation_temporality,
234        metric::Data::ExponentialHistogram(hist) => hist.aggregation_temporality,
235        _ => return None,
236    };
237    match AggregationTemporality::try_from(raw) {
238        Ok(AggregationTemporality::Delta) => Some(METRIC_TEMPORALITY_DELTA),
239        Ok(AggregationTemporality::Cumulative) => Some(METRIC_TEMPORALITY_CUMULATIVE),
240        _ => None,
241    }
242}
243
244/// Records the declared metric-level semantic keys for every table this metric
245/// emits.
246fn record_metric_semantics(
247    index: &mut SemanticIndex,
248    metric: &Metric,
249    name: &str,
250    emitted: &[(String, &str)],
251) {
252    if emitted.is_empty() {
253        return;
254    }
255
256    let temporality = metric.data.as_ref().and_then(temporality_value);
257    let unit = metric.unit.trim();
258    // `original_name` is meaningful only when translation renamed the metric.
259    let original_name = (name != metric.name.as_str()).then_some(metric.name.as_str());
260
261    for (table, metric_type) in emitted {
262        index.record_scalar(table, SEMANTIC_METRIC_TYPE, metric_type);
263        index.record_scalar(
264            table,
265            SEMANTIC_METRIC_METADATA_QUALITY,
266            METADATA_QUALITY_DECLARED,
267        );
268        if let Some(temporality) = temporality {
269            index.record_scalar(table, SEMANTIC_METRIC_TEMPORALITY, temporality);
270        }
271        if !unit.is_empty() {
272            index.record_scalar(table, SEMANTIC_METRIC_UNIT, unit);
273        }
274        if let Some(original_name) = original_name {
275            index.record_scalar(table, SEMANTIC_METRIC_ORIGINAL_NAME, original_name);
276        }
277    }
278}
279
280fn from_metric_type(data: &metric::Data) -> MetricType {
281    match data {
282        metric::Data::Gauge(_) => MetricType::Gauge,
283        metric::Data::Sum(s) => {
284            if s.is_monotonic {
285                MetricType::MonotonicSum
286            } else {
287                MetricType::NonMonotonicSum
288            }
289        }
290        metric::Data::Histogram(_) => MetricType::Histogram,
291        metric::Data::ExponentialHistogram(_) => MetricType::ExponentialHistogram,
292        metric::Data::Summary(_) => MetricType::Summary,
293    }
294}
295
296/// Non-scalar values (arrays, maps, bytes) are not representable as tags.
297fn scalar_value_string(value: Option<&AnyValue>) -> Option<String> {
298    match value.and_then(|v| v.value.as_ref())? {
299        any_value::Value::StringValue(s) => Some(s.clone()),
300        any_value::Value::IntValue(v) => Some(v.to_string()),
301        any_value::Value::DoubleValue(v) => Some(v.to_string()),
302        any_value::Value::BoolValue(v) => Some(v.to_string()),
303        _ => None,
304    }
305}
306
307/// Prometheus-style `(job, instance)` identity. Per the OTel Prometheus
308/// compatibility spec `job` folds in `service.namespace` when present; a
309/// resource without `service.name` gets no job rather than a fabricated one.
310/// Both fields are optional strings, so a named type keeps a swapped
311/// destructuring from type-checking at the call sites.
312pub(crate) struct ServiceIdentity {
313    pub job: Option<String>,
314    pub instance: Option<String>,
315}
316
317pub(crate) fn service_identity(attrs: &[KeyValue]) -> ServiceIdentity {
318    let mut name = None;
319    let mut namespace = None;
320    let mut instance = None;
321    for kv in attrs {
322        match kv.key.as_str() {
323            KEY_SERVICE_NAME => name = scalar_value_string(kv.value.as_ref()),
324            KEY_SERVICE_NAMESPACE => namespace = scalar_value_string(kv.value.as_ref()),
325            KEY_SERVICE_INSTANCE_ID => instance = scalar_value_string(kv.value.as_ref()),
326            _ => {}
327        }
328    }
329    let job = name.map(|name| match namespace {
330        Some(ns) if !ns.is_empty() => format!("{ns}/{name}"),
331        _ => name,
332    });
333    ServiceIdentity { job, instance }
334}
335
336fn string_key_value(key: &str, value: String) -> KeyValue {
337    KeyValue {
338        key: key.to_string(),
339        value: Some(AnyValue {
340            value: Some(any_value::Value::StringValue(value)),
341        }),
342    }
343}
344
345fn process_resource_attrs(attrs: &mut Vec<KeyValue>, metric_ctx: &OtlpMetricCtx) {
346    // remap the service identity attributes to job and instance
347    let ServiceIdentity { job, instance } = service_identity(attrs);
348
349    // if promote all, then exclude the list, else, include the list
350    if metric_ctx.promote_all_resource_attrs {
351        attrs.retain(|kv| !metric_ctx.resource_attrs.contains(&kv.key));
352    } else {
353        attrs.retain(|kv| {
354            metric_ctx.resource_attrs.contains(&kv.key)
355                || DEFAULT_PROMOTE_ATTRS_SET.contains(&kv.key)
356        });
357    }
358
359    if let Some(job) = job {
360        attrs.push(string_key_value(JOB_KEY, job));
361    }
362    if let Some(instance) = instance {
363        attrs.push(string_key_value(INSTANCE_KEY, instance));
364    }
365}
366
367fn process_scope_attrs(scope: &ScopeMetrics, metric_ctx: &OtlpMetricCtx) -> Option<Vec<KeyValue>> {
368    if !metric_ctx.promote_scope_attrs {
369        return None;
370    }
371
372    // persist scope attrs with name, version and schema_url
373    scope.scope.as_ref().map(|s| {
374        let mut attrs = s.attributes.clone();
375        attrs.push(KeyValue {
376            key: OTEL_SCOPE_NAME.to_string(),
377            value: Some(AnyValue {
378                value: Some(any_value::Value::StringValue(s.name.clone())),
379            }),
380        });
381        attrs.push(KeyValue {
382            key: OTEL_SCOPE_VERSION.to_string(),
383            value: Some(AnyValue {
384                value: Some(any_value::Value::StringValue(s.version.clone())),
385            }),
386        });
387        attrs.push(KeyValue {
388            key: OTEL_SCOPE_SCHEMA_URL.to_string(),
389            value: Some(AnyValue {
390                value: Some(any_value::Value::StringValue(scope.schema_url.clone())),
391            }),
392        });
393        attrs
394    })
395}
396
397#[allow(clippy::too_many_arguments)]
398fn encode_metrics(
399    table_writer: &mut MultiTableData,
400    metric: &Metric,
401    metadata: &MetricMetadata,
402    resource_attrs: Option<&Vec<KeyValue>>,
403    scope_attrs: Option<&Vec<KeyValue>>,
404    metric_ctx: &OtlpMetricCtx,
405    outcome: &mut MetricsIngestOutcome,
406    exemplars: &mut Vec<exemplars::RowExemplars>,
407) -> Result<()> {
408    let name = &metadata.name;
409
410    if let Some(data) = &metric.data {
411        match data {
412            metric::Data::Gauge(gauge) => {
413                encode_gauge(
414                    table_writer,
415                    name,
416                    gauge,
417                    resource_attrs,
418                    scope_attrs,
419                    metric_ctx,
420                    exemplars,
421                )?;
422                add_accepted_data_points(outcome, gauge.data_points.len())?;
423            }
424            metric::Data::Sum(sum) => {
425                encode_sum(
426                    table_writer,
427                    name,
428                    sum,
429                    resource_attrs,
430                    scope_attrs,
431                    metric_ctx,
432                    exemplars,
433                )?;
434                add_accepted_data_points(outcome, sum.data_points.len())?;
435            }
436            metric::Data::Summary(summary) => {
437                encode_summary(
438                    table_writer,
439                    name,
440                    summary,
441                    resource_attrs,
442                    scope_attrs,
443                    metric_ctx,
444                )?;
445                add_accepted_data_points(outcome, summary.data_points.len())?;
446            }
447            metric::Data::Histogram(hist) => encode_histogram(
448                table_writer,
449                name,
450                hist,
451                resource_attrs,
452                scope_attrs,
453                metric_ctx,
454                outcome,
455                exemplars,
456            )?,
457            metric::Data::ExponentialHistogram(hist) => encode_exponential_histogram(
458                table_writer,
459                metadata,
460                hist,
461                resource_attrs,
462                scope_attrs,
463                metric_ctx,
464                outcome,
465                exemplars,
466            )?,
467        }
468    }
469
470    Ok(())
471}
472
473fn add_accepted_data_points(outcome: &mut MetricsIngestOutcome, count: usize) -> Result<()> {
474    let count = i64::try_from(count).map_err(|_| {
475        error::InvalidParameterSnafu {
476            reason: "OTLP metrics data-point count exceeds i64",
477        }
478        .build()
479    })?;
480    outcome.accepted_data_points =
481        outcome
482            .accepted_data_points
483            .checked_add(count)
484            .ok_or_else(|| {
485                error::InvalidParameterSnafu {
486                    reason: "OTLP accepted data-point count overflows i64",
487                }
488                .build()
489            })?;
490    Ok(())
491}
492
493fn reject_data_points(
494    outcome: &mut MetricsIngestOutcome,
495    count: usize,
496    reason: impl FnOnce() -> String,
497) -> Result<()> {
498    if count == 0 {
499        return Ok(());
500    }
501    let count = i64::try_from(count).map_err(|_| {
502        error::InvalidParameterSnafu {
503            reason: "OTLP rejected data-point count exceeds i64",
504        }
505        .build()
506    })?;
507    outcome.rejected_data_points =
508        outcome
509            .rejected_data_points
510            .checked_add(count)
511            .ok_or_else(|| {
512                error::InvalidParameterSnafu {
513                    reason: "OTLP rejected data-point count overflows i64",
514                }
515                .build()
516            })?;
517    append_rejection_message(&mut outcome.error_message, reason);
518    Ok(())
519}
520
521fn append_rejection_message(message: &mut Option<String>, reason: impl FnOnce() -> String) {
522    let message = message.get_or_insert_with(String::new);
523    let separator = if message.is_empty() { "" } else { "; " };
524    let Some(available) = MAX_REJECTION_MESSAGE_BYTES.checked_sub(message.len()) else {
525        return;
526    };
527    if available <= separator.len() {
528        return;
529    }
530    let reason = reason();
531    message.push_str(separator);
532
533    let available = MAX_REJECTION_MESSAGE_BYTES - message.len();
534    if reason.len() <= available {
535        message.push_str(&reason);
536        return;
537    }
538
539    const ELLIPSIS: &str = "...";
540    let mut end = available.saturating_sub(ELLIPSIS.len());
541    while !reason.is_char_boundary(end) {
542        end -= 1;
543    }
544    message.push_str(&reason[..end]);
545    if available >= ELLIPSIS.len() {
546        message.push_str(ELLIPSIS);
547    }
548}
549
550#[allow(clippy::too_many_arguments)]
551fn encode_exponential_histogram(
552    table_writer: &mut MultiTableData,
553    metadata: &MetricMetadata,
554    histogram: &ExponentialHistogram,
555    resource_attrs: Option<&Vec<KeyValue>>,
556    scope_attrs: Option<&Vec<KeyValue>>,
557    metric_ctx: &OtlpMetricCtx,
558    outcome: &mut MetricsIngestOutcome,
559    exemplars: &mut Vec<exemplars::RowExemplars>,
560) -> Result<()> {
561    let name = &metadata.name;
562    let temporality = match exponential_histogram_gate(histogram) {
563        Ok(temporality) => temporality,
564        Err(rejection) => {
565            reject_data_points(outcome, histogram.data_points.len(), || {
566                rejection.message(name)
567            })?;
568            OTLP_EXPONENTIAL_HISTOGRAM_REJECTED_DATA_POINTS
569                .with_label_values(&[rejection.reason_label()])
570                .inc_by(histogram.data_points.len() as u64);
571            return Ok(());
572        }
573    };
574
575    let column_schema = metadata
576        .native_schema
577        .as_ref()
578        .context(error::InternalSnafu {
579            err_msg: "missing native histogram schema",
580        })?;
581    for data_point in &histogram.data_points {
582        let (value, timestamp_nanos) = match exponential_histogram_value(data_point, temporality) {
583            Ok(value) => value,
584            Err(reason) => {
585                reject_data_points(outcome, 1, || format!("metric `{name}`: {reason}"))?;
586                OTLP_EXPONENTIAL_HISTOGRAM_REJECTED_DATA_POINTS
587                    .with_label_values(&["invalid_data_point"])
588                    .inc();
589                continue;
590            }
591        };
592
593        let table = table_writer.get_or_default_table_data(
594            name,
595            APPROXIMATE_COLUMN_COUNT,
596            histogram.data_points.len(),
597        );
598        let mut row = table.alloc_one_row();
599        write_tags_and_timestamp(
600            table,
601            &mut row,
602            resource_attrs,
603            scope_attrs,
604            Some(data_point.attributes.as_ref()),
605            timestamp_nanos,
606            metric_ctx,
607        )?;
608        write_temporality_tag(
609            table,
610            &mut row,
611            temporality == AggregationTemporality::Delta,
612        )?;
613        row_writer::write_by_schema(
614            table,
615            std::iter::once((column_schema.clone(), Some(value))),
616            &mut row,
617        )?;
618        exemplars::append(
619            exemplars,
620            &data_point.exemplars,
621            name,
622            table.num_rows(),
623            metric_ctx,
624        );
625        table.add_row(row);
626        add_accepted_data_points(outcome, 1)?;
627    }
628
629    Ok(())
630}
631
632#[derive(Debug)]
633pub(crate) enum ExponentialHistogramRejection {
634    UnspecifiedTemporality,
635}
636
637impl ExponentialHistogramRejection {
638    fn reason_label(&self) -> &'static str {
639        match self {
640            Self::UnspecifiedTemporality => "unspecified_temporality",
641        }
642    }
643
644    fn message(&self, name: &str) -> String {
645        match self {
646            Self::UnspecifiedTemporality => format!(
647                "metric `{name}` has unspecified OTLP exponential histogram temporality; delta or cumulative temporality is required"
648            ),
649        }
650    }
651}
652
653/// Validate temporality before processing points; delta values remain raw intervals.
654pub(crate) fn exponential_histogram_gate(
655    histogram: &ExponentialHistogram,
656) -> std::result::Result<AggregationTemporality, ExponentialHistogramRejection> {
657    match AggregationTemporality::try_from(histogram.aggregation_temporality) {
658        Ok(temporality @ (AggregationTemporality::Cumulative | AggregationTemporality::Delta)) => {
659            Ok(temporality)
660        }
661        _ => Err(ExponentialHistogramRejection::UnspecifiedTemporality),
662    }
663}
664
665pub(crate) fn exponential_histogram_value(
666    data_point: &ExponentialHistogramDataPoint,
667    temporality: AggregationTemporality,
668) -> std::result::Result<(ValueData, i64), String> {
669    if data_point.start_time_unix_nano > data_point.time_unix_nano {
670        return Err(format!(
671            "start_time_unix_nano {} exceeds time_unix_nano {}",
672            data_point.start_time_unix_nano, data_point.time_unix_nano
673        ));
674    }
675
676    let timestamp_nanos = i64::try_from(data_point.time_unix_nano)
677        .map_err(|_| format!("time_unix_nano {} overflows i64", data_point.time_unix_nano))?;
678    let timestamp = timestamp_millis(data_point.time_unix_nano, "time_unix_nano")?;
679    let start_timestamp =
680        timestamp_millis(data_point.start_time_unix_nano, "start_time_unix_nano")?;
681
682    let reset_hint = if temporality == AggregationTemporality::Delta {
683        ResetHint::Gauge
684    } else {
685        ResetHint::Unspecified
686    } as i32;
687    let no_recorded_value = data_point.flags & DataPointFlags::NoRecordedValueMask as u32 != 0;
688    let histogram = if no_recorded_value {
689        PromHistogram {
690            sum: f64::from_bits(PROMETHEUS_STALE_NAN_BITS),
691            schema: 0,
692            zero_threshold: 0.0,
693            reset_hint,
694            timestamp,
695            start_timestamp,
696            count: Some(PromCount::CountInt(0)),
697            zero_count: Some(PromZeroCount::ZeroCountInt(0)),
698            ..Default::default()
699        }
700    } else {
701        if data_point.scale < MIN_EXPONENTIAL_HISTOGRAM_SCALE {
702            return Err(format!(
703                "scale {} is unsupported; minimum supported scale is {}",
704                data_point.scale, MIN_EXPONENTIAL_HISTOGRAM_SCALE
705            ));
706        }
707        if !data_point.zero_threshold.is_finite() || data_point.zero_threshold < 0.0 {
708            return Err(format!(
709                "zero_threshold {} must be finite and non-negative",
710                data_point.zero_threshold
711            ));
712        }
713
714        let downscale_shift = if data_point.scale > MAX_EXPONENTIAL_HISTOGRAM_SCALE {
715            let shift = data_point
716                .scale
717                .checked_sub(MAX_EXPONENTIAL_HISTOGRAM_SCALE)
718                .ok_or_else(|| "downscale shift overflows i32".to_string())?;
719            u32::try_from(shift).map_err(|_| "downscale shift exceeds u32".to_string())?
720        } else {
721            0
722        };
723        let (positive_spans, positive_deltas, positive_count) =
724            convert_bucket_range("positive", data_point.positive.as_ref(), downscale_shift)?;
725        let (negative_spans, negative_deltas, negative_count) =
726            convert_bucket_range("negative", data_point.negative.as_ref(), downscale_shift)?;
727        let bucket_count = data_point
728            .zero_count
729            .checked_add(positive_count)
730            .and_then(|count| count.checked_add(negative_count))
731            .ok_or_else(|| "bucket observation total overflows u64".to_string())?;
732        if bucket_count != data_point.count {
733            return Err(format!(
734                "buckets contain {bucket_count} observations, declared count is {}",
735                data_point.count
736            ));
737        }
738
739        i64::try_from(data_point.count)
740            .map_err(|_| format!("count {} overflows i64", data_point.count))?;
741        i64::try_from(data_point.zero_count)
742            .map_err(|_| format!("zero_count {} overflows i64", data_point.zero_count))?;
743
744        let sum = match data_point.sum {
745            Some(sum) if sum.is_nan() => f64::NAN,
746            Some(sum) => sum,
747            None => f64::NAN,
748        };
749        PromHistogram {
750            sum,
751            schema: data_point.scale.min(MAX_EXPONENTIAL_HISTOGRAM_SCALE),
752            zero_threshold: data_point.zero_threshold,
753            negative_spans,
754            negative_deltas,
755            positive_spans,
756            positive_deltas,
757            reset_hint,
758            timestamp,
759            start_timestamp,
760            count: Some(PromCount::CountInt(data_point.count)),
761            zero_count: Some(PromZeroCount::ZeroCountInt(data_point.zero_count)),
762            ..Default::default()
763        }
764    };
765
766    encode_native_histogram(&histogram)
767        .map(|value| (value, timestamp_nanos))
768        .map_err(|error| format!("OTLP exponential histogram cannot be encoded: {error}"))
769}
770
771fn timestamp_millis(timestamp_nanos: u64, name: &str) -> std::result::Result<i64, String> {
772    i64::try_from(timestamp_nanos / 1_000_000)
773        .map_err(|_| format!("{name} {timestamp_nanos} milliseconds overflow i64"))
774}
775
776fn convert_bucket_range(
777    name: &str,
778    buckets: Option<&exponential_histogram_data_point::Buckets>,
779    downscale_shift: u32,
780) -> std::result::Result<(Vec<BucketSpan>, Vec<i64>, u64), String> {
781    let Some(buckets) = buckets else {
782        return Ok((Vec::new(), Vec::new(), 0));
783    };
784    if buckets.bucket_counts.is_empty() {
785        return Ok((Vec::new(), Vec::new(), 0));
786    }
787
788    let mut merged = Vec::<(i32, u64)>::with_capacity(buckets.bucket_counts.len());
789    let mut total = 0u64;
790    for (position, count) in buckets.bucket_counts.iter().copied().enumerate() {
791        let position =
792            i32::try_from(position).map_err(|_| format!("{name} bucket length exceeds i32"))?;
793        let source_index = buckets.offset.checked_add(position).ok_or_else(|| {
794            format!(
795                "{name} bucket index overflows i32 at offset {} and position {position}",
796                buckets.offset
797            )
798        })?;
799        let target_index = downscale_bucket_index(source_index, downscale_shift)?
800            .checked_add(1)
801            .ok_or_else(|| format!("{name} shifted bucket index overflows i32"))?;
802        if let Some((last_index, last_count)) = merged.last_mut() {
803            if *last_index == target_index {
804                *last_count = last_count
805                    .checked_add(count)
806                    .ok_or_else(|| format!("{name} merged bucket count overflows u64"))?;
807                total = total
808                    .checked_add(count)
809                    .ok_or_else(|| format!("{name} bucket count total overflows u64"))?;
810                continue;
811            }
812            let next_index = last_index
813                .checked_add(1)
814                .ok_or_else(|| format!("{name} target bucket index overflows i32"))?;
815            if target_index != next_index {
816                return Err(format!(
817                    "{name} bucket indexes are not contiguous after downscaling"
818                ));
819            }
820        }
821        total = total
822            .checked_add(count)
823            .ok_or_else(|| format!("{name} bucket count total overflows u64"))?;
824        merged.push((target_index, count));
825    }
826
827    let mut spans = Vec::<BucketSpan>::new();
828    let mut deltas = Vec::with_capacity(merged.len());
829    let mut previous_index = None::<i32>;
830    let mut previous = 0i64;
831    for (index, count) in merged {
832        if count == 0 {
833            continue;
834        }
835        match (spans.last_mut(), previous_index) {
836            (Some(span), Some(prev_index)) if prev_index.checked_add(1) == Some(index) => {
837                span.length = span
838                    .length
839                    .checked_add(1)
840                    .ok_or_else(|| format!("{name} bucket span length exceeds u32"))?;
841            }
842            (_, prev_index) => {
843                let offset = match prev_index {
844                    Some(prev_index) => index
845                        .checked_sub(prev_index)
846                        .and_then(|gap| gap.checked_sub(1))
847                        .ok_or_else(|| format!("{name} bucket span offset overflows i32"))?,
848                    None => index,
849                };
850                spans.push(BucketSpan { offset, length: 1 });
851            }
852        }
853        let count = i64::try_from(count)
854            .map_err(|_| format!("{name} bucket count {count} overflows i64"))?;
855        let delta = count
856            .checked_sub(previous)
857            .ok_or_else(|| format!("{name} bucket delta overflows i64"))?;
858        deltas.push(delta);
859        previous_index = Some(index);
860        // Bucket deltas continue across span gaps; omitted zero buckets do not reset them.
861        previous = count;
862    }
863
864    Ok((spans, deltas, total))
865}
866
867fn downscale_bucket_index(index: i32, downscale_shift: u32) -> std::result::Result<i32, String> {
868    if downscale_shift == 0 {
869        return Ok(index);
870    }
871    if downscale_shift >= i32::BITS {
872        return Ok(if index < 0 { -1 } else { 0 });
873    }
874
875    let divisor = 1i64
876        .checked_shl(downscale_shift)
877        .ok_or_else(|| format!("downscale shift {downscale_shift} is invalid"))?;
878    i32::try_from(i64::from(index).div_euclid(divisor))
879        .map_err(|_| format!("downscaled bucket index {index} overflows i32"))
880}
881
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883enum AttributeType {
884    Resource,
885    Scope,
886    DataPoint,
887}
888
889fn write_attributes(
890    writer: &mut TableData,
891    row: &mut Vec<Value>,
892    attrs: Option<&Vec<KeyValue>>,
893    attribute_type: AttributeType,
894    metric_ctx: &OtlpMetricCtx,
895) -> Result<()> {
896    let Some(attrs) = attrs else {
897        return Ok(());
898    };
899
900    let mut tags = Vec::with_capacity(attrs.len());
901    for attr in attrs {
902        // TODO(sunng87): allow different type of values
903        let Some(value) = scalar_value_string(attr.value.as_ref()) else {
904            continue;
905        };
906        let key = match attribute_type {
907            AttributeType::Resource | AttributeType::DataPoint => {
908                translate_label_name(&attr.key, metric_ctx.metric_translation_strategy)
909            }
910            AttributeType::Scope => {
911                format!(
912                    "otel_scope_{}",
913                    translate_label_name(&attr.key, metric_ctx.metric_translation_strategy)
914                )
915            }
916        };
917        // OTLP attribute keys may include __name__, but Prometheus metric identity comes from
918        // the OTLP metric name. Reject collisions after translation and scope prefixing.
919        // https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#metric-metadata-1
920        if key == OTLP_AGGREGATION_TEMPORALITY_LABEL || key == crate::prom_store::METRIC_NAME_LABEL
921        {
922            return Err(error::InvalidOtlpMetricInputSnafu {
923                reason: format!(
924                    "OTLP attribute `{}` resolves to reserved label `{}`",
925                    attr.key, key
926                ),
927            }
928            .build());
929        }
930        tags.push((key, value));
931    }
932    row_writer::write_tags(writer, tags.into_iter(), row)?;
933
934    Ok(())
935}
936
937fn write_timestamp(
938    table: &mut TableData,
939    row: &mut Vec<Value>,
940    time_nano: i64,
941    metric_ctx: &OtlpMetricCtx,
942) -> Result<()> {
943    // Keep the full nanosecond precision whenever the request is headed for
944    // the metric engine: `Inserter::handle_metric_row_inserts` converts the
945    // timestamps to the physical table's time index unit (which may be
946    // micro/nanosecond). Only the non-metric prometheus-compatible path is
947    // fixed to milliseconds, to keep auto-created mito tables on the
948    // millisecond time index.
949    if metric_ctx.with_metric_engine {
950        row_writer::write_ts_to_nanos(
951            table,
952            greptime_timestamp(),
953            Some(time_nano),
954            Precision::Nanosecond,
955            row,
956        )
957    } else {
958        row_writer::write_ts_to_millis(
959            table,
960            greptime_timestamp(),
961            Some(time_nano / 1000000),
962            Precision::Millisecond,
963            row,
964        )
965    }
966}
967
968fn write_data_point_value(
969    table: &mut TableData,
970    row: &mut Vec<Value>,
971    field: &str,
972    value: &Option<number_data_point::Value>,
973) -> Result<()> {
974    match value {
975        Some(number_data_point::Value::AsInt(val)) => {
976            // we coerce all values to f64
977            row_writer::write_f64(table, field, *val as f64, row)?;
978        }
979        Some(number_data_point::Value::AsDouble(val)) => {
980            row_writer::write_f64(table, field, *val, row)?;
981        }
982        _ => {}
983    }
984    Ok(())
985}
986
987fn write_temporality_tag(
988    table: &mut TableData,
989    row: &mut Vec<Value>,
990    is_delta: bool,
991) -> Result<()> {
992    if is_delta {
993        row_writer::write_tag(
994            table,
995            OTLP_AGGREGATION_TEMPORALITY_LABEL,
996            GREPTIME_TEMPORALITY_DELTA,
997            row,
998        )?;
999    }
1000    Ok(())
1001}
1002
1003fn has_no_recorded_value(flags: u32) -> bool {
1004    flags & DataPointFlags::NoRecordedValueMask as u32 != 0
1005}
1006
1007fn write_tags_and_timestamp(
1008    table: &mut TableData,
1009    row: &mut Vec<Value>,
1010    resource_attrs: Option<&Vec<KeyValue>>,
1011    scope_attrs: Option<&Vec<KeyValue>>,
1012    data_point_attrs: Option<&Vec<KeyValue>>,
1013    timestamp_nanos: i64,
1014    metric_ctx: &OtlpMetricCtx,
1015) -> Result<()> {
1016    // TODO(shuiyisong): check `__type__` and `__unit__` tags in prometheus
1017    write_attributes(
1018        table,
1019        row,
1020        resource_attrs,
1021        AttributeType::Resource,
1022        metric_ctx,
1023    )?;
1024    write_attributes(table, row, scope_attrs, AttributeType::Scope, metric_ctx)?;
1025    write_attributes(
1026        table,
1027        row,
1028        data_point_attrs,
1029        AttributeType::DataPoint,
1030        metric_ctx,
1031    )?;
1032
1033    write_timestamp(table, row, timestamp_nanos, metric_ctx)?;
1034
1035    Ok(())
1036}
1037
1038/// encode this gauge metric
1039///
1040/// note that there can be multiple data points in the request, it's going to be
1041/// stored as multiple rows
1042fn encode_gauge(
1043    table_writer: &mut MultiTableData,
1044    name: &str,
1045    gauge: &Gauge,
1046    resource_attrs: Option<&Vec<KeyValue>>,
1047    scope_attrs: Option<&Vec<KeyValue>>,
1048    metric_ctx: &OtlpMetricCtx,
1049    exemplars: &mut Vec<exemplars::RowExemplars>,
1050) -> Result<()> {
1051    let table = table_writer.get_or_default_table_data(
1052        name,
1053        APPROXIMATE_COLUMN_COUNT,
1054        gauge.data_points.len(),
1055    );
1056
1057    for data_point in &gauge.data_points {
1058        let mut row = table.alloc_one_row();
1059        write_tags_and_timestamp(
1060            table,
1061            &mut row,
1062            resource_attrs,
1063            scope_attrs,
1064            Some(data_point.attributes.as_ref()),
1065            data_point.time_unix_nano as i64,
1066            metric_ctx,
1067        )?;
1068
1069        write_data_point_value(table, &mut row, greptime_value(), &data_point.value)?;
1070        exemplars::append(
1071            exemplars,
1072            &data_point.exemplars,
1073            name,
1074            table.num_rows(),
1075            metric_ctx,
1076        );
1077        table.add_row(row);
1078    }
1079
1080    Ok(())
1081}
1082
1083/// Encodes sums, preserving delta points as interval values with a temporality tag.
1084/// Ingestion is stateless: values are never accumulated across timestamps.
1085fn encode_sum(
1086    table_writer: &mut MultiTableData,
1087    name: &str,
1088    sum: &Sum,
1089    resource_attrs: Option<&Vec<KeyValue>>,
1090    scope_attrs: Option<&Vec<KeyValue>>,
1091    metric_ctx: &OtlpMetricCtx,
1092    exemplars: &mut Vec<exemplars::RowExemplars>,
1093) -> Result<()> {
1094    let is_delta = matches!(
1095        AggregationTemporality::try_from(sum.aggregation_temporality),
1096        Ok(AggregationTemporality::Delta)
1097    );
1098    let table = table_writer.get_or_default_table_data(
1099        name,
1100        APPROXIMATE_COLUMN_COUNT,
1101        sum.data_points.len(),
1102    );
1103
1104    for data_point in &sum.data_points {
1105        let mut row = table.alloc_one_row();
1106        write_tags_and_timestamp(
1107            table,
1108            &mut row,
1109            resource_attrs,
1110            scope_attrs,
1111            Some(data_point.attributes.as_ref()),
1112            data_point.time_unix_nano as i64,
1113            metric_ctx,
1114        )?;
1115        write_temporality_tag(table, &mut row, is_delta)?;
1116        if has_no_recorded_value(data_point.flags) {
1117            row_writer::write_f64(
1118                table,
1119                greptime_value(),
1120                f64::from_bits(PROMETHEUS_STALE_NAN_BITS),
1121                &mut row,
1122            )?;
1123        } else {
1124            write_data_point_value(table, &mut row, greptime_value(), &data_point.value)?;
1125        }
1126        exemplars::append(
1127            exemplars,
1128            &data_point.exemplars,
1129            name,
1130            table.num_rows(),
1131            metric_ctx,
1132        );
1133        table.add_row(row);
1134    }
1135
1136    Ok(())
1137}
1138
1139const HISTOGRAM_LE_COLUMN: &str = "le";
1140
1141/// Encode histogram data. This function returns 3 insert requests for 3 tables.
1142///
1143/// The implementation has been following Prometheus histogram table format:
1144///
1145/// - A `%metric%_bucket` table including `greptime_le` tag that stores bucket upper
1146///   limit, and `greptime_value` for bucket count
1147/// - A `%metric%_sum` table storing sum of samples
1148/// -  A `%metric%_count` table storing count of samples.
1149///
1150/// By its Prometheus compatibility, we hope to be able to use prometheus
1151/// quantile functions on this table.
1152/// Delta points retain their temporality tag and interval values. Bucket counts
1153/// are prefix-summed within each point, never accumulated across timestamps.
1154#[allow(clippy::too_many_arguments)]
1155fn encode_histogram(
1156    table_writer: &mut MultiTableData,
1157    name: &str,
1158    hist: &Histogram,
1159    resource_attrs: Option<&Vec<KeyValue>>,
1160    scope_attrs: Option<&Vec<KeyValue>>,
1161    metric_ctx: &OtlpMetricCtx,
1162    outcome: &mut MetricsIngestOutcome,
1163    exemplars: &mut Vec<exemplars::RowExemplars>,
1164) -> Result<()> {
1165    let normalized_name = name;
1166
1167    let bucket_table_name = format!("{}{}", normalized_name, BUCKET_TABLE_SUFFIX);
1168    let sum_table_name = format!("{}{}", normalized_name, SUM_TABLE_SUFFIX);
1169    let count_table_name = format!("{}{}", normalized_name, COUNT_TABLE_SUFFIX);
1170
1171    let is_delta = matches!(
1172        AggregationTemporality::try_from(hist.aggregation_temporality),
1173        Ok(AggregationTemporality::Delta)
1174    );
1175    let stale_value = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
1176    for data_point in &hist.data_points {
1177        if let Some(reason) = histogram_data_point_rejection(data_point) {
1178            reject_data_points(outcome, 1, || format!("metric `{name}`: {reason}"))?;
1179            continue;
1180        }
1181
1182        let bucket_table =
1183            table_writer.get_or_default_table_data(&bucket_table_name, APPROXIMATE_COLUMN_COUNT, 0);
1184        let no_recorded_value = has_no_recorded_value(data_point.flags);
1185        if no_recorded_value {
1186            bucket_table.reserve_rows(data_point.explicit_bounds.len());
1187            bucket_table.reserve_rows(1);
1188        } else {
1189            bucket_table.reserve_rows(data_point.bucket_counts.len().max(1));
1190        }
1191        let bucket_values = if no_recorded_value {
1192            data_point
1193                .explicit_bounds
1194                .iter()
1195                .copied()
1196                .chain(std::iter::once(f64::INFINITY))
1197                .map(|bound| (bound, stale_value))
1198                .collect::<Vec<_>>()
1199        } else if data_point.bucket_counts.is_empty() && data_point.explicit_bounds.is_empty() {
1200            // OTLP count-only histograms map to one implicit Prometheus infinity bucket.
1201            vec![(f64::INFINITY, data_point.count as f64)]
1202        } else {
1203            let mut accumulated_count = 0u64;
1204            let mut values = Vec::with_capacity(data_point.bucket_counts.len());
1205            for (bound, count) in data_point
1206                .explicit_bounds
1207                .iter()
1208                .copied()
1209                .chain(std::iter::once(f64::INFINITY))
1210                .zip(&data_point.bucket_counts)
1211            {
1212                accumulated_count += *count;
1213                values.push((bound, accumulated_count as f64));
1214            }
1215            values
1216        };
1217        let mut by_bucket = vec![Vec::new(); bucket_values.len()];
1218        for exemplar in &data_point.exemplars {
1219            let value = match exemplars::value(exemplar) {
1220                Ok(value) => value,
1221                Err(_) => {
1222                    crate::metrics::EXEMPLARS_DROPPED_TOTAL
1223                        .with_label_values(&["otlp"])
1224                        .inc();
1225                    continue;
1226                }
1227            };
1228            let Some(bucket) = bucket_values.iter().position(|(bound, _)| {
1229                value <= *bound || (value.is_nan() && *bound == f64::INFINITY)
1230            }) else {
1231                crate::metrics::EXEMPLARS_DROPPED_TOTAL
1232                    .with_label_values(&["otlp"])
1233                    .inc();
1234                continue;
1235            };
1236            by_bucket[bucket].push(exemplar);
1237        }
1238        for ((bound, value), bucket_exemplars) in bucket_values.into_iter().zip(by_bucket) {
1239            let mut bucket_row = bucket_table.alloc_one_row();
1240            write_tags_and_timestamp(
1241                bucket_table,
1242                &mut bucket_row,
1243                resource_attrs,
1244                scope_attrs,
1245                Some(data_point.attributes.as_ref()),
1246                data_point.time_unix_nano as i64,
1247                metric_ctx,
1248            )?;
1249            write_temporality_tag(bucket_table, &mut bucket_row, is_delta)?;
1250            // Preserve existing OTLP series identities, including the "inf" bucket.
1251            row_writer::write_tag(bucket_table, HISTOGRAM_LE_COLUMN, bound, &mut bucket_row)?;
1252            row_writer::write_f64(bucket_table, greptime_value(), value, &mut bucket_row)?;
1253
1254            exemplars::append(
1255                exemplars,
1256                bucket_exemplars,
1257                &bucket_table_name,
1258                bucket_table.num_rows(),
1259                metric_ctx,
1260            );
1261            bucket_table.add_row(bucket_row);
1262        }
1263
1264        if let Some(sum) = data_point.sum {
1265            let sum_table = table_writer.get_or_default_table_data(
1266                &sum_table_name,
1267                APPROXIMATE_COLUMN_COUNT,
1268                hist.data_points.len(),
1269            );
1270            let mut sum_row = sum_table.alloc_one_row();
1271            write_tags_and_timestamp(
1272                sum_table,
1273                &mut sum_row,
1274                resource_attrs,
1275                scope_attrs,
1276                Some(data_point.attributes.as_ref()),
1277                data_point.time_unix_nano as i64,
1278                metric_ctx,
1279            )?;
1280            write_temporality_tag(sum_table, &mut sum_row, is_delta)?;
1281            row_writer::write_f64(
1282                sum_table,
1283                greptime_value(),
1284                if no_recorded_value { stale_value } else { sum },
1285                &mut sum_row,
1286            )?;
1287            sum_table.add_row(sum_row);
1288        }
1289
1290        let count_table = table_writer.get_or_default_table_data(
1291            &count_table_name,
1292            APPROXIMATE_COLUMN_COUNT,
1293            hist.data_points.len(),
1294        );
1295        let mut count_row = count_table.alloc_one_row();
1296        write_tags_and_timestamp(
1297            count_table,
1298            &mut count_row,
1299            resource_attrs,
1300            scope_attrs,
1301            Some(data_point.attributes.as_ref()),
1302            data_point.time_unix_nano as i64,
1303            metric_ctx,
1304        )?;
1305        write_temporality_tag(count_table, &mut count_row, is_delta)?;
1306        row_writer::write_f64(
1307            count_table,
1308            greptime_value(),
1309            if no_recorded_value {
1310                stale_value
1311            } else {
1312                data_point.count as f64
1313            },
1314            &mut count_row,
1315        )?;
1316        count_table.add_row(count_row);
1317        add_accepted_data_points(outcome, 1)?;
1318    }
1319
1320    Ok(())
1321}
1322
1323pub(crate) fn histogram_data_point_rejection(data_point: &HistogramDataPoint) -> Option<String> {
1324    if has_no_recorded_value(data_point.flags) {
1325        return None;
1326    }
1327
1328    let valid_empty_layout =
1329        data_point.bucket_counts.is_empty() && data_point.explicit_bounds.is_empty();
1330    let expected_buckets = data_point.explicit_bounds.len().checked_add(1);
1331    if !valid_empty_layout && expected_buckets != Some(data_point.bucket_counts.len()) {
1332        return Some(format!(
1333            "bucket_counts length {} must equal explicit_bounds length {} plus one",
1334            data_point.bucket_counts.len(),
1335            data_point.explicit_bounds.len()
1336        ));
1337    }
1338    // OTLP requires strictly increasing explicit_bounds; GreptimeDB also requires finite
1339    // bounds so an explicit +Inf cannot duplicate the le="inf" bucket appended above.
1340    if data_point
1341        .explicit_bounds
1342        .iter()
1343        .any(|bound| !bound.is_finite())
1344        || data_point
1345            .explicit_bounds
1346            .windows(2)
1347            .any(|bounds| bounds[0] >= bounds[1])
1348    {
1349        return Some("explicit_bounds must be finite and strictly increasing".to_string());
1350    }
1351    if data_point.count == 0 && data_point.sum.is_some_and(|sum| sum != 0.0) {
1352        return Some("sum must be absent or zero when count is zero".to_string());
1353    }
1354
1355    let bucket_total = data_point
1356        .bucket_counts
1357        .iter()
1358        .try_fold(0u64, |total, count| total.checked_add(*count));
1359    let Some(bucket_total) = bucket_total else {
1360        return Some("bucket prefix overflows u64".to_string());
1361    };
1362    if !data_point.bucket_counts.is_empty() && bucket_total != data_point.count {
1363        return Some(format!(
1364            "buckets contain {bucket_total} observations, declared count is {}",
1365            data_point.count
1366        ));
1367    }
1368
1369    None
1370}
1371
1372fn encode_summary(
1373    table_writer: &mut MultiTableData,
1374    name: &str,
1375    summary: &Summary,
1376    resource_attrs: Option<&Vec<KeyValue>>,
1377    scope_attrs: Option<&Vec<KeyValue>>,
1378    metric_ctx: &OtlpMetricCtx,
1379) -> Result<()> {
1380    // 1. quantile table
1381    // 2. count table
1382    // 3. sum table
1383
1384    let metric_name = name;
1385    let count_name = format!("{}{}", metric_name, COUNT_TABLE_SUFFIX);
1386    let sum_name = format!("{}{}", metric_name, SUM_TABLE_SUFFIX);
1387
1388    for data_point in &summary.data_points {
1389        {
1390            let quantile_table = table_writer.get_or_default_table_data(
1391                metric_name,
1392                APPROXIMATE_COLUMN_COUNT,
1393                summary.data_points.len(),
1394            );
1395
1396            for quantile in &data_point.quantile_values {
1397                let mut row = quantile_table.alloc_one_row();
1398                write_tags_and_timestamp(
1399                    quantile_table,
1400                    &mut row,
1401                    resource_attrs,
1402                    scope_attrs,
1403                    Some(data_point.attributes.as_ref()),
1404                    data_point.time_unix_nano as i64,
1405                    metric_ctx,
1406                )?;
1407                row_writer::write_tag(quantile_table, "quantile", quantile.quantile, &mut row)?;
1408                row_writer::write_f64(quantile_table, greptime_value(), quantile.value, &mut row)?;
1409                quantile_table.add_row(row);
1410            }
1411        }
1412        {
1413            let count_table = table_writer.get_or_default_table_data(
1414                &count_name,
1415                APPROXIMATE_COLUMN_COUNT,
1416                summary.data_points.len(),
1417            );
1418            let mut row = count_table.alloc_one_row();
1419            write_tags_and_timestamp(
1420                count_table,
1421                &mut row,
1422                resource_attrs,
1423                scope_attrs,
1424                Some(data_point.attributes.as_ref()),
1425                data_point.time_unix_nano as i64,
1426                metric_ctx,
1427            )?;
1428
1429            row_writer::write_f64(
1430                count_table,
1431                greptime_value(),
1432                data_point.count as f64,
1433                &mut row,
1434            )?;
1435
1436            count_table.add_row(row);
1437        }
1438        {
1439            let sum_table = table_writer.get_or_default_table_data(
1440                &sum_name,
1441                APPROXIMATE_COLUMN_COUNT,
1442                summary.data_points.len(),
1443            );
1444
1445            let mut row = sum_table.alloc_one_row();
1446            write_tags_and_timestamp(
1447                sum_table,
1448                &mut row,
1449                resource_attrs,
1450                scope_attrs,
1451                Some(data_point.attributes.as_ref()),
1452                data_point.time_unix_nano as i64,
1453                metric_ctx,
1454            )?;
1455
1456            row_writer::write_f64(sum_table, greptime_value(), data_point.sum, &mut row)?;
1457
1458            sum_table.add_row(row);
1459        }
1460    }
1461
1462    Ok(())
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use api::v1::ColumnDataType;
1468    use common_query::prelude::set_default_prefix;
1469    use otel_arrow_rust::proto::opentelemetry::common::v1::any_value::Value as Val;
1470    use otel_arrow_rust::proto::opentelemetry::common::v1::{AnyValue, InstrumentationScope};
1471    use otel_arrow_rust::proto::opentelemetry::metrics::v1::number_data_point::Value;
1472    use otel_arrow_rust::proto::opentelemetry::metrics::v1::summary_data_point::ValueAtQuantile;
1473    use otel_arrow_rust::proto::opentelemetry::metrics::v1::{
1474        AggregationTemporality, HistogramDataPoint, NumberDataPoint, SummaryDataPoint,
1475    };
1476    use otel_arrow_rust::proto::opentelemetry::resource::v1::Resource;
1477    use session::protocol_ctx::OtlpMetricTranslationStrategy;
1478
1479    use super::*;
1480
1481    mod delta;
1482
1483    fn keyvalue(key: &str, value: &str) -> KeyValue {
1484        KeyValue {
1485            key: key.into(),
1486            value: Some(AnyValue {
1487                value: Some(Val::StringValue(value.into())),
1488            }),
1489        }
1490    }
1491
1492    fn bool_keyvalue(key: &str, value: bool) -> KeyValue {
1493        KeyValue {
1494            key: key.into(),
1495            value: Some(AnyValue {
1496                value: Some(Val::BoolValue(value)),
1497            }),
1498        }
1499    }
1500
1501    fn descriptor_ctx() -> OtlpMetricCtx {
1502        OtlpMetricCtx {
1503            resource_info: true,
1504            ..Default::default()
1505        }
1506    }
1507
1508    fn attr_value(attrs: &[KeyValue], key: &str) -> Option<String> {
1509        attrs
1510            .iter()
1511            .find(|kv| kv.key == key)
1512            .and_then(|kv| scalar_value_string(kv.value.as_ref()))
1513    }
1514
1515    fn gauge_request(
1516        resource_attrs: Vec<KeyValue>,
1517        metric_name: &str,
1518    ) -> ExportMetricsServiceRequest {
1519        use otel_arrow_rust::proto::opentelemetry::resource::v1::Resource;
1520        ExportMetricsServiceRequest {
1521            resource_metrics: vec![ResourceMetrics {
1522                resource: Some(Resource {
1523                    attributes: resource_attrs,
1524                    ..Default::default()
1525                }),
1526                scope_metrics: vec![ScopeMetrics {
1527                    metrics: vec![Metric {
1528                        name: metric_name.to_string(),
1529                        data: Some(metric::Data::Gauge(Gauge {
1530                            data_points: vec![NumberDataPoint {
1531                                time_unix_nano: 1_000_000,
1532                                value: Some(Value::AsInt(1)),
1533                                ..Default::default()
1534                            }],
1535                        })),
1536                        ..Default::default()
1537                    }],
1538                    ..Default::default()
1539                }],
1540                ..Default::default()
1541            }],
1542        }
1543    }
1544
1545    fn column_names(request: &RowInsertRequests, table: &str) -> Vec<String> {
1546        request
1547            .inserts
1548            .iter()
1549            .find(|r| r.table_name == table)
1550            .unwrap_or_else(|| panic!("missing table {table}"))
1551            .rows
1552            .as_ref()
1553            .unwrap()
1554            .schema
1555            .iter()
1556            .map(|c| c.column_name.clone())
1557            .collect()
1558    }
1559
1560    #[test]
1561    fn test_conversion_synthesizes_resource_descriptor() {
1562        set_default_prefix(None).unwrap();
1563        let request = gauge_request(
1564            vec![keyvalue("service.name", "api"), keyvalue("host.id", "h-1")],
1565            "my_gauge",
1566        );
1567        let conversion = to_grpc_insert_requests(request, &mut descriptor_ctx()).unwrap();
1568
1569        // descriptor keeps raw OTel keys while the metric table's labels went
1570        // through the (default underscore-escaping) translation strategy
1571        let resource_info = conversion.resource_info.expect("descriptor synthesized");
1572        let descriptor_cols = column_names(&resource_info, OTEL_RESOURCE_INFO_TABLE_NAME);
1573        assert!(descriptor_cols.contains(&"host.id".to_string()));
1574        assert!(descriptor_cols.contains(&"service.name".to_string()));
1575        assert!(descriptor_cols.contains(&"job".to_string()));
1576        let metric_cols = column_names(&conversion.requests, "my_gauge");
1577        assert!(metric_cols.contains(&"service_name".to_string()));
1578        assert!(!metric_cols.contains(&"service.name".to_string()));
1579        // host.id is not in the promote list: only the descriptor keeps it
1580        assert!(!metric_cols.contains(&"host_id".to_string()));
1581
1582        let decoded = decode(&conversion.semantic_index);
1583        let t = &decoded[OTEL_RESOURCE_INFO_TABLE_NAME];
1584        assert_eq!(
1585            t.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
1586            Some("info")
1587        );
1588        assert_eq!(
1589            t.get(SEMANTIC_METRIC_METADATA_QUALITY).map(String::as_str),
1590            Some("declared")
1591        );
1592    }
1593
1594    #[test]
1595    fn test_descriptors_and_exemplars_exclude_points_rejected_by_destination_preflight() {
1596        let mut request = gauge_request(vec![keyvalue("service.name", "api")], "accepted");
1597        let Some(metric::Data::Gauge(gauge)) = request.resource_metrics[0].scope_metrics[0].metrics
1598            [0]
1599        .data
1600        .as_mut() else {
1601            unreachable!()
1602        };
1603        gauge.data_points[0].exemplars.push(Exemplar {
1604            time_unix_nano: 1,
1605            value: Some(exemplar::Value::AsDouble(0.5)),
1606            ..Default::default()
1607        });
1608        let mut rejected = request.resource_metrics[0].clone();
1609        let metric = &mut rejected.scope_metrics[0].metrics[0];
1610        metric.name = "rejected".into();
1611        let Some(metric::Data::Gauge(gauge)) = metric.data.as_mut() else {
1612            unreachable!()
1613        };
1614        gauge.data_points[0].time_unix_nano =
1615            2 * common_catalog::consts::SEMANTIC_GRAPH_WINDOW_NANOS as u64;
1616        request.resource_metrics.push(rejected);
1617        let mut prepared = prepare_metrics(
1618            request,
1619            &mut OtlpMetricCtx {
1620                with_metric_engine: true,
1621                ..descriptor_ctx()
1622            },
1623        )
1624        .unwrap();
1625        for request in &mut prepared.requests {
1626            let rows = request.rows.as_mut().unwrap();
1627            rows.schema.push(ColumnSchema {
1628                column_name: "defaulted_host".into(),
1629                datatype: api::v1::ColumnDataType::String as i32,
1630                semantic_type: SemanticType::Tag as i32,
1631                ..Default::default()
1632            });
1633            for row in &mut rows.rows {
1634                row.values.push(api::v1::Value {
1635                    value_data: Some(ValueData::StringValue("unknown".into())),
1636                });
1637            }
1638        }
1639        let conversion = prepared
1640            .finish(
1641                vec![None, Some("incompatible schema".into())],
1642                &Default::default(),
1643            )
1644            .unwrap();
1645        assert_eq!(
1646            (
1647                conversion.outcome.accepted_data_points,
1648                conversion.outcome.rejected_data_points
1649            ),
1650            (1, 1)
1651        );
1652        assert_eq!(conversion.exemplars.len(), 1);
1653        assert_eq!(
1654            conversion.exemplars[0].series_labels["defaulted_host"],
1655            "unknown"
1656        );
1657        let exemplars = crate::exemplar::ExemplarBatch::try_new(conversion.exemplars).unwrap();
1658        assert_eq!(exemplars.exemplars()[0].metric.as_ref(), "accepted");
1659        let descriptors = conversion.resource_info.unwrap();
1660        let rows = descriptors.inserts[0].rows.as_ref().unwrap();
1661        assert_eq!(rows.rows.len(), 1);
1662        let timestamp = rows
1663            .schema
1664            .iter()
1665            .position(|c| c.column_name == greptime_timestamp())
1666            .unwrap();
1667        assert_eq!(
1668            rows.rows[0].values[timestamp].value_data,
1669            Some(ValueData::TimestampMillisecondValue(1))
1670        );
1671    }
1672
1673    #[test]
1674    fn test_finish_rejects_mismatched_point_counts() {
1675        for (requests, rejections) in [(0, 1), (2, 1), (1, 0), (1, 2)] {
1676            let mut prepared = prepare_metrics(
1677                gauge_request(vec![], "gauge"),
1678                &mut OtlpMetricCtx::default(),
1679            )
1680            .unwrap();
1681            prepared.requests.resize(requests, Default::default());
1682            let err = prepared
1683                .finish(vec![None; rejections], &Default::default())
1684                .unwrap_err();
1685            assert!(matches!(err, error::Error::Internal { .. }));
1686        }
1687    }
1688
1689    #[test]
1690    fn test_conversion_describes_only_accepted_exponential_histogram_windows() {
1691        set_default_prefix(None).unwrap();
1692        let window = common_catalog::consts::SEMANTIC_GRAPH_WINDOW_NANOS as u64;
1693        let mut valid = exponential_point();
1694        valid.time_unix_nano = window + 1_000_000;
1695
1696        let mut invalid_count = valid.clone();
1697        invalid_count.time_unix_nano += 8_000_000;
1698        invalid_count.count += 1;
1699        let mut invalid_scale = valid.clone();
1700        invalid_scale.time_unix_nano += window;
1701        invalid_scale.scale = -5;
1702        // OTLP bucket conversion succeeds, but the shared native encoder rejects this index.
1703        let invalid_native = ExponentialHistogramDataPoint {
1704            time_unix_nano: 3 * window + 1_000_000,
1705            count: 1,
1706            positive: Some(exponential_buckets(2000, vec![1])),
1707            ..Default::default()
1708        };
1709        assert!(
1710            exponential_histogram_value(&invalid_native, AggregationTemporality::Cumulative)
1711                .unwrap_err()
1712                .contains("out of range")
1713        );
1714        let stale = ExponentialHistogramDataPoint {
1715            time_unix_nano: 4 * window + 1_000_000,
1716            count: u64::MAX,
1717            scale: i32::MIN,
1718            flags: DataPointFlags::NoRecordedValueMask as u32,
1719            ..Default::default()
1720        };
1721        let invalid_time = ExponentialHistogramDataPoint {
1722            time_unix_nano: 5 * window + 1_000_000,
1723            start_time_unix_nano: 5 * window + 2_000_000,
1724            ..stale.clone()
1725        };
1726        let rejected = vec![invalid_count, invalid_scale, invalid_native, invalid_time];
1727        let mut mixed = rejected.clone();
1728        mixed.extend([valid, stale]);
1729        for (points, expected) in [
1730            (rejected, vec![]),
1731            (
1732                mixed,
1733                vec![
1734                    (window / 1_000_000 + 1) as i64,
1735                    (4 * window / 1_000_000 + 1) as i64,
1736                ],
1737            ),
1738        ] {
1739            let mut request = metrics_request(vec![exponential_metric(
1740                "latency",
1741                points,
1742                AggregationTemporality::Cumulative,
1743            )]);
1744            request.resource_metrics[0].resource = Some(Resource {
1745                attributes: vec![keyvalue("service.name", "api")],
1746                ..Default::default()
1747            });
1748            let conversion = to_grpc_insert_requests(request, &mut descriptor_ctx()).unwrap();
1749            assert_eq!(conversion.outcome.rejected_data_points, 4);
1750            assert_eq!(
1751                conversion.outcome.accepted_data_points,
1752                expected.len() as i64
1753            );
1754            assert_eq!(conversion.rows, expected.len());
1755            assert_eq!(conversion.resource_info.is_some(), !expected.is_empty());
1756            let actual = conversion
1757                .resource_info
1758                .map(|descriptor| {
1759                    let rows = descriptor.inserts[0].rows.as_ref().unwrap();
1760                    let ts_index = rows
1761                        .schema
1762                        .iter()
1763                        .position(|column| column.column_name == greptime_timestamp())
1764                        .unwrap();
1765                    rows.rows
1766                        .iter()
1767                        .map(|row| match row.values[ts_index].value_data {
1768                            Some(ValueData::TimestampMillisecondValue(ts)) => ts,
1769                            _ => panic!("expected descriptor timestamp"),
1770                        })
1771                        .collect::<Vec<_>>()
1772                })
1773                .unwrap_or_default();
1774            assert_eq!(actual, expected);
1775        }
1776    }
1777
1778    #[test]
1779    fn test_conversion_skips_descriptor_on_metric_name_collision() {
1780        set_default_prefix(None).unwrap();
1781        for (enabled, attributes, warns) in [
1782            (true, vec![keyvalue("service.name", "api")], true),
1783            (false, vec![keyvalue("service.name", "api")], false),
1784            (true, vec![keyvalue("unprojected", "value")], false),
1785        ] {
1786            let logs = tempfile::NamedTempFile::new().unwrap();
1787            let writer = logs.reopen().unwrap();
1788            let subscriber = common_telemetry::tracing_subscriber::fmt()
1789                .without_time()
1790                .with_ansi(false)
1791                .with_writer(move || writer.try_clone().unwrap())
1792                .finish();
1793            let conversion = tracing::subscriber::with_default(subscriber, || {
1794                let mut ctx = descriptor_ctx();
1795                ctx.resource_info = enabled;
1796                to_grpc_insert_requests(
1797                    gauge_request(attributes, OTEL_RESOURCE_INFO_TABLE_NAME),
1798                    &mut ctx,
1799                )
1800                .unwrap()
1801            });
1802            let diagnostics = std::fs::read_to_string(logs.path()).unwrap();
1803            assert_eq!(
1804                diagnostics.contains("Skipping OTLP resource descriptor"),
1805                warns
1806            );
1807            assert!(conversion.resource_info.is_none());
1808            assert!(
1809                conversion
1810                    .requests
1811                    .inserts
1812                    .iter()
1813                    .any(|r| r.table_name == OTEL_RESOURCE_INFO_TABLE_NAME)
1814            );
1815        }
1816    }
1817
1818    #[test]
1819    fn test_job_composition_follows_service_namespace() {
1820        let mut attrs = vec![
1821            keyvalue("service.name", "api"),
1822            keyvalue("service.namespace", "shop"),
1823        ];
1824        process_resource_attrs(&mut attrs, &OtlpMetricCtx::default());
1825        assert_eq!(attr_value(&attrs, "job").as_deref(), Some("shop/api"));
1826
1827        let mut attrs = vec![keyvalue("service.name", "api")];
1828        process_resource_attrs(&mut attrs, &OtlpMetricCtx::default());
1829        assert_eq!(attr_value(&attrs, "job").as_deref(), Some("api"));
1830
1831        let mut attrs = vec![
1832            keyvalue("service.name", "api"),
1833            keyvalue("service.namespace", ""),
1834        ];
1835        process_resource_attrs(&mut attrs, &OtlpMetricCtx::default());
1836        assert_eq!(attr_value(&attrs, "job").as_deref(), Some("api"));
1837
1838        // no service.name: no job is fabricated
1839        let mut attrs = vec![
1840            keyvalue("service.namespace", "shop"),
1841            keyvalue("service.instance.id", "inst-1"),
1842        ];
1843        process_resource_attrs(&mut attrs, &OtlpMetricCtx::default());
1844        assert_eq!(attr_value(&attrs, "job"), None);
1845        assert_eq!(attr_value(&attrs, "instance").as_deref(), Some("inst-1"));
1846    }
1847
1848    #[test]
1849    fn test_reject_metric_name_attribute() {
1850        set_default_prefix(None).unwrap();
1851        for (strategy, key) in [
1852            (
1853                OtlpMetricTranslationStrategy::UnderscoreEscapingWithSuffixes,
1854                "__name__",
1855            ),
1856            (
1857                OtlpMetricTranslationStrategy::UnderscoreEscapingWithoutSuffixes,
1858                "__name__",
1859            ),
1860            (
1861                OtlpMetricTranslationStrategy::NoUtf8EscapingWithSuffixes,
1862                "__name__",
1863            ),
1864            (OtlpMetricTranslationStrategy::NoTranslation, "__name__"),
1865            (
1866                OtlpMetricTranslationStrategy::UnderscoreEscapingWithSuffixes,
1867                "..name..",
1868            ),
1869        ] {
1870            for source in [
1871                AttributeType::Resource,
1872                AttributeType::Scope,
1873                AttributeType::DataPoint,
1874            ] {
1875                let mut request = gauge_request(vec![], "source_metric");
1876                let resource = &mut request.resource_metrics[0];
1877                let scope = &mut resource.scope_metrics[0];
1878                let Some(metric::Data::Gauge(gauge)) = scope.metrics[0].data.as_mut() else {
1879                    unreachable!();
1880                };
1881                gauge.data_points[0].exemplars.push(Exemplar {
1882                    value: Some(exemplar::Value::AsDouble(0.25)),
1883                    time_unix_nano: 1_000_000,
1884                    ..Default::default()
1885                });
1886                let attributes = vec![keyvalue(key, "wrong_metric")];
1887                match source {
1888                    AttributeType::Resource => {
1889                        resource.resource.as_mut().unwrap().attributes = attributes;
1890                    }
1891                    AttributeType::Scope => {
1892                        scope.scope = Some(InstrumentationScope {
1893                            attributes,
1894                            ..Default::default()
1895                        });
1896                    }
1897                    AttributeType::DataPoint => gauge.data_points[0].attributes = attributes,
1898                }
1899                let mut ctx = OtlpMetricCtx {
1900                    with_metric_engine: true,
1901                    metric_translation_strategy: strategy,
1902                    promote_all_resource_attrs: true,
1903                    promote_scope_attrs: true,
1904                    ..Default::default()
1905                };
1906                let result = to_grpc_insert_requests(request, &mut ctx);
1907                if source == AttributeType::Scope {
1908                    let conversion = result.unwrap();
1909                    assert_eq!(1, conversion.exemplars.len());
1910                    assert!(
1911                        column_names(&conversion.requests, "source_metric")
1912                            .contains(&"otel_scope___name__".to_string())
1913                    );
1914                } else {
1915                    let conversion = result.unwrap();
1916                    assert_eq!(conversion.outcome.accepted_data_points, 0);
1917                    assert_eq!(conversion.outcome.rejected_data_points, 1);
1918                    assert_eq!(conversion.exemplars.len(), 0);
1919                    assert!(conversion.outcome.error_message.unwrap().contains(&format!(
1920                        "OTLP attribute `{key}` resolves to reserved label `__name__`"
1921                    )));
1922                }
1923            }
1924        }
1925    }
1926
1927    #[test]
1928    fn test_boolean_attributes_keep_series_distinct() {
1929        set_default_prefix(None).unwrap();
1930        let request = metrics_request(vec![Metric {
1931            name: "bool_repro".to_string(),
1932            data: Some(metric::Data::Sum(Sum {
1933                data_points: vec![
1934                    NumberDataPoint {
1935                        attributes: vec![bool_keyvalue("failed", false)],
1936                        start_time_unix_nano: 1_000_000,
1937                        time_unix_nano: 2_000_000,
1938                        value: Some(Value::AsDouble(100.0)),
1939                        ..Default::default()
1940                    },
1941                    NumberDataPoint {
1942                        attributes: vec![bool_keyvalue("failed", true)],
1943                        start_time_unix_nano: 1_000_000,
1944                        time_unix_nano: 2_000_000,
1945                        value: Some(Value::AsDouble(7.0)),
1946                        ..Default::default()
1947                    },
1948                ],
1949                aggregation_temporality: AggregationTemporality::Cumulative as i32,
1950                is_monotonic: true,
1951            })),
1952            ..Default::default()
1953        }]);
1954        let conversion = to_grpc_insert_requests(request, &mut OtlpMetricCtx::default()).unwrap();
1955
1956        let rows = conversion
1957            .requests
1958            .inserts
1959            .iter()
1960            .find(|insert| insert.table_name == "bool_repro_total")
1961            .expect("missing bool_repro_total table")
1962            .rows
1963            .as_ref()
1964            .unwrap();
1965        assert_eq!(2, rows.rows.len());
1966        let failed = rows
1967            .schema
1968            .iter()
1969            .position(|column| column.column_name == "failed")
1970            .expect("boolean attribute `failed` was dropped from the label set");
1971        let values = rows
1972            .rows
1973            .iter()
1974            .map(|row| row.values[failed].value_data.clone())
1975            .collect::<Vec<_>>();
1976        assert_eq!(
1977            vec![
1978                Some(ValueData::StringValue("false".to_string())),
1979                Some(ValueData::StringValue("true".to_string())),
1980            ],
1981            values
1982        );
1983    }
1984
1985    #[test]
1986    fn test_encode_gauge() {
1987        let mut tables = MultiTableData::default();
1988
1989        let data_points = vec![
1990            NumberDataPoint {
1991                attributes: vec![keyvalue("host", "testsevrer")],
1992                time_unix_nano: 100,
1993                value: Some(Value::AsInt(100)),
1994                ..Default::default()
1995            },
1996            NumberDataPoint {
1997                attributes: vec![keyvalue("host", "testserver")],
1998                time_unix_nano: 105,
1999                value: Some(Value::AsInt(105)),
2000                ..Default::default()
2001            },
2002        ];
2003        let gauge = Gauge { data_points };
2004        encode_gauge(
2005            &mut tables,
2006            "datamon",
2007            &gauge,
2008            Some(&vec![]),
2009            Some(&vec![keyvalue("scope", "otel")]),
2010            &OtlpMetricCtx::default(),
2011            &mut Vec::new(),
2012        )
2013        .unwrap();
2014
2015        let table = tables.get_or_default_table_data("datamon", 0, 0);
2016        assert_eq!(table.num_rows(), 2);
2017        assert_eq!(table.num_columns(), 4);
2018        assert_eq!(
2019            table
2020                .columns()
2021                .iter()
2022                .map(|c| &c.column_name)
2023                .collect::<Vec<&String>>(),
2024            vec![
2025                "otel_scope_scope",
2026                "host",
2027                greptime_timestamp(),
2028                greptime_value()
2029            ]
2030        );
2031    }
2032
2033    #[test]
2034    fn test_encode_sum() {
2035        let mut tables = MultiTableData::default();
2036
2037        let data_points = vec![
2038            NumberDataPoint {
2039                attributes: vec![keyvalue("host", "testserver")],
2040                time_unix_nano: 100,
2041                value: Some(Value::AsInt(100)),
2042                ..Default::default()
2043            },
2044            NumberDataPoint {
2045                attributes: vec![keyvalue("host", "testserver")],
2046                time_unix_nano: 105,
2047                value: Some(Value::AsInt(0)),
2048                ..Default::default()
2049            },
2050        ];
2051        let sum = Sum {
2052            data_points,
2053            ..Default::default()
2054        };
2055        encode_sum(
2056            &mut tables,
2057            "datamon",
2058            &sum,
2059            Some(&vec![]),
2060            Some(&vec![keyvalue("scope", "otel")]),
2061            &OtlpMetricCtx::default(),
2062            &mut Vec::new(),
2063        )
2064        .unwrap();
2065
2066        let table = tables.get_or_default_table_data("datamon", 0, 0);
2067        assert_eq!(table.num_rows(), 2);
2068        assert_eq!(table.num_columns(), 4);
2069        assert_eq!(
2070            table
2071                .columns()
2072                .iter()
2073                .map(|c| &c.column_name)
2074                .collect::<Vec<&String>>(),
2075            vec![
2076                "otel_scope_scope",
2077                "host",
2078                greptime_timestamp(),
2079                greptime_value()
2080            ]
2081        );
2082    }
2083
2084    #[test]
2085    fn test_encode_summary() {
2086        let mut tables = MultiTableData::default();
2087
2088        let data_points = vec![SummaryDataPoint {
2089            attributes: vec![keyvalue("host", "testserver")],
2090            time_unix_nano: 100,
2091            count: 25,
2092            sum: 5400.0,
2093            quantile_values: vec![
2094                ValueAtQuantile {
2095                    quantile: 0.90,
2096                    value: 1000.0,
2097                },
2098                ValueAtQuantile {
2099                    quantile: 0.95,
2100                    value: 3030.0,
2101                },
2102            ],
2103            ..Default::default()
2104        }];
2105        let summary = Summary { data_points };
2106        encode_summary(
2107            &mut tables,
2108            "datamon",
2109            &summary,
2110            Some(&vec![]),
2111            Some(&vec![keyvalue("scope", "otel")]),
2112            &OtlpMetricCtx::default(),
2113        )
2114        .unwrap();
2115
2116        let table = tables.get_or_default_table_data("datamon", 0, 0);
2117        assert_eq!(table.num_rows(), 2);
2118        assert_eq!(table.num_columns(), 5);
2119        assert_eq!(
2120            table
2121                .columns()
2122                .iter()
2123                .map(|c| &c.column_name)
2124                .collect::<Vec<&String>>(),
2125            vec![
2126                "otel_scope_scope",
2127                "host",
2128                greptime_timestamp(),
2129                "quantile",
2130                greptime_value()
2131            ]
2132        );
2133
2134        let table = tables.get_or_default_table_data("datamon_count", 0, 0);
2135        assert_eq!(table.num_rows(), 1);
2136        assert_eq!(table.num_columns(), 4);
2137        assert_eq!(
2138            table
2139                .columns()
2140                .iter()
2141                .map(|c| &c.column_name)
2142                .collect::<Vec<&String>>(),
2143            vec![
2144                "otel_scope_scope",
2145                "host",
2146                greptime_timestamp(),
2147                greptime_value()
2148            ]
2149        );
2150
2151        let table = tables.get_or_default_table_data("datamon_sum", 0, 0);
2152        assert_eq!(table.num_rows(), 1);
2153        assert_eq!(table.num_columns(), 4);
2154        assert_eq!(
2155            table
2156                .columns()
2157                .iter()
2158                .map(|c| &c.column_name)
2159                .collect::<Vec<&String>>(),
2160            vec![
2161                "otel_scope_scope",
2162                "host",
2163                greptime_timestamp(),
2164                greptime_value()
2165            ]
2166        );
2167    }
2168
2169    #[test]
2170    fn test_encode_histogram() {
2171        let mut tables = MultiTableData::default();
2172        let mut outcome = MetricsIngestOutcome::default();
2173
2174        let data_points = vec![HistogramDataPoint {
2175            attributes: vec![keyvalue("host", "testserver")],
2176            time_unix_nano: 100,
2177            start_time_unix_nano: 23,
2178            count: 25,
2179            sum: Some(100.),
2180            max: Some(200.),
2181            min: Some(0.03),
2182            bucket_counts: vec![2, 4, 6, 9, 4],
2183            explicit_bounds: vec![0.1, 1., 10., 100.],
2184            ..Default::default()
2185        }];
2186
2187        let histogram = Histogram {
2188            data_points,
2189            aggregation_temporality: AggregationTemporality::Delta.into(),
2190        };
2191        encode_histogram(
2192            &mut tables,
2193            "histo",
2194            &histogram,
2195            Some(&vec![]),
2196            Some(&vec![keyvalue("scope", "otel")]),
2197            &OtlpMetricCtx::default(),
2198            &mut outcome,
2199            &mut Vec::new(),
2200        )
2201        .unwrap();
2202
2203        assert_eq!(3, tables.num_tables());
2204        assert_eq!(1, outcome.accepted_data_points);
2205
2206        // bucket table
2207        let bucket_table = tables.get_or_default_table_data("histo_bucket", 0, 0);
2208        assert_eq!(bucket_table.num_rows(), 5);
2209        assert_eq!(bucket_table.num_columns(), 6);
2210        assert_eq!(
2211            bucket_table
2212                .columns()
2213                .iter()
2214                .map(|c| &c.column_name)
2215                .collect::<Vec<&String>>(),
2216            vec![
2217                "otel_scope_scope",
2218                "host",
2219                greptime_timestamp(),
2220                OTLP_AGGREGATION_TEMPORALITY_LABEL,
2221                "le",
2222                greptime_value(),
2223            ]
2224        );
2225
2226        let sum_table = tables.get_or_default_table_data("histo_sum", 0, 0);
2227        assert_eq!(sum_table.num_rows(), 1);
2228        assert_eq!(sum_table.num_columns(), 5);
2229        assert_eq!(
2230            sum_table
2231                .columns()
2232                .iter()
2233                .map(|c| &c.column_name)
2234                .collect::<Vec<&String>>(),
2235            vec![
2236                "otel_scope_scope",
2237                "host",
2238                greptime_timestamp(),
2239                OTLP_AGGREGATION_TEMPORALITY_LABEL,
2240                greptime_value()
2241            ]
2242        );
2243
2244        let count_table = tables.get_or_default_table_data("histo_count", 0, 0);
2245        assert_eq!(count_table.num_rows(), 1);
2246        assert_eq!(count_table.num_columns(), 5);
2247        assert_eq!(
2248            count_table
2249                .columns()
2250                .iter()
2251                .map(|c| &c.column_name)
2252                .collect::<Vec<&String>>(),
2253            vec![
2254                "otel_scope_scope",
2255                "host",
2256                greptime_timestamp(),
2257                OTLP_AGGREGATION_TEMPORALITY_LABEL,
2258                greptime_value()
2259            ]
2260        );
2261    }
2262
2263    use std::collections::BTreeMap;
2264
2265    use table::requests::validate_semantic_option;
2266
2267    fn decode(index: &SemanticIndex) -> BTreeMap<String, BTreeMap<String, String>> {
2268        let nested: BTreeMap<String, BTreeMap<String, BTreeMap<String, String>>> =
2269            serde_json::from_str(&index.encode("public").expect("non-empty index")).unwrap();
2270        nested.into_values().next().unwrap()
2271    }
2272
2273    fn record(metric: &Metric, metric_type: MetricType, name: &str) -> SemanticIndex {
2274        let ctx = OtlpMetricCtx {
2275            metric_type,
2276            ..Default::default()
2277        };
2278        let mut index = SemanticIndex::default();
2279        record_metric_semantics(
2280            &mut index,
2281            metric,
2282            name,
2283            &emitted_semantic_tables(&ctx.metric_type, name),
2284        );
2285        index
2286    }
2287
2288    #[test]
2289    fn test_metric_type_constants_validate() {
2290        for value in [
2291            METRIC_TYPE_COUNTER,
2292            METRIC_TYPE_UPDOWN_COUNTER,
2293            METRIC_TYPE_GAUGE,
2294            METRIC_TYPE_HISTOGRAM,
2295            METRIC_TYPE_SUMMARY,
2296        ] {
2297            assert!(
2298                validate_semantic_option(SEMANTIC_METRIC_TYPE, value),
2299                "metric.type value `{value}` must be in the vocabulary domain"
2300            );
2301        }
2302        for value in ["delta", "cumulative"] {
2303            assert!(validate_semantic_option(SEMANTIC_METRIC_TEMPORALITY, value));
2304        }
2305    }
2306
2307    #[test]
2308    fn test_record_monotonic_sum() {
2309        let metric = Metric {
2310            name: "claude_code.cost.usage".to_string(),
2311            unit: "USD".to_string(),
2312            data: Some(metric::Data::Sum(Sum {
2313                aggregation_temporality: AggregationTemporality::Delta as i32,
2314                is_monotonic: true,
2315                ..Default::default()
2316            })),
2317            ..Default::default()
2318        };
2319        let index = record(
2320            &metric,
2321            MetricType::MonotonicSum,
2322            "claude_code_cost_usage_USD_total",
2323        );
2324        let decoded = decode(&index);
2325        let t = &decoded["claude_code_cost_usage_USD_total"];
2326
2327        assert_eq!(
2328            t.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
2329            Some("counter")
2330        );
2331        assert_eq!(
2332            t.get(SEMANTIC_METRIC_TEMPORALITY).map(String::as_str),
2333            Some("delta")
2334        );
2335        assert_eq!(t.get(SEMANTIC_METRIC_UNIT).map(String::as_str), Some("USD"));
2336        assert_eq!(
2337            t.get(SEMANTIC_METRIC_ORIGINAL_NAME).map(String::as_str),
2338            Some("claude_code.cost.usage")
2339        );
2340        assert_eq!(
2341            t.get(SEMANTIC_METRIC_METADATA_QUALITY).map(String::as_str),
2342            Some("declared")
2343        );
2344    }
2345
2346    #[test]
2347    fn test_record_non_monotonic_sum() {
2348        let metric = Metric {
2349            name: "queue_size".to_string(),
2350            data: Some(metric::Data::Sum(Sum {
2351                aggregation_temporality: AggregationTemporality::Cumulative as i32,
2352                is_monotonic: false,
2353                ..Default::default()
2354            })),
2355            ..Default::default()
2356        };
2357        let index = record(&metric, MetricType::NonMonotonicSum, "queue_size");
2358        let decoded = decode(&index);
2359        let t = &decoded["queue_size"];
2360        assert_eq!(
2361            t.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
2362            Some("updown_counter")
2363        );
2364        assert_eq!(
2365            t.get(SEMANTIC_METRIC_TEMPORALITY).map(String::as_str),
2366            Some("cumulative")
2367        );
2368        // Name unchanged by translation -> no original_name.
2369        assert_eq!(t.get(SEMANTIC_METRIC_ORIGINAL_NAME), None);
2370    }
2371
2372    #[test]
2373    fn test_record_gauge_has_no_temporality() {
2374        let metric = Metric {
2375            name: "temperature".to_string(),
2376            data: Some(metric::Data::Gauge(Gauge::default())),
2377            ..Default::default()
2378        };
2379        let index = record(&metric, MetricType::Gauge, "temperature");
2380        let decoded = decode(&index);
2381        let t = &decoded["temperature"];
2382        assert_eq!(
2383            t.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
2384            Some("gauge")
2385        );
2386        assert_eq!(t.get(SEMANTIC_METRIC_TEMPORALITY), None);
2387    }
2388
2389    #[test]
2390    fn test_record_histogram_fans_out_with_distinct_types() {
2391        let metric = Metric {
2392            name: "request.duration".to_string(),
2393            unit: "s".to_string(),
2394            data: Some(metric::Data::Histogram(Histogram {
2395                aggregation_temporality: AggregationTemporality::Cumulative as i32,
2396                ..Default::default()
2397            })),
2398            ..Default::default()
2399        };
2400        let index = record(&metric, MetricType::Histogram, "request_duration");
2401        let decoded = decode(&index);
2402
2403        let bucket = &decoded["request_duration_bucket"];
2404        assert_eq!(
2405            bucket.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
2406            Some("histogram")
2407        );
2408        assert_eq!(
2409            bucket.get(SEMANTIC_METRIC_UNIT).map(String::as_str),
2410            Some("s")
2411        );
2412
2413        for companion in ["request_duration_sum", "request_duration_count"] {
2414            let t = &decoded[companion];
2415            assert_eq!(
2416                t.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
2417                Some("counter")
2418            );
2419            assert_eq!(
2420                t.get(SEMANTIC_METRIC_TEMPORALITY).map(String::as_str),
2421                Some("cumulative")
2422            );
2423        }
2424    }
2425
2426    #[test]
2427    fn test_record_summary_fans_out() {
2428        let metric = Metric {
2429            name: "rpc.latency".to_string(),
2430            data: Some(metric::Data::Summary(Summary::default())),
2431            ..Default::default()
2432        };
2433        let index = record(&metric, MetricType::Summary, "rpc_latency");
2434        let decoded = decode(&index);
2435
2436        assert_eq!(
2437            decoded["rpc_latency"]
2438                .get(SEMANTIC_METRIC_TYPE)
2439                .map(String::as_str),
2440            Some("summary")
2441        );
2442        // Summary has no temporality.
2443        assert_eq!(
2444            decoded["rpc_latency"].get(SEMANTIC_METRIC_TEMPORALITY),
2445            None
2446        );
2447        for companion in ["rpc_latency_count", "rpc_latency_sum"] {
2448            assert_eq!(
2449                decoded[companion]
2450                    .get(SEMANTIC_METRIC_TYPE)
2451                    .map(String::as_str),
2452                Some("counter")
2453            );
2454        }
2455    }
2456
2457    fn exponential_buckets(
2458        offset: i32,
2459        bucket_counts: Vec<u64>,
2460    ) -> exponential_histogram_data_point::Buckets {
2461        exponential_histogram_data_point::Buckets {
2462            offset,
2463            bucket_counts,
2464        }
2465    }
2466
2467    fn exponential_point() -> ExponentialHistogramDataPoint {
2468        ExponentialHistogramDataPoint {
2469            start_time_unix_nano: 1_000_000,
2470            time_unix_nano: 2_000_000,
2471            count: 28,
2472            sum: None,
2473            scale: 9,
2474            zero_count: 7,
2475            positive: Some(exponential_buckets(-3, vec![1, 2, 3, 4, 5, 6])),
2476            zero_threshold: 0.0,
2477            ..Default::default()
2478        }
2479    }
2480
2481    fn native_field(value: &ValueData, name: &str) -> Option<ValueData> {
2482        let ValueData::StructValue(value) = value else {
2483            panic!("expected native histogram Struct value");
2484        };
2485        let index = common_query::native_histogram::NATIVE_HISTOGRAM_FIELD_NAMES
2486            .iter()
2487            .position(|field| *field == name)
2488            .unwrap();
2489        value.items[index].value_data.clone()
2490    }
2491
2492    fn i32_list(value: Option<ValueData>) -> Vec<i32> {
2493        let Some(ValueData::ListValue(value)) = value else {
2494            panic!("expected i32 list");
2495        };
2496        value
2497            .items
2498            .into_iter()
2499            .map(|item| match item.value_data {
2500                Some(ValueData::I32Value(value)) => value,
2501                _ => panic!("expected i32 value"),
2502            })
2503            .collect()
2504    }
2505
2506    fn i64_list(value: Option<ValueData>) -> Vec<i64> {
2507        let Some(ValueData::ListValue(value)) = value else {
2508            panic!("expected i64 list");
2509        };
2510        value
2511            .items
2512            .into_iter()
2513            .map(|item| match item.value_data {
2514                Some(ValueData::I64Value(value)) => value,
2515                _ => panic!("expected i64 value"),
2516            })
2517            .collect()
2518    }
2519
2520    #[test]
2521    fn test_downscale_bucket_index_uses_signed_floor_division() {
2522        assert_eq!(downscale_bucket_index(-3, 1).unwrap(), -2);
2523        assert_eq!(downscale_bucket_index(-2, 1).unwrap(), -1);
2524        assert_eq!(downscale_bucket_index(-1, 1).unwrap(), -1);
2525        assert_eq!(downscale_bucket_index(0, 1).unwrap(), 0);
2526        assert_eq!(downscale_bucket_index(1, 1).unwrap(), 0);
2527        assert_eq!(downscale_bucket_index(2, 1).unwrap(), 1);
2528        assert_eq!(downscale_bucket_index(i32::MIN, 32).unwrap(), -1);
2529        assert_eq!(downscale_bucket_index(i32::MAX, 32).unwrap(), 0);
2530    }
2531
2532    #[test]
2533    fn test_convert_bucket_range_downscales_before_prometheus_shift() {
2534        let buckets = exponential_buckets(-3, vec![1, 2, 3, 4, 5, 6]);
2535        let (spans, deltas, total) = convert_bucket_range("positive", Some(&buckets), 1).unwrap();
2536
2537        assert_eq!(
2538            spans,
2539            vec![BucketSpan {
2540                offset: -1,
2541                length: 4
2542            }]
2543        );
2544        assert_eq!(deltas, vec![1, 4, 4, -3]);
2545        assert_eq!(total, 21);
2546    }
2547
2548    #[test]
2549    fn test_convert_bucket_range_compacts_zero_runs() {
2550        let large = (1u64 << 53) + 1;
2551        for (offset, counts, shift, expected_spans, expected_deltas, expected_total) in [
2552            (
2553                -3,
2554                vec![0, 3, 0, 0, 7, 9, 0],
2555                0,
2556                vec![(-1, 1), (2, 2)],
2557                vec![3, 4, 2],
2558                19,
2559            ),
2560            (
2561                -4,
2562                vec![0, 0, 2, 3, 0, 0, 0, 0, 7, 0],
2563                1,
2564                vec![(0, 1), (2, 1)],
2565                vec![5, 2],
2566                12,
2567            ),
2568            (0, vec![0, 0, 0], 0, vec![], vec![], 0),
2569            (0, vec![], 0, vec![], vec![], 0),
2570            (i32::MIN, vec![0, 1], 0, vec![(i32::MIN + 2, 1)], vec![1], 1),
2571            (i32::MAX - 1, vec![1], 0, vec![(i32::MAX, 1)], vec![1], 1),
2572            (
2573                0,
2574                vec![large, 0, large + 2],
2575                0,
2576                vec![(1, 1), (1, 1)],
2577                vec![large as i64, 2],
2578                large * 2 + 2,
2579            ),
2580        ] {
2581            let buckets = exponential_buckets(offset, counts);
2582            let (spans, deltas, total) =
2583                convert_bucket_range("positive", Some(&buckets), shift).unwrap();
2584            assert_eq!(
2585                spans
2586                    .iter()
2587                    .map(|span| (span.offset, span.length))
2588                    .collect::<Vec<_>>(),
2589                expected_spans,
2590                "{buckets:?}, shift={shift}"
2591            );
2592            assert_eq!(deltas, expected_deltas, "{buckets:?}, shift={shift}");
2593            assert_eq!(total, expected_total);
2594        }
2595
2596        // Compaction must not hide invalid source indexes, even for empty buckets.
2597        let buckets = exponential_buckets(i32::MAX, vec![0]);
2598        assert!(
2599            convert_bucket_range("positive", Some(&buckets), 0)
2600                .unwrap_err()
2601                .contains("shifted bucket index overflows")
2602        );
2603    }
2604
2605    #[test]
2606    fn test_exponential_histogram_compaction_preserves_integer_counts() {
2607        use common_query::native_histogram::{
2608            COUNT_I64_FIELD, NEGATIVE_BUCKETS_I64_FIELD, NEGATIVE_SPAN_LENGTHS_FIELD,
2609            NEGATIVE_SPAN_OFFSETS_FIELD, POSITIVE_BUCKETS_I64_FIELD, POSITIVE_SPAN_LENGTHS_FIELD,
2610            POSITIVE_SPAN_OFFSETS_FIELD,
2611        };
2612
2613        let large = (1u64 << 53) + 1;
2614        let buckets = exponential_buckets(-2, vec![0, large, 0, 3, 0]);
2615        let point = ExponentialHistogramDataPoint {
2616            count: 2 * (large + 3),
2617            positive: Some(buckets.clone()),
2618            negative: Some(buckets),
2619            ..Default::default()
2620        };
2621        let (value, _) =
2622            exponential_histogram_value(&point, AggregationTemporality::Cumulative).unwrap();
2623        assert_eq!(
2624            native_field(&value, COUNT_I64_FIELD),
2625            Some(ValueData::I64Value(point.count as i64))
2626        );
2627        for (offsets, lengths, counts) in [
2628            (
2629                POSITIVE_SPAN_OFFSETS_FIELD,
2630                POSITIVE_SPAN_LENGTHS_FIELD,
2631                POSITIVE_BUCKETS_I64_FIELD,
2632            ),
2633            (
2634                NEGATIVE_SPAN_OFFSETS_FIELD,
2635                NEGATIVE_SPAN_LENGTHS_FIELD,
2636                NEGATIVE_BUCKETS_I64_FIELD,
2637            ),
2638        ] {
2639            assert_eq!(i32_list(native_field(&value, offsets)), vec![0, 1]);
2640            assert_eq!(i32_list(native_field(&value, lengths)), vec![1, 1]);
2641            assert_eq!(
2642                i64_list(native_field(&value, counts)),
2643                vec![large as i64, 3]
2644            );
2645        }
2646    }
2647
2648    #[test]
2649    fn test_exponential_histogram_value_uses_integer_family() {
2650        use common_query::native_histogram::{
2651            COUNT_F64_FIELD, COUNT_I64_FIELD, POSITIVE_BUCKETS_I64_FIELD,
2652            POSITIVE_SPAN_LENGTHS_FIELD, POSITIVE_SPAN_OFFSETS_FIELD, SCHEMA_FIELD, SUM_FIELD,
2653            ZERO_COUNT_I64_FIELD,
2654        };
2655
2656        let (value, timestamp_nanos) =
2657            exponential_histogram_value(&exponential_point(), AggregationTemporality::Cumulative)
2658                .unwrap();
2659
2660        assert_eq!(timestamp_nanos, 2_000_000);
2661        assert_eq!(
2662            native_field(&value, SCHEMA_FIELD),
2663            Some(ValueData::I32Value(8))
2664        );
2665        assert_eq!(
2666            native_field(&value, COUNT_I64_FIELD),
2667            Some(ValueData::I64Value(28))
2668        );
2669        assert_eq!(
2670            native_field(&value, ZERO_COUNT_I64_FIELD),
2671            Some(ValueData::I64Value(7))
2672        );
2673        assert_eq!(native_field(&value, COUNT_F64_FIELD), None);
2674        assert_eq!(
2675            i32_list(native_field(&value, POSITIVE_SPAN_OFFSETS_FIELD)),
2676            vec![-1]
2677        );
2678        assert_eq!(
2679            i32_list(native_field(&value, POSITIVE_SPAN_LENGTHS_FIELD)),
2680            vec![4]
2681        );
2682        assert_eq!(
2683            i64_list(native_field(&value, POSITIVE_BUCKETS_I64_FIELD)),
2684            vec![1, 5, 9, 6]
2685        );
2686        let Some(ValueData::F64Value(sum)) = native_field(&value, SUM_FIELD) else {
2687            panic!("expected histogram sum");
2688        };
2689        assert_eq!(sum.to_bits(), f64::NAN.to_bits());
2690        assert_ne!(sum.to_bits(), PROMETHEUS_STALE_NAN_BITS);
2691    }
2692
2693    #[test]
2694    fn test_no_recorded_value_ignores_other_value_fields() {
2695        use common_query::native_histogram::{
2696            COUNT_I64_FIELD, POSITIVE_BUCKETS_I64_FIELD, SCHEMA_FIELD, SUM_FIELD,
2697            ZERO_COUNT_I64_FIELD, ZERO_THRESHOLD_FIELD,
2698        };
2699
2700        let point = ExponentialHistogramDataPoint {
2701            start_time_unix_nano: 1_000_000,
2702            time_unix_nano: 2_000_000,
2703            count: u64::MAX,
2704            sum: Some(1.0),
2705            scale: i32::MIN,
2706            zero_count: u64::MAX,
2707            positive: Some(exponential_buckets(i32::MAX, vec![u64::MAX])),
2708            flags: DataPointFlags::NoRecordedValueMask as u32,
2709            zero_threshold: f64::NAN,
2710            ..Default::default()
2711        };
2712        let (value, _) =
2713            exponential_histogram_value(&point, AggregationTemporality::Cumulative).unwrap();
2714
2715        assert_eq!(
2716            native_field(&value, SCHEMA_FIELD),
2717            Some(ValueData::I32Value(0))
2718        );
2719        assert_eq!(
2720            native_field(&value, ZERO_THRESHOLD_FIELD),
2721            Some(ValueData::F64Value(0.0))
2722        );
2723        assert_eq!(
2724            native_field(&value, COUNT_I64_FIELD),
2725            Some(ValueData::I64Value(0))
2726        );
2727        assert_eq!(
2728            native_field(&value, ZERO_COUNT_I64_FIELD),
2729            Some(ValueData::I64Value(0))
2730        );
2731        assert!(i64_list(native_field(&value, POSITIVE_BUCKETS_I64_FIELD)).is_empty());
2732        let Some(ValueData::F64Value(sum)) = native_field(&value, SUM_FIELD) else {
2733            panic!("expected histogram sum");
2734        };
2735        assert_eq!(sum.to_bits(), PROMETHEUS_STALE_NAN_BITS);
2736    }
2737
2738    #[test]
2739    fn test_non_flag_nan_sum_is_normalized() {
2740        use common_query::native_histogram::SUM_FIELD;
2741
2742        let point = ExponentialHistogramDataPoint {
2743            sum: Some(f64::from_bits(PROMETHEUS_STALE_NAN_BITS)),
2744            ..Default::default()
2745        };
2746        let (value, _) =
2747            exponential_histogram_value(&point, AggregationTemporality::Cumulative).unwrap();
2748        let Some(ValueData::F64Value(sum)) = native_field(&value, SUM_FIELD) else {
2749            panic!("expected histogram sum");
2750        };
2751        assert_eq!(sum.to_bits(), f64::NAN.to_bits());
2752        assert_ne!(sum.to_bits(), PROMETHEUS_STALE_NAN_BITS);
2753    }
2754
2755    #[test]
2756    fn test_exponential_histogram_rejects_invalid_values() {
2757        let mut cases = Vec::new();
2758
2759        let mut point = exponential_point();
2760        point.scale = -5;
2761        cases.push((point, "scale -5 is unsupported"));
2762
2763        let mut point = exponential_point();
2764        point.zero_threshold = f64::INFINITY;
2765        cases.push((point, "must be finite and non-negative"));
2766
2767        let mut point = exponential_point();
2768        point.start_time_unix_nano = point.time_unix_nano + 1;
2769        cases.push((point, "start_time_unix_nano"));
2770
2771        let mut point = exponential_point();
2772        point.count = 27;
2773        cases.push((point, "declared count is 27"));
2774
2775        let point = ExponentialHistogramDataPoint {
2776            count: u64::MAX,
2777            zero_count: u64::MAX,
2778            ..Default::default()
2779        };
2780        cases.push((point, "count 18446744073709551615 overflows i64"));
2781
2782        let point = ExponentialHistogramDataPoint {
2783            count: 1,
2784            scale: 8,
2785            positive: Some(exponential_buckets(i32::MAX, vec![1])),
2786            ..Default::default()
2787        };
2788        cases.push((point, "shifted bucket index overflows i32"));
2789
2790        for (point, expected) in cases {
2791            let error = exponential_histogram_value(&point, AggregationTemporality::Cumulative)
2792                .unwrap_err();
2793            assert!(
2794                error.contains(expected),
2795                "expected {expected:?}, got {error}"
2796            );
2797        }
2798
2799        let buckets = exponential_buckets(0, vec![u64::MAX, 1]);
2800        let error = convert_bucket_range("positive", Some(&buckets), 1).unwrap_err();
2801        assert!(
2802            error.contains("merged bucket count overflows u64"),
2803            "{error}"
2804        );
2805
2806        let buckets = exponential_buckets(i32::MAX, vec![1, 1]);
2807        let error = convert_bucket_range("positive", Some(&buckets), 1).unwrap_err();
2808        assert!(error.contains("bucket index overflows i32"), "{error}");
2809    }
2810
2811    fn metrics_request(metrics: Vec<Metric>) -> ExportMetricsServiceRequest {
2812        ExportMetricsServiceRequest {
2813            resource_metrics: vec![ResourceMetrics {
2814                scope_metrics: vec![ScopeMetrics {
2815                    metrics,
2816                    ..Default::default()
2817                }],
2818                ..Default::default()
2819            }],
2820        }
2821    }
2822
2823    #[test]
2824    fn test_invalid_exemplars_preserve_metric_payload() {
2825        use otel_arrow_rust::proto::opentelemetry::metrics::v1::{Exemplar, exemplar};
2826
2827        let valid = Exemplar {
2828            time_unix_nano: 1,
2829            value: Some(exemplar::Value::AsDouble(0.5)),
2830            ..Default::default()
2831        };
2832        for invalid in [
2833            Exemplar::default(),
2834            Exemplar {
2835                trace_id: vec![1],
2836                ..valid.clone()
2837            },
2838            Exemplar {
2839                span_id: vec![1],
2840                ..valid.clone()
2841            },
2842            Exemplar {
2843                time_unix_nano: u64::MAX,
2844                ..valid.clone()
2845            },
2846            Exemplar {
2847                filtered_attributes: vec![keyvalue("http.url", &"x".repeat(128))],
2848                ..valid.clone()
2849            },
2850            Exemplar {
2851                filtered_attributes: vec![keyvalue("a", "1"), keyvalue("a", "2")],
2852                ..valid.clone()
2853            },
2854        ] {
2855            let exemplars = vec![invalid.clone(), valid.clone(), invalid, valid.clone()];
2856            let point = NumberDataPoint {
2857                time_unix_nano: 1,
2858                value: Some(Value::AsDouble(1.0)),
2859                exemplars: exemplars.clone(),
2860                ..Default::default()
2861            };
2862            let metrics = vec![
2863                Metric {
2864                    name: "gauge".into(),
2865                    data: Some(metric::Data::Gauge(Gauge {
2866                        data_points: vec![point.clone()],
2867                    })),
2868                    ..Default::default()
2869                },
2870                Metric {
2871                    name: "sum".into(),
2872                    data: Some(metric::Data::Sum(Sum {
2873                        data_points: vec![point],
2874                        aggregation_temporality: AggregationTemporality::Cumulative as i32,
2875                        ..Default::default()
2876                    })),
2877                    ..Default::default()
2878                },
2879                exponential_metric(
2880                    "histogram",
2881                    vec![ExponentialHistogramDataPoint {
2882                        exemplars,
2883                        ..exponential_point()
2884                    }],
2885                    AggregationTemporality::Cumulative,
2886                ),
2887            ];
2888            let conversion = to_grpc_insert_requests(
2889                metrics_request(metrics),
2890                &mut OtlpMetricCtx {
2891                    with_metric_engine: true,
2892                    ..Default::default()
2893                },
2894            )
2895            .unwrap();
2896            assert_eq!(conversion.rows, 3);
2897            assert_eq!(conversion.outcome.accepted_data_points, 3);
2898            assert_eq!(conversion.outcome.rejected_data_points, 0);
2899            assert_eq!(conversion.exemplars.len(), 6);
2900        }
2901    }
2902
2903    #[test]
2904    fn test_histogram_exemplars_follow_emitted_buckets() {
2905        use otel_arrow_rust::proto::opentelemetry::metrics::v1::{Exemplar, exemplar};
2906        use prost::Message;
2907
2908        for mode in ["delta", "cumulative", "empty", "stale"] {
2909            let mut point = HistogramDataPoint {
2910                time_unix_nano: 100,
2911                count: 4,
2912                explicit_bounds: vec![1.0, 2.0],
2913                bucket_counts: vec![1, 1, 2],
2914                exemplars: [5.0, 1.0, 0.5, f64::NEG_INFINITY, f64::INFINITY, f64::NAN]
2915                    .into_iter()
2916                    .enumerate()
2917                    .map(|(i, value)| Exemplar {
2918                        time_unix_nano: i as u64 + 1,
2919                        value: Some(exemplar::Value::AsDouble(value)),
2920                        ..Default::default()
2921                    })
2922                    .collect(),
2923                ..Default::default()
2924            };
2925            point.exemplars.extend([
2926                Exemplar::default(),
2927                Exemplar {
2928                    trace_id: vec![1],
2929                    value: Some(exemplar::Value::AsDouble(1.0)),
2930                    ..Default::default()
2931                },
2932            ]);
2933            match mode {
2934                "empty" => {
2935                    point.explicit_bounds.clear();
2936                    point.bucket_counts.clear();
2937                }
2938                "stale" => point.flags = DataPointFlags::NoRecordedValueMask as u32,
2939                _ => {}
2940            }
2941            let mut histogram = Histogram {
2942                data_points: vec![point],
2943                aggregation_temporality: if mode == "cumulative" {
2944                    AggregationTemporality::Cumulative
2945                } else {
2946                    AggregationTemporality::Delta
2947                } as i32,
2948            };
2949            // This sibling omits the +Inf bucket to exercise partial rejection in every mode.
2950            histogram.data_points.push(HistogramDataPoint {
2951                explicit_bounds: vec![1.0],
2952                bucket_counts: vec![4],
2953                count: 4,
2954                exemplars: vec![Exemplar::default()],
2955                ..Default::default()
2956            });
2957            let mut request = gauge_request(vec![], "gauge");
2958            request.resource_metrics[0].scope_metrics[0]
2959                .metrics
2960                .push(Metric {
2961                    name: "histogram".into(),
2962                    data: Some(metric::Data::Histogram(histogram.clone())),
2963                    ..Default::default()
2964                });
2965            let ctx = OtlpMetricCtx {
2966                with_metric_engine: true,
2967                ..Default::default()
2968            };
2969            let mut conversion =
2970                to_grpc_insert_requests(request.clone(), &mut ctx.clone()).unwrap();
2971            assert_eq!(conversion.outcome.accepted_data_points, 2, "{mode}");
2972            assert_eq!(conversion.outcome.rejected_data_points, 1, "{mode}");
2973
2974            // Exemplars must not change either the histogram or the independent gauge payload.
2975            for point in &mut histogram.data_points {
2976                point.exemplars.clear();
2977            }
2978            request.resource_metrics[0].scope_metrics[0].metrics[1].data =
2979                Some(metric::Data::Histogram(histogram));
2980            let mut baseline = to_grpc_insert_requests(request, &mut ctx.clone()).unwrap();
2981            conversion
2982                .requests
2983                .inserts
2984                .sort_by(|a, b| a.table_name.cmp(&b.table_name));
2985            baseline
2986                .requests
2987                .inserts
2988                .sort_by(|a, b| a.table_name.cmp(&b.table_name));
2989            // Compare wire bytes so stale NaN values compare by their bits.
2990            assert_eq!(
2991                conversion.requests.encode_to_vec(),
2992                baseline.requests.encode_to_vec(),
2993                "{mode}"
2994            );
2995
2996            let expected = match mode {
2997                "empty" => vec![
2998                    (1, "inf"),
2999                    (2, "inf"),
3000                    (3, "inf"),
3001                    (4, "inf"),
3002                    (5, "inf"),
3003                    (6, "inf"),
3004                ],
3005                _ => vec![
3006                    (1, "inf"),
3007                    (2, "1"),
3008                    (3, "1"),
3009                    (4, "1"),
3010                    (5, "inf"),
3011                    (6, "inf"),
3012                ],
3013            };
3014            assert_eq!(conversion.exemplars.len(), expected.len(), "{mode}");
3015            let exemplars = crate::exemplar::ExemplarBatch::try_new(conversion.exemplars).unwrap();
3016            let mut actual = Vec::new();
3017            for exemplar in exemplars.exemplars() {
3018                assert_eq!(exemplar.metric.as_ref(), "histogram_bucket");
3019                let bound = exemplar
3020                    .series_labels
3021                    .get("le")
3022                    .expect("missing bucket label");
3023                actual.push((exemplar.timestamp, bound.as_str()));
3024                if exemplar.timestamp == 3 {
3025                    assert_eq!(exemplar.value, 0.5);
3026                }
3027            }
3028            actual.sort_unstable();
3029            assert_eq!(actual, expected, "{mode}");
3030        }
3031
3032        let missing_infinity = Histogram {
3033            data_points: vec![HistogramDataPoint {
3034                explicit_bounds: vec![1.0],
3035                bucket_counts: vec![1],
3036                count: 1,
3037                exemplars: vec![Exemplar {
3038                    time_unix_nano: 2,
3039                    value: Some(exemplar::Value::AsDouble(0.5)),
3040                    ..Default::default()
3041                }],
3042                ..Default::default()
3043            }],
3044            aggregation_temporality: AggregationTemporality::Cumulative as i32,
3045        };
3046        let conversion = to_grpc_insert_requests(
3047            metrics_request(vec![Metric {
3048                name: "missing_infinity".into(),
3049                data: Some(metric::Data::Histogram(missing_infinity)),
3050                ..Default::default()
3051            }]),
3052            &mut OtlpMetricCtx {
3053                with_metric_engine: true,
3054                ..Default::default()
3055            },
3056        )
3057        .unwrap();
3058        assert_eq!(conversion.outcome.accepted_data_points, 0);
3059        assert_eq!(conversion.outcome.rejected_data_points, 1);
3060        assert!(conversion.requests.inserts.is_empty());
3061        assert!(conversion.exemplars.is_empty());
3062    }
3063
3064    fn exponential_metric(
3065        name: impl Into<String>,
3066        data_points: Vec<ExponentialHistogramDataPoint>,
3067        temporality: AggregationTemporality,
3068    ) -> Metric {
3069        Metric {
3070            name: name.into(),
3071            data: Some(metric::Data::ExponentialHistogram(ExponentialHistogram {
3072                data_points,
3073                aggregation_temporality: temporality as i32,
3074            })),
3075            ..Default::default()
3076        }
3077    }
3078
3079    fn histogram_metric(name: impl Into<String>) -> Metric {
3080        Metric {
3081            name: name.into(),
3082            data: Some(metric::Data::Histogram(Histogram {
3083                data_points: vec![HistogramDataPoint {
3084                    start_time_unix_nano: 1_000_000,
3085                    time_unix_nano: 2_000_000,
3086                    count: 1,
3087                    sum: Some(1.0),
3088                    bucket_counts: vec![1],
3089                    ..Default::default()
3090                }],
3091                aggregation_temporality: AggregationTemporality::Cumulative as i32,
3092            })),
3093            ..Default::default()
3094        }
3095    }
3096
3097    #[test]
3098    fn test_metric_engine_path_keeps_nanosecond_precision() {
3099        let time_unix_nano = 1_704_067_200_123_456_789u64;
3100        let request = metrics_request(vec![Metric {
3101            name: "my_gauge".to_string(),
3102            data: Some(metric::Data::Gauge(Gauge {
3103                data_points: vec![NumberDataPoint {
3104                    time_unix_nano,
3105                    value: Some(Value::AsDouble(1.0)),
3106                    ..Default::default()
3107                }],
3108            })),
3109            ..Default::default()
3110        }]);
3111
3112        // The metric engine path keeps the full nanosecond precision here;
3113        // `Inserter::handle_metric_row_inserts` converts the timestamps to
3114        // the physical table's time index unit afterwards.
3115        let mut metric_ctx = OtlpMetricCtx {
3116            with_metric_engine: true,
3117            ..Default::default()
3118        };
3119        let MetricsConversion { requests, .. } =
3120            to_grpc_insert_requests(request, &mut metric_ctx).unwrap();
3121
3122        let rows = requests.inserts[0].rows.as_ref().unwrap();
3123        let ts_index = rows
3124            .schema
3125            .iter()
3126            .position(|column| column.column_name == greptime_timestamp())
3127            .unwrap();
3128        assert_eq!(
3129            rows.schema[ts_index].datatype,
3130            ColumnDataType::TimestampNanosecond as i32
3131        );
3132        assert!(matches!(
3133            rows.rows[0].values[ts_index].value_data,
3134            Some(ValueData::TimestampNanosecondValue(
3135                1_704_067_200_123_456_789
3136            ))
3137        ));
3138
3139        // The non-metric prometheus-compatible path stays millisecond so
3140        // auto-created mito tables keep the millisecond time index.
3141        let mut compat_ctx = OtlpMetricCtx::default();
3142        let request = metrics_request(vec![Metric {
3143            name: "my_gauge".to_string(),
3144            data: Some(metric::Data::Gauge(Gauge {
3145                data_points: vec![NumberDataPoint {
3146                    time_unix_nano,
3147                    value: Some(Value::AsDouble(1.0)),
3148                    ..Default::default()
3149                }],
3150            })),
3151            ..Default::default()
3152        }]);
3153        let MetricsConversion { requests, .. } =
3154            to_grpc_insert_requests(request, &mut compat_ctx).unwrap();
3155
3156        let rows = requests.inserts[0].rows.as_ref().unwrap();
3157        let ts_index = rows
3158            .schema
3159            .iter()
3160            .position(|column| column.column_name == greptime_timestamp())
3161            .unwrap();
3162        assert_eq!(
3163            rows.schema[ts_index].datatype,
3164            ColumnDataType::TimestampMillisecond as i32
3165        );
3166        assert!(matches!(
3167            rows.rows[0].values[ts_index].value_data,
3168            Some(ValueData::TimestampMillisecondValue(1_704_067_200_123))
3169        ));
3170    }
3171
3172    #[test]
3173    fn test_exponential_histogram_rejection_metrics() {
3174        // Other conversion tests update the same process-global counters.
3175        const ISOLATED_ENV: &str = "GREPTIME_TEST_OTLP_REJECTION_METRICS_ISOLATED";
3176        if std::env::var_os(ISOLATED_ENV).is_none() {
3177            let output = std::process::Command::new(std::env::current_exe().unwrap())
3178                .args([
3179                    "--exact",
3180                    "otlp::metrics::tests::test_exponential_histogram_rejection_metrics",
3181                ])
3182                .env(ISOLATED_ENV, "1")
3183                .output()
3184                .unwrap();
3185            let stdout = String::from_utf8_lossy(&output.stdout);
3186            assert!(
3187                output.status.success() && stdout.contains("1 passed"),
3188                "isolated rejection metrics test failed\nstdout:\n{stdout}\nstderr:\n{}",
3189                String::from_utf8_lossy(&output.stderr)
3190            );
3191            return;
3192        }
3193
3194        let mut invalid = exponential_point();
3195        invalid.scale = -5;
3196        for (temporality, points, reason, accepted, rejected) in [
3197            (
3198                AggregationTemporality::Delta,
3199                vec![exponential_point(); 2],
3200                "invalid_data_point",
3201                2,
3202                0,
3203            ),
3204            (
3205                AggregationTemporality::Unspecified,
3206                vec![exponential_point(); 2],
3207                "unspecified_temporality",
3208                0,
3209                2,
3210            ),
3211            (
3212                AggregationTemporality::Cumulative,
3213                vec![exponential_point(), invalid],
3214                "invalid_data_point",
3215                1,
3216                1,
3217            ),
3218            (
3219                AggregationTemporality::Cumulative,
3220                vec![exponential_point()],
3221                "invalid_data_point",
3222                1,
3223                0,
3224            ),
3225        ] {
3226            let counter =
3227                OTLP_EXPONENTIAL_HISTOGRAM_REJECTED_DATA_POINTS.with_label_values(&[reason]);
3228            let before = counter.get();
3229            let mut request =
3230                metrics_request(vec![exponential_metric("latency", points, temporality)]);
3231            request.resource_metrics[0].resource = Some(Resource {
3232                attributes: vec![keyvalue("service.name", "api")],
3233                ..Default::default()
3234            });
3235            let mut ctx = descriptor_ctx();
3236            let conversion = to_grpc_insert_requests(request, &mut ctx).unwrap();
3237            assert_eq!(conversion.outcome.accepted_data_points, accepted);
3238            assert_eq!(conversion.outcome.rejected_data_points, rejected);
3239            assert_eq!(counter.get() - before, rejected as u64, "{reason}");
3240            assert_eq!(conversion.resource_info.is_some(), accepted > 0);
3241
3242            let before = counter.get();
3243            let empty = metrics_request(vec![exponential_metric("empty", vec![], temporality)]);
3244            assert_eq!(
3245                to_grpc_insert_requests(empty, &mut ctx)
3246                    .unwrap()
3247                    .outcome
3248                    .rejected_data_points,
3249                0
3250            );
3251            assert_eq!(counter.get(), before, "empty metric: {reason}");
3252        }
3253    }
3254
3255    #[test]
3256    fn test_exponential_histogram_default_context_and_partial_outcome() {
3257        let request = metrics_request(vec![
3258            Metric {
3259                name: "temperature".to_string(),
3260                data: Some(metric::Data::Gauge(Gauge {
3261                    data_points: vec![NumberDataPoint::default()],
3262                })),
3263                ..Default::default()
3264            },
3265            exponential_metric(
3266                "latency",
3267                vec![exponential_point()],
3268                AggregationTemporality::Cumulative,
3269            ),
3270            exponential_metric(
3271                "delta_latency",
3272                vec![exponential_point()],
3273                AggregationTemporality::Delta,
3274            ),
3275        ]);
3276        let MetricsConversion {
3277            requests,
3278            semantic_index,
3279            outcome,
3280            ..
3281        } = to_grpc_insert_requests(request, &mut OtlpMetricCtx::default()).unwrap();
3282
3283        assert_eq!(outcome.accepted_data_points, 3);
3284        assert_eq!(outcome.rejected_data_points, 0);
3285        assert!(outcome.error_message.is_none());
3286        assert_eq!(requests.inserts.len(), 3);
3287        let semantics = decode(&semantic_index);
3288        assert!(semantics.contains_key("temperature"));
3289        assert!(semantics.contains_key("latency"));
3290        assert_eq!(
3291            semantics["delta_latency"][SEMANTIC_METRIC_TEMPORALITY],
3292            "delta"
3293        );
3294
3295        let empty = metrics_request(vec![exponential_metric(
3296            "empty",
3297            vec![],
3298            AggregationTemporality::Cumulative,
3299        )]);
3300        let outcome = to_grpc_insert_requests(empty, &mut OtlpMetricCtx::default())
3301            .unwrap()
3302            .outcome;
3303        assert_eq!(outcome.rejected_data_points, 0);
3304        assert_eq!(outcome.error_message, None);
3305    }
3306
3307    #[test]
3308    fn test_exponential_histogram_cannot_share_table_with_scalar_metric() {
3309        let request = metrics_request(vec![
3310            Metric {
3311                name: "latency".to_string(),
3312                data: Some(metric::Data::Gauge(Gauge {
3313                    data_points: vec![NumberDataPoint {
3314                        value: Some(number_data_point::Value::AsDouble(1.0)),
3315                        ..Default::default()
3316                    }],
3317                })),
3318                ..Default::default()
3319            },
3320            exponential_metric(
3321                "latency",
3322                vec![exponential_point()],
3323                AggregationTemporality::Cumulative,
3324            ),
3325        ]);
3326        let mut ctx = OtlpMetricCtx::default();
3327
3328        let conversion = to_grpc_insert_requests(request, &mut ctx).unwrap();
3329        assert_eq!(conversion.outcome.accepted_data_points, 0);
3330        assert_eq!(conversion.outcome.rejected_data_points, 2);
3331        assert!(conversion.requests.inserts.is_empty());
3332    }
3333
3334    #[test]
3335    fn test_histogram_cannot_replace_exponential_histogram_table() {
3336        let request = metrics_request(vec![
3337            exponential_metric(
3338                "latency_bucket",
3339                vec![exponential_point()],
3340                AggregationTemporality::Cumulative,
3341            ),
3342            histogram_metric("latency"),
3343        ]);
3344        let mut ctx = OtlpMetricCtx::default();
3345
3346        let conversion = to_grpc_insert_requests(request, &mut ctx).unwrap();
3347        assert_eq!(conversion.outcome.accepted_data_points, 0);
3348        assert_eq!(conversion.outcome.rejected_data_points, 2);
3349        assert!(conversion.requests.inserts.is_empty());
3350    }
3351
3352    #[test]
3353    fn test_histograms_with_same_name_across_resources_are_merged() {
3354        let metric = histogram_metric("latency");
3355        let request = ExportMetricsServiceRequest {
3356            resource_metrics: ["service-a", "service-b"]
3357                .into_iter()
3358                .map(|service| ResourceMetrics {
3359                    resource: Some(Resource {
3360                        attributes: vec![keyvalue("service.name", service)],
3361                        ..Default::default()
3362                    }),
3363                    scope_metrics: vec![ScopeMetrics {
3364                        metrics: vec![metric.clone()],
3365                        ..Default::default()
3366                    }],
3367                    ..Default::default()
3368                })
3369                .collect(),
3370        };
3371
3372        let MetricsConversion {
3373            requests,
3374            rows,
3375            outcome,
3376            ..
3377        } = to_grpc_insert_requests(request, &mut OtlpMetricCtx::default()).unwrap();
3378
3379        assert_eq!(outcome.accepted_data_points, 2);
3380        assert_eq!(rows, 6);
3381        assert_eq!(requests.inserts.len(), 3);
3382        for request in requests.inserts {
3383            assert_eq!(
3384                request.rows.unwrap().rows.len(),
3385                2,
3386                "{}",
3387                request.table_name
3388            );
3389        }
3390    }
3391
3392    #[test]
3393    fn test_exponential_histogram_rejects_temporality_before_stale_point() {
3394        let stale = ExponentialHistogramDataPoint {
3395            flags: DataPointFlags::NoRecordedValueMask as u32,
3396            ..Default::default()
3397        };
3398        let request = metrics_request(vec![exponential_metric(
3399            "latency",
3400            vec![stale],
3401            AggregationTemporality::Unspecified,
3402        )]);
3403        let mut ctx = OtlpMetricCtx::default();
3404        let MetricsConversion {
3405            requests,
3406            rows,
3407            semantic_index,
3408            outcome,
3409            ..
3410        } = to_grpc_insert_requests(request, &mut ctx).unwrap();
3411
3412        assert_eq!(outcome.accepted_data_points, 0);
3413        assert_eq!(outcome.rejected_data_points, 1);
3414        assert_eq!(rows, 0);
3415        assert!(requests.inserts.is_empty());
3416        assert!(semantic_index.is_empty());
3417    }
3418
3419    #[test]
3420    fn test_exponential_histogram_storage_paths_share_struct() {
3421        use common_query::prelude::greptime_native_histogram;
3422
3423        let mut point = exponential_point();
3424        point.sum = Some(42.0);
3425        let request = metrics_request(vec![exponential_metric(
3426            "request.duration",
3427            vec![point],
3428            AggregationTemporality::Cumulative,
3429        )]);
3430        let mut ordinary_ctx = OtlpMetricCtx::default();
3431        let ordinary_requests = to_grpc_insert_requests(request.clone(), &mut ordinary_ctx)
3432            .unwrap()
3433            .requests;
3434        let mut metric_ctx = OtlpMetricCtx {
3435            with_metric_engine: true,
3436            ..Default::default()
3437        };
3438        let metric_requests = to_grpc_insert_requests(request, &mut metric_ctx)
3439            .unwrap()
3440            .requests;
3441
3442        let ordinary_insert = &ordinary_requests.inserts[0];
3443        let metric_insert = &metric_requests.inserts[0];
3444        assert_eq!(ordinary_insert.table_name, "request_duration");
3445        assert_eq!(metric_insert.table_name, "request_duration");
3446        let ordinary_rows = ordinary_insert.rows.as_ref().unwrap();
3447        let metric_rows = metric_insert.rows.as_ref().unwrap();
3448        let field = greptime_native_histogram();
3449        let ordinary_histogram = ordinary_rows.rows[0].values[ordinary_rows
3450            .schema
3451            .iter()
3452            .position(|column| column.column_name == field)
3453            .unwrap()]
3454        .clone();
3455        let metric_histogram = metric_rows.rows[0].values[metric_rows
3456            .schema
3457            .iter()
3458            .position(|column| column.column_name == field)
3459            .unwrap()]
3460        .clone();
3461        assert_eq!(ordinary_histogram, metric_histogram);
3462        assert!(matches!(
3463            ordinary_rows.rows[0].values[ordinary_rows
3464                .schema
3465                .iter()
3466                .position(|column| column.column_name == greptime_timestamp())
3467                .unwrap()]
3468            .value_data,
3469            Some(ValueData::TimestampMillisecondValue(2))
3470        ));
3471        assert!(matches!(
3472            metric_rows.rows[0].values[metric_rows
3473                .schema
3474                .iter()
3475                .position(|column| column.column_name == greptime_timestamp())
3476                .unwrap()]
3477            .value_data,
3478            Some(ValueData::TimestampNanosecondValue(2_000_000))
3479        ));
3480    }
3481
3482    #[test]
3483    fn test_rejection_message_is_bounded() {
3484        let request = metrics_request(vec![exponential_metric(
3485            "x".repeat(1_000),
3486            vec![ExponentialHistogramDataPoint::default()],
3487            AggregationTemporality::Unspecified,
3488        )]);
3489        let outcome = to_grpc_insert_requests(request, &mut OtlpMetricCtx::default())
3490            .unwrap()
3491            .outcome;
3492
3493        assert_eq!(outcome.rejected_data_points, 1);
3494        assert!(outcome.error_message.unwrap().len() <= MAX_REJECTION_MESSAGE_BYTES);
3495    }
3496
3497    #[test]
3498    fn test_rejection_message_reason_is_lazy_after_cap() {
3499        let mut outcome = MetricsIngestOutcome {
3500            error_message: Some("x".repeat(MAX_REJECTION_MESSAGE_BYTES)),
3501            ..Default::default()
3502        };
3503        let mut reason_built = false;
3504
3505        reject_data_points(&mut outcome, 1, || {
3506            reason_built = true;
3507            "unused".to_string()
3508        })
3509        .unwrap();
3510
3511        assert_eq!(outcome.rejected_data_points, 1);
3512        assert!(!reason_built);
3513    }
3514}