Skip to main content

servers/http/result/
prometheus_resp.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
15//! prom supply the prometheus HTTP API Server compliance
16use std::cmp::Ordering;
17use std::collections::{BTreeMap, HashMap};
18use std::hash::BuildHasher;
19use std::ops::Range;
20
21use arrow::array::{Array, ArrayRef, AsArray, StructArray};
22use arrow::buffer::BooleanBuffer;
23use arrow::compute::kernels::cmp::distinct;
24use arrow::datatypes::{Float64Type, TimestampMillisecondType};
25use arrow_schema::DataType;
26use axum::Json;
27use axum::http::HeaderValue;
28use axum::response::{IntoResponse, Response};
29use common_error::ext::ErrorExt;
30use common_error::status_code::StatusCode;
31use common_query::native_histogram::{
32    NativeHistogram, is_native_histogram_value_type, read_histogram,
33};
34use common_query::prometheus::{format_prometheus_float, is_prometheus_stale_nan};
35use common_query::promql_annotations::PromqlAnnotationCollector;
36use common_query::{Output, OutputData};
37use common_recordbatch::{RecordBatch, RecordBatches, SendableRecordBatchStream};
38use datatypes::arrow_array::string_array_value_at_index;
39use datatypes::prelude::ConcreteDataType;
40use datatypes::schema::Schema;
41use futures::TryStreamExt;
42use indexmap::map::RawEntryApiV1;
43use indexmap::map::raw_entry_v1::RawEntryMut;
44use indexmap::{Equivalent, IndexMap};
45use itertools::Either;
46use promql_parser::label::METRIC_NAME;
47use promql_parser::parser::value::ValueType;
48use ryu::Buffer;
49use serde::{Deserialize, Serialize, Serializer};
50use serde_json::Value;
51use snafu::{OptionExt, ResultExt};
52
53use crate::error::{
54    ArrowSnafu, CollectRecordbatchSnafu, DataFusionSnafu, Result, UnexpectedResultSnafu,
55    status_code_to_http_status,
56};
57use crate::http::header::{GREPTIME_DB_HEADER_METRICS, collect_plan_metrics};
58use crate::http::prometheus::{
59    PromData, PromNativeHistogram, PromQueryResult, PromSeriesMatrix, PromSeriesVector,
60    PrometheusResponse,
61};
62
63#[derive(Default)]
64struct PromSeriesSamples {
65    values: Vec<(f64, PromSampleValue)>,
66    histograms: Vec<(f64, PromNativeHistogram)>,
67}
68
69/// A sample value of the Prometheus HTTP API JSON format.
70///
71/// Samples read out of a query result are kept as `f64` and formatted while the
72/// response is serialized, which avoids one `String` per sample. Samples parsed
73/// from a JSON body keep their original spelling, so a response that is
74/// deserialized and serialized again is unchanged.
75#[derive(Debug, Clone, Deserialize, PartialEq)]
76#[serde(untagged)]
77pub enum PromSampleValue {
78    #[serde(skip_deserializing)]
79    Number(f64),
80    Text(String),
81}
82
83impl Serialize for PromSampleValue {
84    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
85        match self {
86            Self::Number(value) if value.is_finite() => {
87                serializer.serialize_str(Buffer::new().format_finite(*value))
88            }
89            Self::Number(value) if value.is_nan() => serializer.serialize_str("NaN"),
90            Self::Number(value) if value.is_sign_positive() => serializer.serialize_str("+Inf"),
91            Self::Number(_) => serializer.serialize_str("-Inf"),
92            Self::Text(value) => serializer.serialize_str(value),
93        }
94    }
95}
96
97impl PromSampleValue {
98    fn into_string(self) -> String {
99        match self {
100            Self::Number(value) => format_prometheus_sample_value(value),
101            Self::Text(value) => value,
102        }
103    }
104}
105
106fn prometheus_native_histogram(histogram: &NativeHistogram) -> Result<PromNativeHistogram> {
107    Ok(PromNativeHistogram {
108        count: format_prometheus_float(histogram.count),
109        sum: format_prometheus_float(histogram.sum),
110        buckets: histogram
111            .to_prometheus_buckets()
112            .context(UnexpectedResultSnafu {
113                reason: "native histogram cannot be converted to Prometheus buckets",
114            })?,
115    })
116}
117
118/// Formats a sample value for the Prometheus HTTP API.
119///
120/// Finite sample strings use ryu's shortest-roundtrip representation and may
121/// differ textually from previous Rust/Prometheus wire formatting; values parse
122/// identically. Non-finite values use Prometheus' `+Inf`, `-Inf` and `NaN`.
123fn format_prometheus_sample_value(value: f64) -> String {
124    if value.is_finite() {
125        Buffer::new().format_finite(value).to_string()
126    } else {
127        format_prometheus_float(value)
128    }
129}
130
131#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
132pub struct PrometheusJsonResponse {
133    pub status: String,
134    #[serde(skip_serializing_if = "PrometheusResponse::is_none")]
135    #[serde(default)]
136    pub data: PrometheusResponse,
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub error: Option<String>,
139    #[serde(skip_serializing_if = "Option::is_none")]
140    #[serde(rename = "errorType")]
141    pub error_type: Option<String>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub warnings: Option<Vec<String>>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub infos: Option<Vec<String>>,
146
147    #[serde(skip)]
148    pub status_code: Option<StatusCode>,
149    // placeholder for header value
150    #[serde(skip)]
151    #[serde(default)]
152    pub resp_metrics: HashMap<String, Value>,
153}
154
155impl IntoResponse for PrometheusJsonResponse {
156    fn into_response(self) -> Response {
157        let metrics = if self.resp_metrics.is_empty() {
158            None
159        } else {
160            serde_json::to_string(&self.resp_metrics).ok()
161        };
162
163        let http_code = self.status_code.map(|c| status_code_to_http_status(&c));
164
165        let mut resp = Json(self).into_response();
166
167        if let Some(http_code) = http_code {
168            *resp.status_mut() = http_code;
169        }
170
171        if let Some(m) = metrics.and_then(|m| HeaderValue::from_str(&m).ok()) {
172            resp.headers_mut().insert(&GREPTIME_DB_HEADER_METRICS, m);
173        }
174
175        resp
176    }
177}
178
179impl PrometheusJsonResponse {
180    pub fn error<S1>(error_type: StatusCode, reason: S1) -> Self
181    where
182        S1: Into<String>,
183    {
184        PrometheusJsonResponse {
185            status: "error".to_string(),
186            data: PrometheusResponse::None,
187            error: Some(reason.into()),
188            error_type: Some(error_type.to_string()),
189            warnings: None,
190            infos: None,
191            resp_metrics: Default::default(),
192            status_code: Some(error_type),
193        }
194    }
195
196    pub fn success(data: PrometheusResponse) -> Self {
197        PrometheusJsonResponse {
198            status: "success".to_string(),
199            data,
200            error: None,
201            error_type: None,
202            warnings: None,
203            infos: None,
204            resp_metrics: Default::default(),
205            status_code: None,
206        }
207    }
208
209    /// Adds collected PromQL warnings and infos to the response.
210    fn append_promql_annotations(&mut self, collector: &PromqlAnnotationCollector) {
211        let mut warnings = self.warnings.take().unwrap_or_default();
212        let mut infos = self.infos.take().unwrap_or_default();
213        collector.append_to(&mut warnings, &mut infos);
214        self.warnings = (!warnings.is_empty()).then_some(warnings);
215        self.infos = (!infos.is_empty()).then_some(infos);
216    }
217
218    /// Merges data and annotations from another expanded PromQL query response.
219    pub(crate) fn append_query_response(&mut self, mut other: Self) {
220        self.data.append(other.data);
221        merge_annotations(&mut self.warnings, other.warnings.take());
222        merge_annotations(&mut self.infos, other.infos.take());
223    }
224
225    /// Convert from `Result<Output>`
226    pub async fn from_query_result(
227        result: Result<Output>,
228        metric_name: Option<String>,
229        result_type: ValueType,
230        collector: Option<PromqlAnnotationCollector>,
231    ) -> Self {
232        // Hold the collector while a streaming result is consumed.
233        let response: Result<Self> = async {
234            let result = result?;
235            let mut resp =
236                match result.data {
237                    OutputData::RecordBatches(batches) => Self::success(
238                        Self::record_batches_to_data(batches, metric_name, result_type)?,
239                    ),
240                    OutputData::Stream(stream) => Self::success(
241                        Self::consume_stream_to_data(stream, metric_name, result_type).await?,
242                    ),
243                    OutputData::AffectedRows(_) => Self::error(
244                        StatusCode::Unexpected,
245                        "expected data result, but got affected rows",
246                    ),
247                };
248
249            if let Some(physical_plan) = result.meta.plan {
250                let mut result_map = HashMap::new();
251                let mut tmp = vec![&mut result_map];
252                collect_plan_metrics(&physical_plan, &mut tmp);
253
254                let re = result_map
255                    .into_iter()
256                    .map(|(k, v)| (k, Value::from(v)))
257                    .collect();
258                resp.resp_metrics = re;
259            }
260
261            Ok(resp)
262        }
263        .await;
264
265        let result_type_string = result_type.to_string();
266
267        let mut response = match response {
268            Ok(resp) => resp,
269            Err(err) => {
270                // Prometheus won't report error if querying nonexist label and metric
271                if err.status_code() == StatusCode::TableNotFound
272                    || err.status_code() == StatusCode::TableColumnNotFound
273                {
274                    Self::success(PrometheusResponse::PromData(PromData {
275                        result_type: result_type_string,
276                        ..Default::default()
277                    }))
278                } else {
279                    Self::error(err.status_code(), err.output_msg())
280                }
281            }
282        };
283        if let Some(collector) = collector {
284            response.append_promql_annotations(&collector);
285        }
286        response
287    }
288
289    /// Convert [RecordBatches] to [PromData]
290    fn record_batches_to_data(
291        batches: RecordBatches,
292        metric_name: Option<String>,
293        result_type: ValueType,
294    ) -> Result<PrometheusResponse> {
295        // Return empty result if no batches
296        if batches.iter().next().is_none() {
297            return Ok(empty_data(result_type));
298        }
299
300        let layout = ColumnLayout::infer(&batches.schema())?;
301
302        // Preserves the order of output tags.
303        // Tag order matters, e.g., after sorc and sort_desc, the output order must be kept.
304        let mut buffer = IndexMap::<Vec<(String, String)>, PromSeriesSamples>::new();
305
306        for batch in batches.iter() {
307            merge_batch(&mut buffer, &layout, batch, metric_name.as_deref())?;
308        }
309
310        samples_to_data(buffer, result_type)
311    }
312
313    /// Consume a streaming query result into [PromData].
314    ///
315    /// Every batch is merged into the per-series buffer and dropped before the
316    /// next one is polled, so the whole query result and the assembled series
317    /// never coexist in memory.
318    async fn consume_stream_to_data(
319        mut stream: SendableRecordBatchStream,
320        metric_name: Option<String>,
321        result_type: ValueType,
322    ) -> Result<PrometheusResponse> {
323        // An empty stream carries no batch to infer the column roles from, and
324        // reads as an empty result, like empty [RecordBatches].
325        let Some(first_batch) = stream.try_next().await.context(CollectRecordbatchSnafu)? else {
326            return Ok(empty_data(result_type));
327        };
328
329        let layout = ColumnLayout::infer(&stream.schema())?;
330
331        // Preserves the order of output tags.
332        // Tag order matters, e.g., after sorc and sort_desc, the output order must be kept.
333        let mut buffer = IndexMap::<Vec<(String, String)>, PromSeriesSamples>::new();
334
335        merge_batch(&mut buffer, &layout, &first_batch, metric_name.as_deref())?;
336        // Release the batch before polling the next one.
337        drop(first_batch);
338
339        while let Some(batch) = stream.try_next().await.context(CollectRecordbatchSnafu)? {
340            merge_batch(&mut buffer, &layout, &batch, metric_name.as_deref())?;
341        }
342
343        samples_to_data(buffer, result_type)
344    }
345}
346
347/// The empty data of a Prometheus HTTP API response of `result_type`.
348fn empty_data(result_type: ValueType) -> PrometheusResponse {
349    PrometheusResponse::PromData(PromData {
350        result_type: result_type.to_string(),
351        ..Default::default()
352    })
353}
354
355/// The role of every column of a query result.
356struct ColumnLayout {
357    timestamp_column_index: usize,
358    /// The column holding the metric name of each row, when the plan declares one.
359    ///
360    /// A set operator reports the series of both its operands, so it names each row with the name
361    /// of the side the row came from instead of the one name the statement derives.
362    name_column_index: Option<usize>,
363    tag_column_indices: Vec<usize>,
364    tag_names: Vec<String>,
365    first_field_column_index: Option<usize>,
366    native_histogram_column_index: Option<usize>,
367}
368
369impl ColumnLayout {
370    /// Infer the role of every column from `schema`.
371    // TODO(ruihang): wish there is a better way to do this.
372    fn infer(schema: &Schema) -> Result<Self> {
373        let mut timestamp_column_index = None;
374        let mut name_column_index: Option<usize> = None;
375        let mut tag_column_indices = Vec::new();
376        let mut first_field_column_index = None;
377        let mut native_histogram_column_index = None;
378
379        for (i, column) in schema.column_schemas().iter().enumerate() {
380            // The declaration, not the column name, says a column holds metric names: an operation
381            // may name a column of values `__name__`, and those values are not names.
382            if column.is_metric_name() {
383                if !matches!(column.data_type, ConcreteDataType::String(_)) {
384                    return UnexpectedResultSnafu {
385                        reason: format!(
386                            "metric name column {} is not a string column",
387                            column.name
388                        ),
389                    }
390                    .fail();
391                }
392                if name_column_index.replace(i).is_some() {
393                    return UnexpectedResultSnafu {
394                        reason: format!(
395                            "result declares more than one metric name column, {} among them",
396                            column.name
397                        ),
398                    }
399                    .fail();
400                }
401                continue;
402            }
403            match column.data_type {
404                ConcreteDataType::Timestamp(datatypes::types::TimestampType::Millisecond(_))
405                    if timestamp_column_index.is_none() =>
406                {
407                    timestamp_column_index = Some(i);
408                }
409                // Treat all value types as field
410                ConcreteDataType::Float32(_)
411                | ConcreteDataType::Float64(_)
412                | ConcreteDataType::Int8(_)
413                | ConcreteDataType::Int16(_)
414                | ConcreteDataType::Int32(_)
415                | ConcreteDataType::Int64(_)
416                | ConcreteDataType::UInt8(_)
417                | ConcreteDataType::UInt16(_)
418                | ConcreteDataType::UInt32(_)
419                | ConcreteDataType::UInt64(_)
420                    if first_field_column_index.is_none() =>
421                {
422                    first_field_column_index = Some(i);
423                }
424                _ if native_histogram_column_index.is_none()
425                    && is_native_histogram_value_type(&column.data_type) =>
426                {
427                    native_histogram_column_index = Some(i);
428                }
429                ConcreteDataType::String(_) => {
430                    tag_column_indices.push(i);
431                }
432                _ => {}
433            }
434        }
435
436        let timestamp_column_index = timestamp_column_index.context(UnexpectedResultSnafu {
437            reason: "no timestamp column found".to_string(),
438        })?;
439        if first_field_column_index.is_none() && native_histogram_column_index.is_none() {
440            return UnexpectedResultSnafu {
441                reason: "no value column found".to_string(),
442            }
443            .fail();
444        }
445
446        let tag_names = tag_column_indices
447            .iter()
448            .map(|index| schema.column_name_by_index(*index).to_string())
449            .collect::<Vec<_>>();
450
451        Ok(Self {
452            timestamp_column_index,
453            name_column_index,
454            tag_column_indices,
455            tag_names,
456            first_field_column_index,
457            native_histogram_column_index,
458        })
459    }
460}
461
462/// The lookup key of a series in the per-series sample buffer.
463///
464/// The blanket `Equivalent` implementation compares through `Borrow`, which
465/// `Vec<(String, String)>` cannot provide for labels borrowed from a batch, so
466/// this wrapper compares the labels itself. It is built for a single lookup and
467/// hashes like the owned key it looks up.
468struct SeriesKeyLookup<'a>(&'a [(&'a str, &'a str)]);
469
470impl Equivalent<Vec<(String, String)>> for SeriesKeyLookup<'_> {
471    fn equivalent(&self, key: &Vec<(String, String)>) -> bool {
472        self.0.len() == key.len()
473            && self
474                .0
475                .iter()
476                .zip(key)
477                .all(|((name, value), (key_name, key_value))| {
478                    *name == key_name.as_str() && *value == key_value.as_str()
479                })
480    }
481}
482
483/// Merge the rows of one batch into the per-series sample buffer.
484fn merge_batch(
485    buffer: &mut IndexMap<Vec<(String, String)>, PromSeriesSamples>,
486    layout: &ColumnLayout,
487    batch: &RecordBatch,
488    metric_name: Option<&str>,
489) -> Result<()> {
490    // Scratch buffer of the labels of the series being read, borrowed from
491    // `batch` and `layout` and refilled for every series that is not in
492    // `buffer` yet, so looking a series up allocates nothing and only a series
493    // that is new allocates its labels.
494    let mut tags: Vec<(&str, &str)> = Vec::with_capacity(layout.tag_column_indices.len() + 1);
495
496    // prepare things...
497    let tag_columns = layout
498        .tag_column_indices
499        .iter()
500        .map(|i| batch.column(*i))
501        .collect::<Vec<_>>();
502    // The plan's own name column replaces the one name derived from the statement, because the rows
503    // of one result may carry different names. It is a label of the series it names, so the runs of
504    // rows sharing their labels break where it changes.
505    let name_column = layout.name_column_index.map(|index| batch.column(index));
506    let run_columns = if let Some(name_column) = name_column {
507        tag_columns
508            .iter()
509            .copied()
510            .chain(std::iter::once(name_column))
511            .collect::<Vec<_>>()
512    } else {
513        tag_columns.clone()
514    };
515    let timestamp_column = batch
516        .column(layout.timestamp_column_index)
517        .as_primitive::<TimestampMillisecondType>();
518
519    let field_array = layout
520        .first_field_column_index
521        .map(|index| arrow::compute::cast(batch.column(index), &DataType::Float64))
522        .transpose()
523        .context(ArrowSnafu)?;
524    let field_column = field_array
525        .as_ref()
526        .map(|array| array.as_primitive::<Float64Type>());
527    let native_histogram_column = layout
528        .native_histogram_column_index
529        .map(|index| {
530            batch
531                .column(index)
532                .as_any()
533                .downcast_ref::<StructArray>()
534                .with_context(|| UnexpectedResultSnafu {
535                    reason: "native histogram column is not a struct array",
536                })
537        })
538        .transpose()?;
539
540    // Read the labels once per run of rows that share them instead of
541    // once per row. `label_runs` finds every boundary, so the probe only
542    // decides whether looking for runs is worth its cost.
543    let label_runs = if prefer_label_runs(&run_columns, batch.num_rows()) {
544        Either::Left(label_runs(&run_columns, batch.num_rows())?.into_iter())
545    } else {
546        Either::Right((0..batch.num_rows()).map(|row| row..row + 1))
547    };
548
549    // assemble rows
550    for run in label_runs {
551        let mut run_entry_index = None;
552        for row_index in run {
553            let value = field_column.and_then(|field_column| {
554                if !field_column.is_valid(row_index) {
555                    return None;
556                }
557                let value = field_column.value(row_index);
558                (!is_prometheus_stale_nan(value))
559                    .then_some((timestamp_column.value(row_index), value))
560            });
561            let histogram = native_histogram_column
562                .and_then(|column| {
563                    read_histogram(column, row_index)
564                        .context(DataFusionSnafu)
565                        .transpose()
566                })
567                .transpose()?
568                .filter(|histogram| !is_prometheus_stale_nan(histogram.sum))
569                .map(|histogram| {
570                    prometheus_native_histogram(&histogram)
571                        .map(|histogram| (timestamp_column.value(row_index), histogram))
572                })
573                .transpose()?;
574
575            if value.is_none() && histogram.is_none() {
576                continue;
577            }
578
579            let entry_index = match run_entry_index {
580                Some(index) => index,
581                None => {
582                    // retrieve tags
583                    tags.clear();
584                    if let Some(name_column) = name_column {
585                        // A plan that names its rows says so with a column: a row it names reports
586                        // its own name, and a row it leaves unnamed reports none. An empty name is
587                        // one it leaves unnamed - a label with no value is not a label, which is
588                        // how Prometheus reports it too.
589                        if let Some(row_name) = string_array_value_at_index(name_column, row_index)
590                            && !row_name.is_empty()
591                        {
592                            tags.push((METRIC_NAME, row_name));
593                        }
594                    } else if let Some(metric_name) = metric_name {
595                        tags.push((METRIC_NAME, metric_name));
596                    }
597                    for (tag_column, tag_name) in tag_columns.iter().zip(layout.tag_names.iter()) {
598                        if let Some(tag_value) = string_array_value_at_index(tag_column, row_index)
599                        {
600                            tags.push((tag_name.as_str(), tag_value));
601                        }
602                    }
603
604                    // Borrowed and owned labels hash the same: both
605                    // hash their `str` contents, so this hash serves the
606                    // lookup and the insertion of a new series below.
607                    let hash = buffer.hasher().hash_one(&tags);
608                    let entry = buffer
609                        .raw_entry_mut_v1()
610                        .from_key_hashed_nocheck(hash, &SeriesKeyLookup(tags.as_slice()));
611                    let index = entry.index();
612                    if let RawEntryMut::Vacant(entry) = entry {
613                        // A series that is new to the buffer takes
614                        // ownership of its labels.
615                        let key = tags
616                            .iter()
617                            .map(|(name, value)| (name.to_string(), value.to_string()))
618                            .collect::<Vec<_>>();
619                        entry.insert_hashed_nocheck(hash, key, PromSeriesSamples::default());
620                    }
621                    run_entry_index = Some(index);
622                    index
623                }
624            };
625            let samples = &mut buffer[entry_index];
626            if let Some((timestamp_millis, histogram)) = histogram {
627                samples
628                    .histograms
629                    .push((timestamp_millis as f64 / 1000.0, histogram));
630            } else if let Some((timestamp_millis, value)) = value {
631                samples.values.push((
632                    timestamp_millis as f64 / 1000.0,
633                    PromSampleValue::Number(value),
634                ));
635            }
636        }
637    }
638    Ok(())
639}
640
641/// Assemble the per-series samples of `buffer` into the data of a Prometheus
642/// HTTP API response of `result_type`.
643fn samples_to_data(
644    buffer: IndexMap<Vec<(String, String)>, PromSeriesSamples>,
645    result_type: ValueType,
646) -> Result<PrometheusResponse> {
647    // initialize result to return
648    let mut result = match result_type {
649        ValueType::Vector => PromQueryResult::Vector(vec![]),
650        ValueType::Matrix => PromQueryResult::Matrix(vec![]),
651        ValueType::Scalar => PromQueryResult::Scalar(None),
652        ValueType::String => PromQueryResult::String(None),
653    };
654
655    // accumulate data into result
656    buffer.into_iter().for_each(|(tags, mut samples)| {
657        let metric = tags.into_iter().collect::<BTreeMap<String, String>>();
658        match result {
659            PromQueryResult::Vector(ref mut v) => {
660                let histogram = samples.histograms.pop();
661                let value = if histogram.is_none() {
662                    samples
663                        .values
664                        .pop()
665                        .map(|(timestamp, value)| (timestamp, value.into_string()))
666                } else {
667                    None
668                };
669                v.push(PromSeriesVector {
670                    metric,
671                    value,
672                    histogram,
673                });
674            }
675            PromQueryResult::Matrix(ref mut v) => {
676                // sort values by timestamp
677                if !samples.values.is_sorted_by(|a, b| a.0 <= b.0) {
678                    samples
679                        .values
680                        .sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
681                }
682                if !samples.histograms.is_sorted_by(|a, b| a.0 <= b.0) {
683                    samples
684                        .histograms
685                        .sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
686                }
687
688                v.push(PromSeriesMatrix {
689                    metric,
690                    values: samples.values,
691                    histograms: samples.histograms,
692                });
693            }
694            PromQueryResult::Scalar(ref mut v) => {
695                *v = samples
696                    .values
697                    .pop()
698                    .map(|(timestamp, value)| (timestamp, value.into_string()));
699            }
700            PromQueryResult::String(ref mut _v) => {
701                // TODO(ruihang): Not supported yet
702            }
703        }
704    });
705
706    // sort matrix by metric
707    // see: https://prometheus.io/docs/prometheus/3.5/querying/api/#range-vectors
708    if let PromQueryResult::Matrix(ref mut v) = result {
709        v.sort_by(|a, b| a.metric.cmp(&b.metric));
710    }
711
712    let result_type_string = result_type.to_string();
713    let data = PrometheusResponse::PromData(PromData {
714        result_type: result_type_string,
715        result,
716    });
717
718    Ok(data)
719}
720
721/// Ranges of consecutive rows whose label values are all equal.
722///
723/// `arrow::compute::partition` computes the same ranges, but its contract takes
724/// lexicographically sorted columns, which query output is not: range queries
725/// run without the plan's output sort, and `sort`/`topk` order by value.
726/// `distinct` is element-wise, so it holds for any row order, and its null
727/// handling is the one a series key needs: a null label and an empty one are
728/// distinct, and two nulls are not.
729fn label_runs(columns: &[&ArrayRef], rows: usize) -> Result<Vec<Range<usize>>> {
730    let mut boundaries: Option<BooleanBuffer> = None;
731    if rows >= 2 {
732        for column in columns {
733            let changed = distinct(&column.slice(0, rows - 1), &column.slice(1, rows - 1))
734                .context(ArrowSnafu)?;
735            boundaries = Some(match boundaries {
736                Some(accumulated) => &accumulated | changed.values(),
737                None => changed.values().clone(),
738            });
739        }
740    }
741
742    let mut runs = Vec::new();
743    let mut start = 0;
744    for boundary in boundaries.iter().flat_map(BooleanBuffer::set_indices) {
745        runs.push(start..boundary + 1);
746        start = boundary + 1;
747    }
748    runs.push(start..rows);
749    Ok(runs)
750}
751
752/// Decides whether to group the rows of a batch into runs that share their
753/// label values.
754///
755/// Sampling adjacent row pairs keeps the decision independent of the batch
756/// size. Probe positions come from a xorshift sequence instead of a fixed
757/// stride, which would alias with periodic series layouts. A wrong guess only
758/// costs time: `partition` still validates every boundary, and the row-by-row
759/// path builds the labels of every row.
760fn prefer_label_runs(columns: &[&ArrayRef], rows: usize) -> bool {
761    if columns.is_empty() {
762        return true;
763    }
764    if rows < 2 {
765        return false;
766    }
767    let mut position = 0x9e37_79b9_u32;
768    let mut changes = 0;
769    for _ in 0..8 {
770        position ^= position << 13;
771        position ^= position >> 17;
772        position ^= position << 5;
773        let row = position as usize % (rows - 1);
774        if columns.iter().any(|column| {
775            string_array_value_at_index(column, row) != string_array_value_at_index(column, row + 1)
776        }) {
777            changes += 1;
778            if changes > 2 {
779                return false;
780            }
781        }
782    }
783    true
784}
785
786fn merge_annotations(target: &mut Option<Vec<String>>, source: Option<Vec<String>>) {
787    let Some(source) = source else {
788        return;
789    };
790    let target = target.get_or_insert_default();
791    target.extend(source);
792    target.sort();
793    target.dedup();
794}
795
796#[cfg(test)]
797mod tests {
798    use std::sync::Arc;
799
800    use arrow::array::StringViewArray;
801    use common_query::native_histogram::{
802        CUSTOM_BUCKETS_SCHEMA, CounterResetHint, NativeHistogram, Span, build_histogram_array,
803        native_histogram_value_type,
804    };
805    use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
806    use common_query::promql_annotations::{
807        PromqlAnnotationCollector, promql_annotation_collector,
808    };
809    use common_recordbatch::{RecordBatch, RecordBatches};
810    use datatypes::data_type::ConcreteDataType;
811    use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
812    use datatypes::vectors::{
813        Float64Vector, StringVector, StructVector, TimestampMillisecondVector, VectorRef,
814    };
815
816    use super::*;
817
818    #[tokio::test]
819    async fn empty_stream_reads_as_empty_data() {
820        // No timestamp column on purpose: if the empty-stream short-circuit ran
821        // after `ColumnLayout::infer`, inference would fail with
822        // "no timestamp column found" instead of returning empty data.
823        let schema = Arc::new(Schema::new(vec![
824            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
825            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
826        ]));
827        let stream = RecordBatches::try_new(schema, vec![]).unwrap().as_stream();
828
829        let response =
830            PrometheusJsonResponse::consume_stream_to_data(stream, None, ValueType::Matrix).await;
831
832        assert!(matches!(
833            response.unwrap(),
834            PrometheusResponse::PromData(PromData {
835                result: PromQueryResult::Matrix(series),
836                ..
837            }) if series.is_empty()
838        ));
839    }
840
841    #[tokio::test]
842    async fn stream_result_matches_record_batches_result() {
843        let schema = Arc::new(Schema::new(vec![
844            ColumnSchema::new(
845                "timestamp",
846                ConcreteDataType::timestamp_millisecond_datatype(),
847                false,
848            ),
849            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
850            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
851        ]));
852        // Two batches, with series "a" split across them: batch 0 holds its
853        // later samples, batch 1 its earlier ones plus series "b", so streaming
854        // must merge samples of one series across a batch boundary.
855        let batch_rows: [Vec<(&str, i64, f64)>; 2] = [
856            vec![
857                ("a", 4_000, 0.0),
858                ("a", 5_000, 1.0),
859                ("a", 6_000, 2.0),
860                ("a", 7_000, 3.0),
861            ],
862            vec![
863                ("a", 0, 4.0),
864                ("a", 1_000, 5.0),
865                ("b", 2_000, 6.0),
866                ("b", 3_000, 7.0),
867            ],
868        ];
869        let batches: Vec<_> = batch_rows
870            .into_iter()
871            .map(|rows| {
872                RecordBatch::new(
873                    schema.clone(),
874                    vec![
875                        Arc::new(TimestampMillisecondVector::from_values(
876                            rows.iter().map(|(_, ts, _)| *ts),
877                        )) as _,
878                        Arc::new(StringVector::from(
879                            rows.iter()
880                                .map(|(host, _, _)| Some(*host))
881                                .collect::<Vec<_>>(),
882                        )) as _,
883                        Arc::new(Float64Vector::from_values(rows.iter().map(|(_, _, v)| *v))) as _,
884                    ],
885                )
886                .unwrap()
887            })
888            .collect();
889
890        let streamed = PrometheusJsonResponse::consume_stream_to_data(
891            RecordBatches::try_new(schema.clone(), batches.clone())
892                .unwrap()
893                .as_stream(),
894            Some("metric".to_string()),
895            ValueType::Matrix,
896        )
897        .await
898        .unwrap();
899        let eager = PrometheusJsonResponse::record_batches_to_data(
900            RecordBatches::try_new(schema, batches).unwrap(),
901            Some("metric".to_string()),
902            ValueType::Matrix,
903        )
904        .unwrap();
905
906        assert_eq!(
907            serde_json::to_value(&streamed).unwrap(),
908            serde_json::to_value(&eager).unwrap()
909        );
910        let PrometheusResponse::PromData(PromData {
911            result: PromQueryResult::Matrix(series),
912            ..
913        }) = streamed
914        else {
915            panic!("expected matrix response");
916        };
917        assert_eq!(series.len(), 2);
918        // Pin the merged content of the cross-batch series, not just the
919        // two-path agreement: both paths share merge_batch, so a regression
920        // there could make them agree on the same wrong output.
921        let series_a = series
922            .iter()
923            .find(|s| s.metric.get("host").map(String::as_str) == Some("a"))
924            .unwrap();
925        let samples_a: Vec<(i64, f64)> = series_a
926            .values
927            .iter()
928            .map(|(ts, value)| {
929                let PromSampleValue::Number(v) = value else {
930                    panic!("expected numeric sample");
931                };
932                ((ts * 1000.0) as i64, *v)
933            })
934            .collect();
935        assert_eq!(
936            samples_a,
937            vec![
938                (0, 4.0),
939                (1_000, 5.0),
940                (4_000, 0.0),
941                (5_000, 1.0),
942                (6_000, 2.0),
943                (7_000, 3.0),
944            ]
945        );
946    }
947
948    #[tokio::test]
949    async fn stream_mixed_histogram_result_matches_record_batches_result() {
950        let schema = Arc::new(Schema::new(vec![
951            ColumnSchema::new(
952                "timestamp",
953                ConcreteDataType::timestamp_millisecond_datatype(),
954                false,
955            ),
956            ColumnSchema::new("kind", ConcreteDataType::string_datatype(), false),
957            ColumnSchema::new("float", ConcreteDataType::float64_datatype(), true),
958            ColumnSchema::new("histogram", native_histogram_value_type().clone(), true),
959        ]));
960        // The float series splits across the batch boundary so streaming must
961        // merge its samples like the eager path; the histogram row only arrives
962        // in the second batch.
963        let first = RecordBatch::new(
964            schema.clone(),
965            vec![
966                Arc::new(TimestampMillisecondVector::from_values([1_000, 2_000])) as _,
967                Arc::new(StringVector::from(vec![Some("float"); 2])) as _,
968                Arc::new(Float64Vector::from(vec![Some(1.25), Some(0.5)])) as _,
969                histogram_vector(&[None, None]),
970            ],
971        )
972        .unwrap();
973        let second = RecordBatch::new(
974            schema.clone(),
975            vec![
976                Arc::new(TimestampMillisecondVector::from_values([3_000, 3_000])) as _,
977                Arc::new(StringVector::from(vec![Some("float"), Some("histogram")])) as _,
978                Arc::new(Float64Vector::from(vec![Some(2.0), None])) as _,
979                histogram_vector(&[None, Some(sample_histogram())]),
980            ],
981        )
982        .unwrap();
983
984        let streamed = PrometheusJsonResponse::consume_stream_to_data(
985            RecordBatches::try_new(schema.clone(), vec![first.clone(), second.clone()])
986                .unwrap()
987                .as_stream(),
988            Some("mixed_metric".to_string()),
989            ValueType::Vector,
990        )
991        .await
992        .unwrap();
993        let eager = PrometheusJsonResponse::record_batches_to_data(
994            RecordBatches::try_new(schema, vec![first, second]).unwrap(),
995            Some("mixed_metric".to_string()),
996            ValueType::Vector,
997        )
998        .unwrap();
999
1000        assert_eq!(
1001            serde_json::to_value(&streamed).unwrap(),
1002            serde_json::to_value(&eager).unwrap()
1003        );
1004        let PrometheusResponse::PromData(PromData {
1005            result: PromQueryResult::Vector(series),
1006            ..
1007        }) = streamed
1008        else {
1009            panic!("expected vector response");
1010        };
1011        assert_eq!(series.len(), 2);
1012        let histogram = series
1013            .iter()
1014            .find(|series| series.metric["kind"] == "histogram")
1015            .unwrap();
1016        assert!(histogram.histogram.is_some());
1017        assert!(histogram.value.is_none());
1018    }
1019
1020    /// A stream that lazily creates one batch per poll and asserts the previous
1021    /// batch has been released before yielding the next one.
1022    ///
1023    /// Unlike `RecordBatches::as_stream`, this stream does not retain yielded
1024    /// batches, so it can verify the consumer drops each batch before polling
1025    /// the next one.
1026    struct LazyDropCheckingStream {
1027        schema: SchemaRef,
1028        batch_index: usize,
1029        /// Weak reference to the Arc wrapping the previously yielded batch.
1030        /// The consumer must have dropped its clone by the next poll.
1031        last_batch: Option<std::sync::Weak<RecordBatch>>,
1032    }
1033
1034    impl LazyDropCheckingStream {
1035        fn new(schema: SchemaRef) -> Self {
1036            Self {
1037                schema,
1038                batch_index: 0,
1039                last_batch: None,
1040            }
1041        }
1042
1043        fn make_batch(&self) -> RecordBatch {
1044            let base = self.batch_index as i64 * 1000;
1045            RecordBatch::new(
1046                self.schema.clone(),
1047                vec![
1048                    Arc::new(TimestampMillisecondVector::from_values([base])) as _,
1049                    Arc::new(StringVector::from(vec![Some("host")])) as _,
1050                    Arc::new(Float64Vector::from_values([base as f64])) as _,
1051                ],
1052            )
1053            .unwrap()
1054        }
1055    }
1056
1057    impl futures::Stream for LazyDropCheckingStream {
1058        type Item = common_recordbatch::error::Result<RecordBatch>;
1059
1060        fn poll_next(
1061            mut self: std::pin::Pin<&mut Self>,
1062            _cx: &mut std::task::Context<'_>,
1063        ) -> std::task::Poll<Option<Self::Item>> {
1064            // The consumer must have released the previous batch before polling
1065            // for the next one.
1066            if let Some(weak) = &self.last_batch {
1067                assert!(
1068                    weak.upgrade().is_none(),
1069                    "previous batch was not released before polling the next one"
1070                );
1071            }
1072
1073            if self.batch_index >= 3 {
1074                return std::task::Poll::Ready(None);
1075            }
1076
1077            let batch = Arc::new(self.make_batch());
1078            self.last_batch = Some(Arc::downgrade(&batch));
1079            self.batch_index += 1;
1080            std::task::Poll::Ready(Some(Ok((*batch).clone())))
1081        }
1082    }
1083
1084    impl common_recordbatch::RecordBatchStream for LazyDropCheckingStream {
1085        fn schema(&self) -> SchemaRef {
1086            self.schema.clone()
1087        }
1088
1089        fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> {
1090            None
1091        }
1092
1093        fn metrics(&self) -> Option<common_recordbatch::adapter::RecordBatchMetrics> {
1094            None
1095        }
1096    }
1097
1098    #[tokio::test]
1099    async fn stream_drops_each_batch_before_polling_next() {
1100        let schema = Arc::new(Schema::new(vec![
1101            ColumnSchema::new(
1102                "timestamp",
1103                ConcreteDataType::timestamp_millisecond_datatype(),
1104                false,
1105            ),
1106            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
1107            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
1108        ]));
1109        let stream = LazyDropCheckingStream::new(schema);
1110
1111        let response = PrometheusJsonResponse::consume_stream_to_data(
1112            Box::pin(stream),
1113            None,
1114            ValueType::Matrix,
1115        )
1116        .await;
1117
1118        assert!(matches!(
1119            response.unwrap(),
1120            PrometheusResponse::PromData(PromData {
1121                result: PromQueryResult::Matrix(series),
1122                ..
1123            }) if series.len() == 1 && series[0].values.len() == 3
1124        ));
1125    }
1126
1127    #[tokio::test]
1128    async fn query_response_preserves_and_merges_promql_annotations() {
1129        let query_id = "query_response_preserves_and_merges_promql_annotations";
1130        let left = promql_annotation_collector(query_id);
1131        left.record_warning("shared warning");
1132        left.record_info("left info");
1133        let mut response = PrometheusJsonResponse::from_query_result(
1134            Ok(Output::new_with_record_batches(RecordBatches::empty())),
1135            None,
1136            ValueType::Vector,
1137            Some(left),
1138        )
1139        .await;
1140
1141        let right = PromqlAnnotationCollector::default();
1142        right.record_warning("shared warning");
1143        right.record_info("right info");
1144        let mut other = PrometheusJsonResponse::success(PrometheusResponse::None);
1145        other.append_promql_annotations(&right);
1146        response.append_query_response(other);
1147
1148        assert_eq!(response.warnings, Some(vec!["shared warning".to_string()]));
1149        assert_eq!(
1150            response.infos,
1151            Some(vec!["left info".to_string(), "right info".to_string()])
1152        );
1153        let json = serde_json::to_value(response).unwrap();
1154        assert_eq!(json["warnings"], serde_json::json!(["shared warning"]));
1155        assert_eq!(
1156            json["infos"],
1157            serde_json::json!(["left info", "right info"])
1158        );
1159    }
1160
1161    fn sample_histogram() -> NativeHistogram {
1162        NativeHistogram {
1163            schema: 0,
1164            zero_threshold: 0.001,
1165            sum: 3.0,
1166            reset_hint: CounterResetHint::Unknown,
1167            start_timestamp: Some(0),
1168            custom_values: vec![],
1169            positive_spans: vec![Span {
1170                offset: 0,
1171                length: 1,
1172            }],
1173            negative_spans: vec![],
1174            count: 2.0,
1175            zero_count: 1.0,
1176            positive_buckets: vec![1.0],
1177            negative_buckets: vec![],
1178        }
1179    }
1180
1181    fn histogram_vector(values: &[Option<NativeHistogram>]) -> VectorRef {
1182        let histogram_array = build_histogram_array(values);
1183        let histogram_array = histogram_array
1184            .as_any()
1185            .downcast_ref::<StructArray>()
1186            .unwrap()
1187            .clone();
1188        let ConcreteDataType::Struct(histogram_type) = native_histogram_value_type().clone() else {
1189            unreachable!("native histogram type must be a struct")
1190        };
1191        Arc::new(StructVector::try_new(histogram_type, histogram_array).unwrap())
1192    }
1193
1194    #[test]
1195    fn format_prometheus_sample_value_uses_ryu_for_finite_values() {
1196        let values = [
1197            1.5,
1198            0.1,
1199            1.0,
1200            0.0,
1201            -0.0,
1202            100.0,
1203            1e-6,
1204            1e-7,
1205            1e21,
1206            1e30,
1207            f64::MAX,
1208            f64::MIN_POSITIVE,
1209        ];
1210
1211        for value in values {
1212            let output = format_prometheus_sample_value(value);
1213            assert_eq!(output.parse::<f64>().unwrap().to_bits(), value.to_bits());
1214        }
1215
1216        // Representative integral values use ryu's explicit .0 form.
1217        assert_eq!(format_prometheus_sample_value(1.0), "1.0");
1218        assert_eq!(format_prometheus_sample_value(-0.0), "-0.0");
1219        assert_eq!(format_prometheus_sample_value(100.0), "100.0");
1220        assert_eq!(format_prometheus_sample_value(1e-6), "1e-6");
1221        assert_eq!(format_prometheus_sample_value(1e-7), "1e-7");
1222        assert_eq!(format_prometheus_sample_value(1e21), "1e21");
1223
1224        // These known shortest-roundtrip tie cases have different text but
1225        // remain numerically equivalent to Rust's representation.
1226        for value in [
1227            f64::from_bits(0x42374876e8000400),
1228            f64::from_bits(0x3ff0000800000000),
1229            f64::from_bits(0x430a8e5672bc7312),
1230        ] {
1231            let ryu_output = format_prometheus_sample_value(value);
1232            let std_output = value.to_string();
1233            assert_ne!(ryu_output, std_output);
1234            assert_eq!(ryu_output.parse::<f64>().unwrap(), value);
1235            assert_eq!(std_output.parse::<f64>().unwrap(), value);
1236        }
1237    }
1238
1239    #[test]
1240    fn format_prometheus_sample_value_spells_nonfinite_values_like_prometheus() {
1241        assert_eq!(format_prometheus_sample_value(f64::NAN), "NaN");
1242        assert_eq!(format_prometheus_sample_value(f64::INFINITY), "+Inf");
1243        assert_eq!(format_prometheus_sample_value(f64::NEG_INFINITY), "-Inf");
1244
1245        // Parsing a NaN does not preserve its payload bits, so NaN is checked
1246        // by its required semantic spelling rather than by to_bits().
1247        assert!(
1248            format_prometheus_sample_value(f64::NAN)
1249                .parse::<f64>()
1250                .unwrap()
1251                .is_nan()
1252        );
1253    }
1254
1255    #[test]
1256    fn sample_value_serialization_matches_eager_formatting() {
1257        let mut values = vec![
1258            0.0,
1259            -0.0,
1260            f64::MAX,
1261            f64::MIN,
1262            f64::MIN_POSITIVE,
1263            f64::from_bits(1),
1264            1e-7,
1265            1e21,
1266            f64::NAN,
1267            f64::INFINITY,
1268            f64::NEG_INFINITY,
1269        ];
1270        let mut bits = 0x1234_5678_9876_5432_u64;
1271        for _ in 0..1000 {
1272            bits ^= bits << 13;
1273            bits ^= bits >> 7;
1274            bits ^= bits << 17;
1275            values.push(f64::from_bits(bits));
1276        }
1277        for value in values {
1278            assert_eq!(
1279                serde_json::to_string(&PromSampleValue::Number(value)).unwrap(),
1280                serde_json::to_string(&format_prometheus_sample_value(value)).unwrap()
1281            );
1282        }
1283        for value in ["1.00", "+Inf", "-0", "NaN", "not-a-number", "", "\"\\\n"] {
1284            let json = serde_json::to_string(value).unwrap();
1285            let parsed: PromSampleValue = serde_json::from_str(&json).unwrap();
1286            assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
1287        }
1288        for value in ["1", "null", "true", "[]", "{}"] {
1289            assert!(serde_json::from_str::<PromSampleValue>(value).is_err());
1290        }
1291    }
1292
1293    #[tokio::test]
1294    async fn matrix_response_body_matches_eagerly_formatted_json() {
1295        let schema = Arc::new(Schema::new(vec![
1296            ColumnSchema::new(
1297                "timestamp",
1298                ConcreteDataType::timestamp_millisecond_datatype(),
1299                false,
1300            ),
1301            ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
1302            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
1303        ]));
1304        let batches = RecordBatches::try_new(
1305            schema.clone(),
1306            vec![
1307                RecordBatch::new(
1308                    schema,
1309                    vec![
1310                        Arc::new(TimestampMillisecondVector::from_values([
1311                            1000, 2000, 3000, 4000, 5000,
1312                        ])) as _,
1313                        Arc::new(StringVector::from(vec![Some("a"); 5])) as _,
1314                        Arc::new(Float64Vector::from_values([
1315                            -0.0,
1316                            f64::NAN,
1317                            1e-7,
1318                            f64::INFINITY,
1319                            f64::NEG_INFINITY,
1320                        ])) as _,
1321                    ],
1322                )
1323                .unwrap(),
1324            ],
1325        )
1326        .unwrap();
1327        let actual = PrometheusJsonResponse::from_query_result(
1328            Ok(Output::new_with_record_batches(batches)),
1329            None,
1330            ValueType::Matrix,
1331            None,
1332        )
1333        .await;
1334        // Deserializing the expectation yields `PromSampleValue::Text`, so this
1335        // compares the deferred numeric encoding against eagerly built strings.
1336        let expected: PrometheusJsonResponse = serde_json::from_value(serde_json::json!({
1337            "status": "success",
1338            "data": {"resultType": "matrix", "result": [{
1339                "metric": {"host": "a"},
1340                "values": [[1.0, "-0.0"], [2.0, "NaN"], [3.0, "1e-7"], [4.0, "+Inf"], [5.0, "-Inf"]]
1341            }]}
1342        }))
1343        .unwrap();
1344        assert_eq!(
1345            serde_json::to_string(&actual).unwrap(),
1346            serde_json::to_string(&expected).unwrap()
1347        );
1348    }
1349
1350    #[test]
1351    fn matrix_response_preserves_ordinary_nan_and_filters_stale_markers() {
1352        let schema = Arc::new(Schema::new(vec![
1353            ColumnSchema::new(
1354                "timestamp",
1355                ConcreteDataType::timestamp_millisecond_datatype(),
1356                false,
1357            ),
1358            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1359        ]));
1360        let batch = RecordBatch::new(
1361            schema.clone(),
1362            vec![
1363                Arc::new(TimestampMillisecondVector::from_vec(vec![
1364                    1_000, 2_000, 3_000, 4_000,
1365                ])) as _,
1366                Arc::new(Float64Vector::from(vec![
1367                    Some(1.0),
1368                    Some(f64::from_bits(0x7ff8_0000_0000_0000)),
1369                    Some(f64::from_bits(0x7ff0_0000_0000_0002)),
1370                    None,
1371                ])) as _,
1372            ],
1373        )
1374        .unwrap();
1375        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1376
1377        let response =
1378            PrometheusJsonResponse::record_batches_to_data(batches, None, ValueType::Matrix)
1379                .unwrap();
1380        let PrometheusResponse::PromData(data) = response else {
1381            panic!("expected Prometheus data response");
1382        };
1383        let PromQueryResult::Matrix(series) = data.result else {
1384            panic!("expected matrix result");
1385        };
1386
1387        assert_eq!(series.len(), 1);
1388        assert_eq!(
1389            serde_json::to_value(&series[0].values).unwrap(),
1390            serde_json::json!([[1.0, "1.0"], [2.0, "NaN"]])
1391        );
1392    }
1393
1394    #[test]
1395    fn record_batches_to_data_formats_values_with_ryu() {
1396        let schema = Arc::new(Schema::new(vec![
1397            ColumnSchema::new(
1398                "timestamp",
1399                ConcreteDataType::timestamp_millisecond_datatype(),
1400                false,
1401            ),
1402            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1403        ]));
1404        let batch = RecordBatch::new(
1405            schema.clone(),
1406            vec![
1407                Arc::new(TimestampMillisecondVector::from_vec(vec![
1408                    1_000, 2_000, 3_000, 4_000, 5_000, 6_000,
1409                ])) as _,
1410                Arc::new(Float64Vector::from(vec![
1411                    Some(0.0),
1412                    Some(-0.0),
1413                    Some(1.25),
1414                    Some(1e30),
1415                    Some(1e-7),
1416                    Some(f64::MAX),
1417                ])) as _,
1418            ],
1419        )
1420        .unwrap();
1421        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1422
1423        let response =
1424            PrometheusJsonResponse::record_batches_to_data(batches, None, ValueType::Matrix)
1425                .unwrap();
1426        let PrometheusResponse::PromData(PromData {
1427            result: PromQueryResult::Matrix(series),
1428            ..
1429        }) = response
1430        else {
1431            panic!("expected matrix response");
1432        };
1433
1434        assert_eq!(series.len(), 1);
1435        let input_values = [0.0, -0.0, 1.25, 1e30, 1e-7, f64::MAX];
1436        // Keep this expected-value generation independent from the production
1437        // formatter while still asserting the Arrow/batch-to-Prometheus path.
1438        let expected = input_values
1439            .into_iter()
1440            .enumerate()
1441            .map(|(index, value)| {
1442                let expected_value = if value.is_finite() {
1443                    let mut buffer = Buffer::new();
1444                    buffer.format_finite(value).to_string()
1445                } else {
1446                    value.to_string()
1447                };
1448                ((index + 1) as f64, expected_value)
1449            })
1450            .collect::<Vec<_>>();
1451        assert_eq!(
1452            serde_json::to_value(&series[0].values).unwrap(),
1453            serde_json::to_value(expected).unwrap()
1454        );
1455    }
1456
1457    #[test]
1458    fn record_batches_to_data_formats_nonfinite_values() {
1459        let schema = Arc::new(Schema::new(vec![
1460            ColumnSchema::new(
1461                "timestamp",
1462                ConcreteDataType::timestamp_millisecond_datatype(),
1463                false,
1464            ),
1465            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1466        ]));
1467        let batch = RecordBatch::new(
1468            schema.clone(),
1469            vec![
1470                Arc::new(TimestampMillisecondVector::from_vec(vec![
1471                    1_000, 2_000, 3_000,
1472                ])) as _,
1473                Arc::new(Float64Vector::from(vec![
1474                    Some(f64::INFINITY),
1475                    Some(f64::NEG_INFINITY),
1476                    Some(f64::NAN),
1477                ])) as _,
1478            ],
1479        )
1480        .unwrap();
1481        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1482
1483        let response =
1484            PrometheusJsonResponse::record_batches_to_data(batches, None, ValueType::Matrix)
1485                .unwrap();
1486        let PrometheusResponse::PromData(PromData {
1487            result: PromQueryResult::Matrix(series),
1488            ..
1489        }) = response
1490        else {
1491            panic!("expected matrix response");
1492        };
1493
1494        assert_eq!(series.len(), 1);
1495        assert_eq!(
1496            serde_json::to_value(&series[0].values).unwrap(),
1497            serde_json::json!([[1.0, "+Inf"], [2.0, "-Inf"], [3.0, "NaN"]])
1498        );
1499    }
1500
1501    #[test]
1502    fn record_batches_to_data_groups_clustered_series() {
1503        // Rows are clustered by series (a, b, a, a, b, c) and `a` is revisited
1504        // after `b`. The result must keep the first-occurrence order and
1505        // accumulate values per series.
1506        let schema = Arc::new(Schema::new(vec![
1507            ColumnSchema::new(
1508                "timestamp",
1509                ConcreteDataType::timestamp_millisecond_datatype(),
1510                false,
1511            ),
1512            ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
1513            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1514        ]));
1515        let batch = RecordBatch::new(
1516            schema.clone(),
1517            vec![
1518                Arc::new(TimestampMillisecondVector::from_vec(vec![
1519                    1_000, 2_000, 3_000, 4_000, 5_000, 6_000,
1520                ])) as _,
1521                Arc::new(StringVector::from(vec![
1522                    Some("a"),
1523                    Some("b"),
1524                    Some("a"),
1525                    Some("a"),
1526                    Some("b"),
1527                    Some("c"),
1528                ])) as _,
1529                Arc::new(Float64Vector::from(vec![
1530                    Some(1.0),
1531                    Some(2.0),
1532                    Some(3.0),
1533                    Some(4.0),
1534                    Some(5.0),
1535                    Some(6.0),
1536                ])) as _,
1537            ],
1538        )
1539        .unwrap();
1540        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1541
1542        let response = PrometheusJsonResponse::record_batches_to_data(
1543            batches,
1544            Some("metric".to_string()),
1545            ValueType::Vector,
1546        )
1547        .unwrap();
1548        let PrometheusResponse::PromData(PromData {
1549            result: PromQueryResult::Vector(series),
1550            ..
1551        }) = response
1552        else {
1553            panic!("expected vector response");
1554        };
1555
1556        assert_eq!(series.len(), 3);
1557        // Output order is first-occurrence order: a, b, c.
1558        assert_eq!(
1559            series
1560                .iter()
1561                .map(|series| series.metric["host"].as_str())
1562                .collect::<Vec<_>>(),
1563            vec!["a", "b", "c"]
1564        );
1565        // Vector results keep the last sample of each series.
1566        assert_eq!(series[0].value, Some((4.0, "4.0".to_string())));
1567        assert_eq!(series[1].value, Some((5.0, "5.0".to_string())));
1568        assert_eq!(series[2].value, Some((6.0, "6.0".to_string())));
1569    }
1570
1571    #[test]
1572    fn label_strategy_switches_preserve_all_rows_when_probes_miss_changes() {
1573        let schema = Arc::new(Schema::new(vec![
1574            ColumnSchema::new(
1575                "timestamp",
1576                ConcreteDataType::timestamp_millisecond_datatype(),
1577                false,
1578            ),
1579            ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
1580            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
1581        ]));
1582        let mut batches = Vec::new();
1583        let mut expected = BTreeMap::<String, Vec<(f64, PromSampleValue)>>::new();
1584        for layout in 0..3 {
1585            let labels = (0..1024)
1586                .map(|row| {
1587                    let alternating = match layout {
1588                        0 => true,
1589                        1 => row < 64,
1590                        _ => row >= 64,
1591                    };
1592                    if alternating && row % 2 != 0 {
1593                        "b"
1594                    } else {
1595                        "a"
1596                    }
1597                })
1598                .collect::<Vec<_>>();
1599            for (row, label) in labels.iter().enumerate() {
1600                let value = (layout * 1024 + row) as f64;
1601                expected
1602                    .entry((*label).to_string())
1603                    .or_default()
1604                    .push((value, PromSampleValue::Number(value)));
1605            }
1606            let batch = RecordBatch::new(
1607                schema.clone(),
1608                vec![
1609                    Arc::new(TimestampMillisecondVector::from_values(
1610                        (0..1024).map(|row| (layout * 1024 + row) as i64 * 1000),
1611                    )) as _,
1612                    Arc::new(StringVector::from(
1613                        labels.into_iter().map(Some).collect::<Vec<_>>(),
1614                    )) as _,
1615                    Arc::new(Float64Vector::from(
1616                        (0..1024)
1617                            .map(|row| Some((layout * 1024 + row) as f64))
1618                            .collect::<Vec<_>>(),
1619                    )) as _,
1620                ],
1621            )
1622            .unwrap();
1623            // The middle batch alternates only over a prefix the probes miss,
1624            // so it takes the run path even though most rows are not runs.
1625            assert_eq!(
1626                prefer_label_runs(&[batch.column(1)], batch.num_rows()),
1627                layout == 1
1628            );
1629            batches.push(batch);
1630        }
1631        let response = PrometheusJsonResponse::record_batches_to_data(
1632            RecordBatches::try_new(schema, batches).unwrap(),
1633            None,
1634            ValueType::Matrix,
1635        )
1636        .unwrap();
1637        let PrometheusResponse::PromData(PromData {
1638            result: PromQueryResult::Matrix(series),
1639            ..
1640        }) = response
1641        else {
1642            panic!("expected matrix response");
1643        };
1644        assert_eq!(series.len(), expected.len());
1645        for series in series {
1646            assert_eq!(series.metric.len(), 1);
1647            assert!(series.histograms.is_empty());
1648            assert_eq!(
1649                series.values,
1650                expected.remove(&series.metric["host"]).unwrap()
1651            );
1652        }
1653        assert!(expected.is_empty());
1654    }
1655
1656    #[test]
1657    fn label_runs_keep_null_and_empty_labels_apart_across_batches() {
1658        let schema = Arc::new(Schema::new(vec![
1659            ColumnSchema::new(
1660                "timestamp",
1661                ConcreteDataType::timestamp_millisecond_datatype(),
1662                false,
1663            ),
1664            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
1665            ColumnSchema::new("rack", ConcreteDataType::string_datatype(), true),
1666            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
1667        ]));
1668        // Two batches of two runs each, with only `rack` changing: a null label
1669        // and an empty one must not share a run, and the run opening the second
1670        // batch continues the series that ended the first one.
1671        let mut batches = Vec::new();
1672        let mut expected = vec![Vec::new(), Vec::new()];
1673        for (batch_index, leading_null) in [true, false].into_iter().enumerate() {
1674            let mut racks = Vec::new();
1675            let mut values = Vec::new();
1676            for row in 0..1024 {
1677                let value = (batch_index * 1024 + row) as f64;
1678                let null_rack = (row < 512) == leading_null;
1679                racks.push((!null_rack).then_some(""));
1680                values.push(Some(value));
1681                expected[usize::from(!null_rack)].push((value, PromSampleValue::Number(value)));
1682            }
1683            batches.push(
1684                RecordBatch::new(
1685                    schema.clone(),
1686                    vec![
1687                        Arc::new(TimestampMillisecondVector::from_values(
1688                            values.iter().map(|value| value.unwrap() as i64 * 1000),
1689                        )) as _,
1690                        Arc::new(StringVector::from(vec![Some("a"); 1024])) as _,
1691                        Arc::new(StringVector::from(racks)) as _,
1692                        Arc::new(Float64Vector::from(values)) as _,
1693                    ],
1694                )
1695                .unwrap(),
1696            );
1697        }
1698        for batch in &batches {
1699            assert!(prefer_label_runs(
1700                &[batch.column(1), batch.column(2)],
1701                batch.num_rows()
1702            ));
1703        }
1704        for series in &mut expected {
1705            series.sort_by(|left, right| left.0.total_cmp(&right.0));
1706        }
1707
1708        let response = PrometheusJsonResponse::record_batches_to_data(
1709            RecordBatches::try_new(schema, batches).unwrap(),
1710            None,
1711            ValueType::Matrix,
1712        )
1713        .unwrap();
1714        let PrometheusResponse::PromData(PromData {
1715            result: PromQueryResult::Matrix(series),
1716            ..
1717        }) = response
1718        else {
1719            panic!("expected matrix response");
1720        };
1721        assert_eq!(series.len(), 2);
1722        assert_eq!(
1723            series[0].metric,
1724            BTreeMap::from([("host".into(), "a".into())])
1725        );
1726        assert_eq!(series[0].values, expected[0]);
1727        assert_eq!(
1728            series[1].metric,
1729            BTreeMap::from([("host".into(), "a".into()), ("rack".into(), "".into())])
1730        );
1731        assert_eq!(series[1].values, expected[1]);
1732    }
1733
1734    #[test]
1735    fn matrix_response_is_independent_of_input_row_order() {
1736        // Range queries run without the plan's output sort, so this function sees
1737        // series interleaved across batches with timestamps out of order. The
1738        // serialized matrix must be the same either way.
1739        let schema = Arc::new(Schema::new(vec![
1740            ColumnSchema::new(
1741                "timestamp",
1742                ConcreteDataType::timestamp_millisecond_datatype(),
1743                false,
1744            ),
1745            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
1746            ColumnSchema::new("rack", ConcreteDataType::string_datatype(), true),
1747            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1748            ColumnSchema::new("histogram", native_histogram_value_type().clone(), true),
1749        ]));
1750        let histogram = |sum: f64| NativeHistogram {
1751            sum,
1752            ..sample_histogram()
1753        };
1754        // timestamp, host, rack, float value, histogram value
1755        type Row = (
1756            i64,
1757            Option<&'static str>,
1758            Option<&'static str>,
1759            Option<f64>,
1760            Option<NativeHistogram>,
1761        );
1762        let rows: Vec<Row> = vec![
1763            (1_000, Some("a"), Some("r"), Some(1.0), None),
1764            (3_000, Some("a"), Some("r"), Some(3.0), None),
1765            (2_000, Some("a"), Some("r"), Some(2.0), None),
1766            (5_000, Some("a"), None, Some(5.0), None),
1767            (4_000, Some("a"), None, Some(4.0), None),
1768            (7_000, Some(""), None, Some(7.0), None),
1769            (8_000, None, None, Some(8.0), None),
1770            (6_000, None, None, Some(6.0), None),
1771            (2_000, Some("h"), None, None, Some(histogram(20.0))),
1772            (1_000, Some("h"), None, None, Some(histogram(10.0))),
1773        ];
1774        let matrix = |order: &[usize], splits: &[usize]| {
1775            let batch = RecordBatch::new(
1776                schema.clone(),
1777                vec![
1778                    Arc::new(TimestampMillisecondVector::from_vec(
1779                        order.iter().map(|&row| rows[row].0).collect(),
1780                    )) as _,
1781                    Arc::new(StringVector::from(
1782                        order.iter().map(|&row| rows[row].1).collect::<Vec<_>>(),
1783                    )) as _,
1784                    Arc::new(StringVector::from(
1785                        order.iter().map(|&row| rows[row].2).collect::<Vec<_>>(),
1786                    )) as _,
1787                    Arc::new(Float64Vector::from(
1788                        order.iter().map(|&row| rows[row].3).collect::<Vec<_>>(),
1789                    )) as _,
1790                    histogram_vector(
1791                        &order
1792                            .iter()
1793                            .map(|&row| rows[row].4.clone())
1794                            .collect::<Vec<_>>(),
1795                    ),
1796                ],
1797            )
1798            .unwrap();
1799            let mut batches = Vec::new();
1800            let mut start = 0;
1801            for &end in splits.iter().chain(std::iter::once(&order.len())) {
1802                batches.push(batch.slice(start, end - start).unwrap());
1803                start = end;
1804            }
1805            let response = PrometheusJsonResponse::record_batches_to_data(
1806                RecordBatches::try_new(schema.clone(), batches).unwrap(),
1807                Some("metric".to_string()),
1808                ValueType::Matrix,
1809            )
1810            .unwrap();
1811            let PrometheusResponse::PromData(PromData {
1812                result: PromQueryResult::Matrix(series),
1813                ..
1814            }) = response
1815            else {
1816                panic!("expected matrix response");
1817            };
1818            series
1819        };
1820
1821        let clustered = matrix(&[0, 2, 1, 4, 3, 5, 7, 6, 9, 8], &[5]);
1822        let interleaved = matrix(&[8, 5, 1, 6, 0, 3, 9, 2, 7, 4], &[3, 6]);
1823        assert_eq!(
1824            serde_json::to_value(&interleaved).unwrap(),
1825            serde_json::to_value(&clustered).unwrap()
1826        );
1827
1828        // Pin the canonical arrangement itself, not only its stability.
1829        assert_eq!(
1830            serde_json::to_value(&clustered[..4]).unwrap(),
1831            serde_json::json!([
1832                {"metric": {"__name__": "metric"}, "values": [[6.0, "6.0"], [8.0, "8.0"]]},
1833                {"metric": {"__name__": "metric", "host": ""}, "values": [[7.0, "7.0"]]},
1834                {"metric": {"__name__": "metric", "host": "a"},
1835                 "values": [[4.0, "4.0"], [5.0, "5.0"]]},
1836                {"metric": {"__name__": "metric", "host": "a", "rack": "r"},
1837                 "values": [[1.0, "1.0"], [2.0, "2.0"], [3.0, "3.0"]]},
1838            ])
1839        );
1840        assert_eq!(clustered[4].metric["host"], "h");
1841        assert_eq!(
1842            clustered[4]
1843                .histograms
1844                .iter()
1845                .map(|(timestamp, histogram)| (*timestamp, histogram.sum.as_str()))
1846                .collect::<Vec<_>>(),
1847            vec![(1.0, "10"), (2.0, "20")]
1848        );
1849    }
1850
1851    #[test]
1852    fn record_batches_to_data_preserves_mixed_float_and_histogram_rows() {
1853        let schema = Arc::new(Schema::new(vec![
1854            ColumnSchema::new(
1855                "timestamp",
1856                ConcreteDataType::timestamp_millisecond_datatype(),
1857                false,
1858            ),
1859            ColumnSchema::new("kind", ConcreteDataType::string_datatype(), false),
1860            ColumnSchema::new("float", ConcreteDataType::float64_datatype(), true),
1861            ColumnSchema::new("histogram", native_histogram_value_type().clone(), true),
1862        ]));
1863        let batch = RecordBatch::new(
1864            schema.clone(),
1865            vec![
1866                Arc::new(TimestampMillisecondVector::from_values([1_000, 1_000])) as _,
1867                Arc::new(StringVector::from(vec![Some("float"), Some("histogram")])) as _,
1868                Arc::new(Float64Vector::from(vec![Some(1.25), None])) as _,
1869                histogram_vector(&[None, Some(sample_histogram())]),
1870            ],
1871        )
1872        .unwrap();
1873        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1874
1875        let response = PrometheusJsonResponse::record_batches_to_data(
1876            batches,
1877            Some("mixed_metric".to_string()),
1878            ValueType::Vector,
1879        )
1880        .unwrap();
1881        let PrometheusResponse::PromData(PromData {
1882            result: PromQueryResult::Vector(series),
1883            ..
1884        }) = response
1885        else {
1886            panic!("expected vector response");
1887        };
1888
1889        assert_eq!(series.len(), 2);
1890        let float = series
1891            .iter()
1892            .find(|series| series.metric["kind"] == "float")
1893            .unwrap();
1894        assert_eq!(float.value, Some((1.0, "1.25".to_string())));
1895        assert!(float.histogram.is_none());
1896
1897        let histogram = series
1898            .iter()
1899            .find(|series| series.metric["kind"] == "histogram")
1900            .unwrap();
1901        assert!(histogram.value.is_none());
1902        let (timestamp, histogram) = histogram.histogram.as_ref().unwrap();
1903        assert_eq!(*timestamp, 1.0);
1904        assert_eq!(histogram.count, "2");
1905        assert_eq!(histogram.sum, "3");
1906    }
1907
1908    #[test]
1909    fn label_replace_with_utf8view_labels_does_not_panic() {
1910        // A PromQL `label_replace` query produces its new label through DataFusion's
1911        // `regexp_replace`, whose output materializes as a `Utf8View` array even when
1912        // the source label is a plain `Utf8`. Serializing such labels must not assume
1913        // the column is a `StringArray`.
1914        let schema = Arc::new(Schema::new(vec![
1915            ColumnSchema::new(
1916                "timestamp",
1917                ConcreteDataType::timestamp_millisecond_datatype(),
1918                false,
1919            ),
1920            ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
1921            ColumnSchema::new("host_copy", ConcreteDataType::utf8_view_datatype(), false),
1922            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
1923        ]));
1924        let batch = RecordBatch::new(
1925            schema.clone(),
1926            vec![
1927                Arc::new(TimestampMillisecondVector::from_values([1_000])) as _,
1928                Arc::new(StringVector::from(vec![Some("server-01")])) as _,
1929                Arc::new(StringVector::from(StringViewArray::from(vec![Some(
1930                    "server-01",
1931                )]))) as _,
1932                Arc::new(Float64Vector::from(vec![Some(1.0)])) as _,
1933            ],
1934        )
1935        .unwrap();
1936        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1937
1938        let response = PrometheusJsonResponse::record_batches_to_data(
1939            batches,
1940            Some("label_replace_repro".to_string()),
1941            ValueType::Vector,
1942        )
1943        .unwrap();
1944        let PrometheusResponse::PromData(PromData {
1945            result: PromQueryResult::Vector(series),
1946            ..
1947        }) = response
1948        else {
1949            panic!("expected vector response");
1950        };
1951
1952        assert_eq!(series.len(), 1);
1953        assert_eq!(series[0].metric["__name__"], "label_replace_repro");
1954        assert_eq!(series[0].metric["host"], "server-01");
1955        assert_eq!(series[0].metric["host_copy"], "server-01");
1956        assert_eq!(series[0].value, Some((1.0, "1.0".to_string())));
1957    }
1958
1959    #[test]
1960    fn matrix_response_preserves_ordinary_histogram_nan_and_filters_stale_marker() {
1961        let schema = Arc::new(Schema::new(vec![
1962            ColumnSchema::new(
1963                "timestamp",
1964                ConcreteDataType::timestamp_millisecond_datatype(),
1965                false,
1966            ),
1967            ColumnSchema::new("histogram", native_histogram_value_type().clone(), true),
1968        ]));
1969        let mut ordinary_nan = sample_histogram();
1970        ordinary_nan.sum = f64::NAN;
1971        let mut stale = sample_histogram();
1972        stale.sum = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
1973        let batch = RecordBatch::new(
1974            schema.clone(),
1975            vec![
1976                Arc::new(TimestampMillisecondVector::from_values([1_000, 2_000])) as _,
1977                histogram_vector(&[Some(ordinary_nan), Some(stale)]),
1978            ],
1979        )
1980        .unwrap();
1981        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1982
1983        let response =
1984            PrometheusJsonResponse::record_batches_to_data(batches, None, ValueType::Matrix)
1985                .unwrap();
1986        let PrometheusResponse::PromData(PromData {
1987            result: PromQueryResult::Matrix(series),
1988            ..
1989        }) = response
1990        else {
1991            panic!("expected matrix response");
1992        };
1993
1994        assert_eq!(series.len(), 1);
1995        assert_eq!(series[0].histograms.len(), 1);
1996        assert_eq!(series[0].histograms[0].0, 1.0);
1997        assert_eq!(series[0].histograms[0].1.sum, "NaN");
1998    }
1999
2000    #[test]
2001    fn native_histogram_json_closes_custom_bucket_zero() {
2002        let mut histogram = sample_histogram();
2003        histogram.schema = CUSTOM_BUCKETS_SCHEMA;
2004        histogram.zero_threshold = 0.0;
2005        histogram.custom_values = vec![1.0];
2006        histogram.positive_spans = vec![Span {
2007            offset: 0,
2008            length: 1,
2009        }];
2010        histogram.count = 1.0;
2011        histogram.sum = 0.0;
2012        histogram.zero_count = 0.0;
2013
2014        let json = serde_json::to_value(prometheus_native_histogram(&histogram).unwrap()).unwrap();
2015        assert_eq!(json["buckets"], serde_json::json!([[3, "-Inf", "1", "1"]]));
2016    }
2017
2018    /// The rows of an `or` result, as the plan above them produces them: the time index, the
2019    /// column declaring each row's metric name, the union of both sides' labels, and the value.
2020    fn or_batches() -> RecordBatches {
2021        let name = || {
2022            ColumnSchema::new(
2023                "__promql_or_name_0",
2024                ConcreteDataType::string_datatype(),
2025                true,
2026            )
2027            .with_metric_name(true)
2028        };
2029        let schema = Arc::new(Schema::new(vec![
2030            ColumnSchema::new(
2031                "timestamp",
2032                ConcreteDataType::timestamp_millisecond_datatype(),
2033                false,
2034            ),
2035            name(),
2036            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
2037            ColumnSchema::new("kind", ConcreteDataType::string_datatype(), true),
2038            ColumnSchema::new("site", ConcreteDataType::string_datatype(), true),
2039            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2040        ]));
2041        // `left_metric{host="a",kind="x"}=10`, `left_metric{host="b",kind="y"}=20`,
2042        // `right_metric{host="a",site="z1"}=2` and `right_metric{host="c",site="z2"}=4`. A side
2043        // that does not carry a label of the other side leaves it null, and a null label is absent.
2044        let batch = RecordBatch::new(
2045            schema.clone(),
2046            vec![
2047                Arc::new(TimestampMillisecondVector::from_vec(vec![1_000; 4])) as _,
2048                Arc::new(StringVector::from(vec![
2049                    Some("left_metric"),
2050                    Some("left_metric"),
2051                    Some("right_metric"),
2052                    Some("right_metric"),
2053                ])) as _,
2054                Arc::new(StringVector::from(vec![
2055                    Some("a"),
2056                    Some("b"),
2057                    Some("a"),
2058                    Some("c"),
2059                ])) as _,
2060                Arc::new(StringVector::from(vec![Some("x"), Some("y"), None, None])) as _,
2061                Arc::new(StringVector::from(vec![None, None, Some("z1"), Some("z2")])) as _,
2062                Arc::new(Float64Vector::from(vec![
2063                    Some(10.0),
2064                    Some(20.0),
2065                    Some(2.0),
2066                    Some(4.0),
2067                ])) as _,
2068            ],
2069        )
2070        .unwrap();
2071        RecordBatches::try_new(schema, vec![batch]).unwrap()
2072    }
2073
2074    /// A result whose rows report different names keeps each row's own name.
2075    ///
2076    /// The statement's own name is passed in as the response layer derives it, and must not be used:
2077    /// it can only describe one of the two sides.
2078    #[test]
2079    fn or_result_names_each_row_after_the_side_it_came_from() {
2080        let response = PrometheusJsonResponse::record_batches_to_data(
2081            or_batches(),
2082            Some("left_metric".to_string()),
2083            ValueType::Vector,
2084        )
2085        .unwrap();
2086        let PrometheusResponse::PromData(PromData {
2087            result: PromQueryResult::Vector(series),
2088            ..
2089        }) = response
2090        else {
2091            panic!("expected vector response");
2092        };
2093
2094        assert_eq!(
2095            serde_json::to_value(&series).unwrap(),
2096            serde_json::json!([
2097                {
2098                    "metric": {"__name__": "left_metric", "host": "a", "kind": "x"},
2099                    "value": [1.0, "10.0"],
2100                },
2101                {
2102                    "metric": {"__name__": "left_metric", "host": "b", "kind": "y"},
2103                    "value": [1.0, "20.0"],
2104                },
2105                {
2106                    "metric": {"__name__": "right_metric", "host": "a", "site": "z1"},
2107                    "value": [1.0, "2.0"],
2108                },
2109                {
2110                    "metric": {"__name__": "right_metric", "host": "c", "site": "z2"},
2111                    "value": [1.0, "4.0"],
2112                },
2113            ])
2114        );
2115    }
2116
2117    /// A row a plan leaves unnamed reports no name at all.
2118    ///
2119    /// A declared name column says "this row has no name" with an empty value as well as with a
2120    /// null, because a plan that carries the name of each row carries it as a string: Prometheus
2121    /// drops an empty label value, so a row without a name carries no `__name__` label rather than
2122    /// an empty one. A statement-derived name is not a fallback for such a row: the column is what
2123    /// names the rows of a plan that declares it.
2124    #[test]
2125    fn an_empty_declared_name_reports_no_name() {
2126        let schema = Arc::new(Schema::new(vec![
2127            ColumnSchema::new(
2128                "timestamp",
2129                ConcreteDataType::timestamp_millisecond_datatype(),
2130                false,
2131            ),
2132            // The column this branch declares: nullable, because a row an operator leaves unnamed
2133            // has no name, and marked as the name column rather than named after the old internal
2134            // projection the plan used to carry.
2135            ColumnSchema::new(METRIC_NAME, ConcreteDataType::string_datatype(), true)
2136                .with_metric_name(true),
2137            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
2138            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2139        ]));
2140        let batch = RecordBatch::new(
2141            schema.clone(),
2142            vec![
2143                Arc::new(TimestampMillisecondVector::from_vec(vec![
2144                    1_000, 1_000, 1_000,
2145                ])) as _,
2146                Arc::new(StringVector::from(vec![
2147                    Some(""),
2148                    None,
2149                    Some("other_metric"),
2150                ])) as _,
2151                Arc::new(StringVector::from(vec![Some("a"), Some("b"), Some("c")])) as _,
2152                Arc::new(Float64Vector::from(vec![Some(1.0), Some(2.0), Some(3.0)])) as _,
2153            ],
2154        )
2155        .unwrap();
2156        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
2157
2158        let response = PrometheusJsonResponse::record_batches_to_data(
2159            batches,
2160            Some("left_metric".to_string()),
2161            ValueType::Vector,
2162        )
2163        .unwrap();
2164        let PrometheusResponse::PromData(PromData {
2165            result: PromQueryResult::Vector(series),
2166            ..
2167        }) = response
2168        else {
2169            panic!("expected vector response");
2170        };
2171
2172        assert_eq!(
2173            serde_json::to_value(&series).unwrap(),
2174            serde_json::json!([
2175                {"metric": {"host": "a"}, "value": [1.0, "1.0"]},
2176                {"metric": {"host": "b"}, "value": [1.0, "2.0"]},
2177                {"metric": {"__name__": "other_metric", "host": "c"}, "value": [1.0, "3.0"]},
2178            ])
2179        );
2180    }
2181
2182    /// A result that declares no name column is named after the statement, as it always was.
2183    #[test]
2184    fn result_without_a_name_column_is_named_after_the_statement() {
2185        let schema = Arc::new(Schema::new(vec![
2186            ColumnSchema::new(
2187                "timestamp",
2188                ConcreteDataType::timestamp_millisecond_datatype(),
2189                false,
2190            ),
2191            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
2192            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2193        ]));
2194        let batch = RecordBatch::new(
2195            schema.clone(),
2196            vec![
2197                Arc::new(TimestampMillisecondVector::from_vec(vec![1_000])) as _,
2198                Arc::new(StringVector::from(vec![Some("a")])) as _,
2199                Arc::new(Float64Vector::from(vec![Some(1.5)])) as _,
2200            ],
2201        )
2202        .unwrap();
2203        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
2204
2205        let response = PrometheusJsonResponse::record_batches_to_data(
2206            batches,
2207            Some("some_metric".to_string()),
2208            ValueType::Vector,
2209        )
2210        .unwrap();
2211        let PrometheusResponse::PromData(PromData {
2212            result: PromQueryResult::Vector(series),
2213            ..
2214        }) = response
2215        else {
2216            panic!("expected vector response");
2217        };
2218
2219        assert_eq!(
2220            serde_json::to_value(&series).unwrap(),
2221            serde_json::json!([
2222                {"metric": {"__name__": "some_metric", "host": "a"}, "value": [1.0, "1.5"]},
2223            ])
2224        );
2225    }
2226
2227    /// A column that happens to be called `__name__` is an ordinary label.
2228    ///
2229    /// `count_values("__name__", metric)` generates such a column, and its values are counts rather
2230    /// than metric names. The declaration is what says a column holds names, so this one keeps
2231    /// naming the result after the statement and keeps its values as a label.
2232    #[test]
2233    fn a_column_called_name_that_is_not_declared_is_an_ordinary_label() {
2234        let schema = Arc::new(Schema::new(vec![
2235            ColumnSchema::new(
2236                "timestamp",
2237                ConcreteDataType::timestamp_millisecond_datatype(),
2238                false,
2239            ),
2240            ColumnSchema::new("__name__", ConcreteDataType::string_datatype(), false),
2241            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2242        ]));
2243        let layout = ColumnLayout::infer(&schema).unwrap();
2244        assert!(
2245            layout.name_column_index.is_none(),
2246            "a column that is not declared is not read as the name"
2247        );
2248        assert_eq!(vec![1], layout.tag_column_indices);
2249
2250        let batch = RecordBatch::new(
2251            schema.clone(),
2252            vec![
2253                Arc::new(TimestampMillisecondVector::from_vec(vec![1_000])) as _,
2254                Arc::new(StringVector::from(vec![Some("5")])) as _,
2255                Arc::new(Float64Vector::from(vec![Some(5.0)])) as _,
2256            ],
2257        )
2258        .unwrap();
2259        let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
2260
2261        let response = PrometheusJsonResponse::record_batches_to_data(
2262            batches,
2263            Some("some_metric".to_string()),
2264            ValueType::Vector,
2265        )
2266        .unwrap();
2267        let PrometheusResponse::PromData(PromData {
2268            result: PromQueryResult::Vector(series),
2269            ..
2270        }) = response
2271        else {
2272            panic!("expected vector response");
2273        };
2274
2275        // The generated label is an ordinary label, so it labels the series as it always has: the
2276        // statement names the series and the label set carries the count.
2277        assert_eq!(
2278            serde_json::to_value(&series).unwrap(),
2279            serde_json::json!([
2280                {"metric": {"__name__": "5"}, "value": [1.0, "5.0"]},
2281            ])
2282        );
2283    }
2284
2285    /// A result that declares more than one name column is an error rather than a guess.
2286    #[test]
2287    fn more_than_one_name_column_is_an_error() {
2288        let schema = Arc::new(Schema::new(vec![
2289            ColumnSchema::new(
2290                "timestamp",
2291                ConcreteDataType::timestamp_millisecond_datatype(),
2292                false,
2293            ),
2294            ColumnSchema::new("first_name", ConcreteDataType::string_datatype(), true)
2295                .with_metric_name(true),
2296            ColumnSchema::new("second_name", ConcreteDataType::string_datatype(), true)
2297                .with_metric_name(true),
2298            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2299        ]));
2300
2301        let error = match ColumnLayout::infer(&schema) {
2302            Ok(_) => panic!("a result that declares two name columns is an error"),
2303            Err(error) => error,
2304        };
2305        assert!(
2306            error
2307                .to_string()
2308                .contains("more than one metric name column"),
2309            "{error}"
2310        );
2311    }
2312
2313    /// A declared name column that does not hold strings is an error rather than a guess.
2314    #[test]
2315    fn a_name_column_that_is_not_a_string_column_is_an_error() {
2316        let schema = Arc::new(Schema::new(vec![
2317            ColumnSchema::new(
2318                "timestamp",
2319                ConcreteDataType::timestamp_millisecond_datatype(),
2320                false,
2321            ),
2322            ColumnSchema::new("name", ConcreteDataType::float64_datatype(), true)
2323                .with_metric_name(true),
2324            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
2325        ]));
2326
2327        let error = match ColumnLayout::infer(&schema) {
2328            Ok(_) => panic!("a name column that is not a string column is an error"),
2329            Err(error) => error,
2330        };
2331        assert!(
2332            error.to_string().contains("is not a string column"),
2333            "{error}"
2334        );
2335    }
2336
2337    #[test]
2338    fn native_histogram_json_preserves_terminal_finite_bucket() {
2339        let mut histogram = sample_histogram();
2340        histogram.positive_spans = vec![Span {
2341            offset: 1024,
2342            length: 2,
2343        }];
2344        histogram.positive_buckets = vec![1.0, 1.0];
2345        histogram.zero_count = 0.0;
2346
2347        let json = serde_json::to_value(prometheus_native_histogram(&histogram).unwrap()).unwrap();
2348        assert_eq!(
2349            json["buckets"],
2350            serde_json::json!([
2351                [0, 2.0_f64.powi(1023).to_string(), f64::MAX.to_string(), "1"],
2352                [0, f64::MAX.to_string(), "+Inf", "1"]
2353            ])
2354        );
2355    }
2356}