Skip to main content

servers/
prom_store.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//! prometheus protocol supportings
16//! handles prometheus remote_write, remote_read logic
17use std::cmp::Ordering;
18use std::collections::HashMap;
19use std::collections::hash_map::DefaultHasher;
20use std::hash::{Hash, Hasher};
21use std::sync::Arc;
22
23use api::prom_store::remote::label_matcher::Type as MatcherType;
24use api::prom_store::remote::{Label, LabelMatcher, Query, Sample, TimeSeries, WriteRequest};
25use api::v1::RowInsertRequests;
26use arrow::array::{
27    Array, ArrayRef, AsArray, DictionaryArray, LargeStringArray, StringArray, StringViewArray,
28};
29use arrow::compute::kernels::cast as casts;
30use arrow::datatypes::{
31    DataType, Float64Type, TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
32    TimestampNanosecondType, UInt32Type,
33};
34use common_grpc::precision::Precision;
35use common_memory_manager::MemoryGuard;
36use common_query::native_histogram;
37use common_query::prelude::{greptime_timestamp, greptime_value};
38use common_recordbatch::{RecordBatch, RecordBatches};
39use common_telemetry::{tracing, warn};
40use datafusion::dataframe::DataFrame;
41use datafusion::prelude::{Expr, ident, lit, regexp_match};
42use datafusion_common::ScalarValue;
43use datafusion_expr::LogicalPlan;
44use snafu::{OptionExt, ResultExt, ensure};
45use snap::raw::{Decoder, Encoder};
46
47use crate::error::{self, Result};
48use crate::prom_remote_write::REMOTE_WRITE_V1_VERSION;
49use crate::request_memory_limiter::ServerMemoryLimiter;
50use crate::request_memory_metrics::RequestMemoryMetrics;
51use crate::row_writer::{self, MultiTableData};
52
53pub const METRIC_NAME_LABEL: &str = "__name__";
54pub const METRIC_NAME_LABEL_BYTES: &[u8] = b"__name__";
55
56/// special label for selecting database name on remote write
57pub const DATABASE_LABEL: &str = "x_greptime_database";
58pub const DATABASE_LABEL_BYTES: &[u8] = b"x_greptime_database";
59pub const DATABASE_LABEL_ALT: &str = "__database__";
60pub const DATABASE_LABEL_ALT_BYTES: &[u8] = b"__database__";
61
62/// deprecated, use DATABASE_LABEL instead
63#[deprecated(note = "use DATABASE_LABEL instead")]
64pub const SCHEMA_LABEL: &str = "__schema__";
65#[deprecated(note = "use DATABASE_LABEL_BYTES instead")]
66pub const SCHEMA_LABEL_BYTES: &[u8] = b"__schema__";
67
68/// special label for selecting physical table name on remote write
69pub const PHYSICAL_TABLE_LABEL: &str = "x_greptime_physical_table";
70pub const PHYSICAL_TABLE_LABEL_BYTES: &[u8] = b"x_greptime_physical_table";
71pub const PHYSICAL_TABLE_LABEL_ALT: &str = "__physical_table__";
72pub const PHYSICAL_TABLE_LABEL_ALT_BYTES: &[u8] = b"__physical_table__";
73
74/// The same as `FIELD_COLUMN_MATCHER` in `promql` crate
75pub const FIELD_NAME_LABEL: &str = "__field__";
76
77#[allow(deprecated)]
78pub fn is_remote_read_special_label(label: &str) -> bool {
79    label == METRIC_NAME_LABEL
80        || label == DATABASE_LABEL
81        || label == DATABASE_LABEL_ALT
82        || label == SCHEMA_LABEL
83}
84
85/// Check if given label is a database selection label
86#[allow(deprecated)]
87pub fn is_database_selection_label(label: &str) -> bool {
88    label == DATABASE_LABEL || label == DATABASE_LABEL_ALT || label == SCHEMA_LABEL
89}
90
91/// Get table name from remote query
92pub fn table_name(q: &Query) -> Result<String> {
93    let mut matchers = q
94        .matchers
95        .iter()
96        .filter(|matcher| matcher.name == METRIC_NAME_LABEL);
97    let matcher = matchers
98        .next()
99        .context(error::InvalidPromRemoteRequestSnafu {
100            msg: "missing '__name__' label in timeseries",
101        })?;
102
103    if matcher.r#type != MatcherType::Eq as i32
104        || matcher.value.is_empty()
105        || matchers.next().is_some()
106    {
107        return Err(error::InvalidPromRemoteRequestSnafu {
108            msg: "expected exactly one non-empty equality matcher for '__name__'".to_string(),
109        }
110        .build());
111    }
112
113    Ok(matcher.value.clone())
114}
115
116/// Extract database selector from a remote read query.
117pub fn extract_schema_from_query(query: &Query) -> Option<String> {
118    query
119        .matchers
120        .iter()
121        .find(|matcher| {
122            is_database_selection_label(&matcher.name) && matcher.r#type == MatcherType::Eq as i32
123        })
124        .map(|matcher| matcher.value.clone())
125}
126
127/// Validate matcher syntax independently of whether the metric exists.
128pub fn validate_matchers(matchers: &[LabelMatcher]) -> Result<()> {
129    for matcher in matchers {
130        let matcher_type = MatcherType::try_from(matcher.r#type).map_err(|e| {
131            error::InvalidPromRemoteRequestSnafu {
132                msg: format!("invalid LabelMatcher type, decode error: {e}"),
133            }
134            .build()
135        })?;
136        if matches!(matcher_type, MatcherType::Re | MatcherType::Nre) {
137            // Like Prometheus, validate the raw regex first, then the anchored pattern.
138            // We use the same regex engine as query execution, whose syntax differs
139            // from Prometheus's: e.g. `(?x) a` is accepted here but rejected by Prometheus.
140            regex::Regex::new(&matcher.value)
141                .and_then(|_| regex::Regex::new(&anchored_label_regex(&matcher.value)))
142                .map_err(|e| {
143                    error::InvalidPromRemoteRequestSnafu {
144                        msg: format!("invalid regex for label '{}': {e}", matcher.name),
145                    }
146                    .build()
147                })?;
148        }
149    }
150    Ok(())
151}
152
153/// Create a DataFrame from a remote Query
154#[tracing::instrument(skip_all)]
155pub fn query_to_plan(
156    dataframe: DataFrame,
157    q: &Query,
158    timestamp_column_name: &str,
159) -> Result<LogicalPlan> {
160    let (start_timestamp_ms, end_timestamp_ms) = remote_read_time_range(q);
161
162    let label_matches = &q.matchers;
163
164    let mut conditions = Vec::with_capacity(label_matches.len() + 1);
165
166    conditions
167        .push(ident(timestamp_column_name).gt_eq(lit_timestamp_millisecond(start_timestamp_ms)));
168    conditions
169        .push(ident(timestamp_column_name).lt_eq(lit_timestamp_millisecond(end_timestamp_ms)));
170
171    for m in label_matches {
172        let name = &m.name;
173
174        if is_remote_read_special_label(name) {
175            continue;
176        }
177
178        let value = &m.value;
179        let m_type = MatcherType::try_from(m.r#type).map_err(|e| {
180            error::InvalidPromRemoteRequestSnafu {
181                msg: format!("invalid LabelMatcher type, decode error: {e}",),
182            }
183            .build()
184        })?;
185
186        // Prometheus treats an absent label as "".
187        let label = if dataframe.schema().has_column_with_unqualified_name(name) {
188            ident(name)
189        } else {
190            lit("")
191        };
192
193        // Like PromQL, include NULL when the matcher accepts the empty string.
194        // Keep EQ/NEQ on the original column for index recognition.
195        let condition = match m_type {
196            MatcherType::Eq => {
197                if value.is_empty() {
198                    label.clone().eq(lit(value)).or(label.is_null())
199                } else {
200                    label.eq(lit(value))
201                }
202            }
203            MatcherType::Neq => {
204                if value.is_empty() {
205                    label.not_eq(lit(value))
206                } else {
207                    label.clone().not_eq(lit(value)).or(label.is_null())
208                }
209            }
210            MatcherType::Re | MatcherType::Nre => {
211                let pattern = anchored_label_regex(value);
212                let matches_empty = regex::Regex::new(&pattern)
213                    .map_err(|e| {
214                        error::InvalidPromRemoteRequestSnafu {
215                            msg: format!("invalid regex for label '{name}': {e}"),
216                        }
217                        .build()
218                    })?
219                    .is_match("");
220                let matched = regexp_match(label.clone(), lit(pattern), None);
221                if m_type == MatcherType::Re {
222                    let condition = matched.is_not_null();
223                    if matches_empty {
224                        condition.or(label.is_null())
225                    } else {
226                        condition
227                    }
228                } else {
229                    let condition = matched.is_null();
230                    // A NULL input also produces NULL. Keep it only when the
231                    // negative matcher accepts the empty string.
232                    if matches_empty {
233                        condition.and(label.is_not_null())
234                    } else {
235                        condition
236                    }
237                }
238            }
239        };
240        conditions.push(condition);
241    }
242
243    // Safety: conditions MUST not be empty, reduce always return Some(expr).
244    let conditions = conditions.into_iter().reduce(Expr::and).unwrap();
245
246    let dataframe = dataframe
247        .filter(conditions)
248        .context(error::DataFrameSnafu)?;
249
250    Ok(dataframe.into_parts().1)
251}
252
253/// Uses selector time hints without expanding the client's remote-storage range.
254/// Nonpositive or reversed hints retain the outer range: proto3 scalar defaults
255/// cannot distinguish missing endpoints from explicit zero timestamps. Valid
256/// disjoint ranges produce contradictory time predicates and therefore no rows.
257fn remote_read_time_range(query: &Query) -> (i64, i64) {
258    let outer = (query.start_timestamp_ms, query.end_timestamp_ms);
259    let Some(hints) = &query.hints else {
260        return outer;
261    };
262    if hints.start_ms <= 0 || hints.end_ms <= 0 || hints.start_ms > hints.end_ms {
263        return outer;
264    }
265
266    (outer.0.max(hints.start_ms), outer.1.min(hints.end_ms))
267}
268
269/// Prometheus's NewFastRegexMatcher also wraps patterns in ^(?s:...)$:
270/// https://github.com/prometheus/prometheus/blob/main/model/labels/regexp.go
271fn anchored_label_regex(value: &str) -> String {
272    format!("^(?s:{value})$")
273}
274
275#[inline]
276fn new_label(name: String, value: String) -> Label {
277    Label { name, value }
278}
279
280fn lit_timestamp_millisecond(ts: i64) -> Expr {
281    Expr::Literal(ScalarValue::TimestampMillisecond(Some(ts), None), None)
282}
283
284/// Sort timeseries by labels, matching the former `BTreeMap` order.
285fn compare_timeseries_labels(left: &[Label], right: &[Label]) -> Ordering {
286    let ordering = left.len().cmp(&right.len());
287    if ordering != Ordering::Equal {
288        return ordering;
289    }
290
291    for (left, right) in left.iter().zip(right) {
292        let ordering = left.name.cmp(&right.name);
293        if ordering != Ordering::Equal {
294            return ordering;
295        }
296
297        let ordering = left.value.cmp(&right.value);
298        if ordering != Ordering::Equal {
299            return ordering;
300        }
301    }
302
303    Ordering::Equal
304}
305
306enum LabelValues<'a> {
307    Utf8(&'a StringArray),
308    LargeUtf8(&'a LargeStringArray),
309    Utf8View(&'a StringViewArray),
310    DictionaryUtf8 {
311        dictionary: &'a DictionaryArray<UInt32Type>,
312        values: &'a StringArray,
313    },
314    Other(Vec<Option<String>>),
315}
316
317impl LabelValues<'_> {
318    fn value(&self, row: usize) -> Option<&str> {
319        match self {
320            Self::Utf8(values) => values.is_valid(row).then(|| values.value(row)),
321            Self::LargeUtf8(values) => values.is_valid(row).then(|| values.value(row)),
322            Self::Utf8View(values) => values.is_valid(row).then(|| values.value(row)),
323            Self::DictionaryUtf8 { dictionary, values } => dictionary
324                .key(row)
325                .and_then(|key| values.is_valid(key).then(|| values.value(key))),
326            Self::Other(values) => values.get(row).and_then(Option::as_deref),
327        }
328    }
329}
330
331fn row_labels<'a>(
332    columns: &'a [LabelColumn<'a>],
333    row: usize,
334) -> impl Iterator<Item = (&'a str, &'a str)> {
335    columns
336        .iter()
337        .filter_map(move |column| column.values.value(row).map(|value| (column.name, value)))
338}
339
340struct LabelColumn<'a> {
341    name: &'a str,
342    values: LabelValues<'a>,
343}
344
345fn label_columns<'a>(
346    recordbatch: &'a RecordBatch,
347    timestamp_column_name: &str,
348    value_column_name: &str,
349) -> Result<Vec<LabelColumn<'a>>> {
350    recordbatch
351        .schema
352        .column_schemas()
353        .iter()
354        .enumerate()
355        .filter(|(_, column_schema)| {
356            column_schema.name != timestamp_column_name && column_schema.name != value_column_name
357        })
358        .map(|(index, column_schema)| {
359            let array = recordbatch.column(index);
360            let values = match array.data_type() {
361                arrow::datatypes::DataType::Utf8 => LabelValues::Utf8(array.as_string::<i32>()),
362                arrow::datatypes::DataType::LargeUtf8 => {
363                    LabelValues::LargeUtf8(array.as_string::<i64>())
364                }
365                arrow::datatypes::DataType::Utf8View => {
366                    LabelValues::Utf8View(array.as_string_view())
367                }
368                arrow::datatypes::DataType::Dictionary(key, value)
369                    if key.as_ref() == &arrow::datatypes::DataType::UInt32
370                        && value.as_ref() == &arrow::datatypes::DataType::Utf8 =>
371                {
372                    let dictionary = array.as_dictionary::<UInt32Type>();
373                    LabelValues::DictionaryUtf8 {
374                        dictionary,
375                        values: dictionary.values().as_string::<i32>(),
376                    }
377                }
378                _ => {
379                    let values = recordbatch.iter_column_as_string(index).collect::<Vec<_>>();
380                    ensure!(
381                        values.len() == recordbatch.num_rows(),
382                        error::InvalidPromRemoteReadQueryResultSnafu {
383                            msg: format!(
384                                "Cannot convert label column '{}' of datatype {:?} to string",
385                                column_schema.name,
386                                array.data_type()
387                            ),
388                        }
389                    );
390                    LabelValues::Other(values)
391                }
392            };
393            Ok(LabelColumn {
394                name: &column_schema.name,
395                values,
396            })
397        })
398        .collect()
399}
400
401fn hash_timeseries(columns: &[LabelColumn<'_>], row: usize) -> u64 {
402    let mut hasher = DefaultHasher::new();
403
404    for (name, value) in row_labels(columns, row) {
405        name.hash(&mut hasher);
406        value.hash(&mut hasher);
407    }
408
409    hasher.finish()
410}
411
412fn matches_timeseries(labels: &[Label], columns: &[LabelColumn<'_>], row: usize) -> bool {
413    let mut labels = labels.iter().skip(1);
414    for (name, value) in row_labels(columns, row) {
415        let Some(label) = labels.next() else {
416            return false;
417        };
418        if label.name != name || label.value != value {
419            return false;
420        }
421    }
422
423    labels.next().is_none()
424}
425
426fn new_timeseries(table: &str, columns: &[LabelColumn<'_>], row: usize) -> TimeSeries {
427    let mut labels = Vec::with_capacity(columns.len() + 1);
428    labels.push(new_label(METRIC_NAME_LABEL.to_string(), table.to_string()));
429
430    for (name, value) in row_labels(columns, row) {
431        labels.push(new_label(name.to_string(), value.to_string()));
432    }
433
434    TimeSeries {
435        labels,
436        ..Default::default()
437    }
438}
439
440pub fn recordbatches_to_timeseries(
441    table_name: &str,
442    timestamp_column_name: &str,
443    value_column_name: &str,
444    recordbatches: RecordBatches,
445) -> Result<Vec<TimeSeries>> {
446    let mut timeseries: Vec<TimeSeries> = Vec::new();
447    let mut timeseries_by_hash: HashMap<u64, Vec<usize>> = HashMap::new();
448
449    for recordbatch in recordbatches.take() {
450        append_recordbatch_to_timeseries(
451            table_name,
452            timestamp_column_name,
453            value_column_name,
454            recordbatch,
455            &mut timeseries,
456            &mut timeseries_by_hash,
457        )?;
458    }
459
460    for ts in &mut timeseries {
461        ts.samples.sort_unstable_by_key(|s| s.timestamp);
462        ts.histograms.sort_unstable_by_key(|h| h.timestamp);
463    }
464
465    timeseries
466        .sort_unstable_by(|left, right| compare_timeseries_labels(&left.labels, &right.labels));
467    Ok(timeseries)
468}
469
470fn append_recordbatch_to_timeseries(
471    table: &str,
472    timestamp_column_name: &str,
473    value_column_name: &str,
474    recordbatch: RecordBatch,
475    timeseries: &mut Vec<TimeSeries>,
476    timeseries_by_hash: &mut HashMap<u64, Vec<usize>>,
477) -> Result<()> {
478    let ts_column = recordbatch
479        .column_by_name(timestamp_column_name)
480        .with_context(|| error::InvalidPromRemoteReadQueryResultSnafu {
481            msg: format!("missing timestamp column '{timestamp_column_name}' in query result"),
482        })?;
483    // The Prometheus remote read wire format carries millisecond timestamps,
484    // while the table's time index can use any time unit (e.g. a metric
485    // physical table created with TIMESTAMP(6)). Narrowing floors towards
486    // negative infinity, consistent with `Timestamp::convert_to` on the
487    // ingestion path; arrow's cast would truncate towards zero, so a
488    // pre-epoch sample (e.g. -1001us) would round to -1ms instead of -2ms
489    // and disagree with what ingesting the same instant into a millisecond
490    // table would have stored.
491    let ts_column: ArrayRef = match ts_column.data_type() {
492        DataType::Timestamp(TimeUnit::Millisecond, _) => ts_column.clone(),
493        // Second -> millisecond is a widening (exact) conversion.
494        DataType::Timestamp(TimeUnit::Second, _) => casts::cast(
495            ts_column,
496            &DataType::Timestamp(TimeUnit::Millisecond, None),
497        )
498        .map_err(|e| {
499            error::InvalidPromRemoteReadQueryResultSnafu {
500                msg: format!(
501                    "failed to cast timestamp column '{timestamp_column_name}' of datatype {:?} to millisecond: {e}",
502                    ts_column.data_type()
503                ),
504            }
505            .build()
506        })?,
507        DataType::Timestamp(TimeUnit::Microsecond, _) => Arc::new(
508            ts_column
509                .as_primitive::<TimestampMicrosecondType>()
510                .unary::<_, TimestampMillisecondType>(|v| v.div_euclid(1_000)),
511        ),
512        DataType::Timestamp(TimeUnit::Nanosecond, _) => Arc::new(
513            ts_column
514                .as_primitive::<TimestampNanosecondType>()
515                .unary::<_, TimestampMillisecondType>(|v| v.div_euclid(1_000_000)),
516        ),
517        _ => {
518            return error::InvalidPromRemoteReadQueryResultSnafu {
519                msg: format!(
520                    "Expect timestamp column of datatype Timestamp(Millisecond), actual {:?}",
521                    ts_column.data_type()
522                ),
523            }
524            .fail();
525        }
526    };
527    let ts_column = ts_column
528        .as_primitive_opt::<TimestampMillisecondType>()
529        .with_context(|| error::InvalidPromRemoteReadQueryResultSnafu {
530            msg: format!(
531                "Expect timestamp column of datatype Timestamp(Millisecond), actual {:?}",
532                ts_column.data_type()
533            ),
534        })?;
535
536    let field_column = recordbatch
537        .column_by_name(value_column_name)
538        .with_context(|| error::InvalidPromRemoteReadQueryResultSnafu {
539            msg: format!("missing value column '{value_column_name}' in query result"),
540        })?;
541    let scalar_column = field_column.as_primitive_opt::<Float64Type>();
542    let histogram_column = recordbatch
543        .schema
544        .column_schema_by_name(value_column_name)
545        .filter(|column| native_histogram::is_native_histogram_value_type(&column.data_type))
546        .and_then(|_| field_column.as_struct_opt());
547    ensure!(
548        scalar_column.is_some() || histogram_column.is_some(),
549        error::InvalidPromRemoteReadQueryResultSnafu {
550            msg: format!(
551                "Expect value column of datatype Float64 or canonical native histogram Struct, actual {:?}",
552                field_column.data_type()
553            ),
554        }
555    );
556
557    let columns = label_columns(&recordbatch, timestamp_column_name, value_column_name)?;
558    let mut previous_timeseries: Option<usize> = None;
559
560    for row in 0..recordbatch.num_rows() {
561        let timeseries_index = match previous_timeseries {
562            Some(index) if matches_timeseries(&timeseries[index].labels, &columns, row) => index,
563            _ => {
564                let hash = hash_timeseries(&columns, row);
565                let candidates = timeseries_by_hash.entry(hash).or_default();
566                match candidates
567                    .iter()
568                    .copied()
569                    .find(|index| matches_timeseries(&timeseries[*index].labels, &columns, row))
570                {
571                    Some(index) => index,
572                    None => {
573                        let index = timeseries.len();
574                        timeseries.push(new_timeseries(table, &columns, row));
575                        candidates.push(index);
576                        index
577                    }
578                }
579            }
580        };
581        previous_timeseries = Some(timeseries_index);
582
583        if ts_column.is_null(row) || field_column.is_null(row) {
584            continue;
585        }
586
587        let timestamp = ts_column.value(row);
588        if let Some(column) = scalar_column {
589            timeseries[timeseries_index].samples.push(Sample {
590                value: column.value(row),
591                timestamp,
592            });
593        } else if let Some(column) = histogram_column {
594            let histogram =
595                native_histogram::decode_native_histogram_for_remote_read(column, row, timestamp)
596                    .map_err(|error| {
597                    error::InvalidPromRemoteReadQueryResultSnafu {
598                        msg: error.to_string(),
599                    }
600                    .build()
601                })?;
602            if let Some(histogram) = histogram {
603                timeseries[timeseries_index].histograms.push(histogram);
604            }
605        }
606    }
607
608    Ok(())
609}
610
611pub fn to_grpc_row_insert_requests(request: &WriteRequest) -> Result<(RowInsertRequests, usize)> {
612    let _timer = crate::metrics::METRIC_HTTP_PROM_STORE_CODEC_ELAPSED
613        .with_label_values(&["convert", REMOTE_WRITE_V1_VERSION])
614        .start_timer();
615
616    let mut multi_table_data = MultiTableData::new();
617
618    for series in &request.timeseries {
619        let table_name = &series
620            .labels
621            .iter()
622            .find(|label| {
623                // The metric name is a special label
624                label.name == METRIC_NAME_LABEL
625            })
626            .context(error::InvalidPromRemoteRequestSnafu {
627                msg: "missing '__name__' label in time-series",
628            })?
629            .value;
630
631        // The metric name is a special label,
632        // num_columns = labels.len() - 1 + 1 (value) + 1 (timestamp)
633        let num_columns = series.labels.len() + 1;
634
635        let table_data = multi_table_data.get_or_default_table_data(
636            table_name,
637            num_columns,
638            series.samples.len(),
639        );
640
641        // labels
642        let kvs = series.labels.iter().filter_map(|label| {
643            if label.name == METRIC_NAME_LABEL {
644                None
645            } else {
646                Some((label.name.clone(), label.value.clone()))
647            }
648        });
649
650        if series.samples.len() == 1 {
651            let mut one_row = table_data.alloc_one_row();
652
653            row_writer::write_tags(table_data, kvs, &mut one_row)?;
654            // value
655            row_writer::write_f64(
656                table_data,
657                greptime_value(),
658                series.samples[0].value,
659                &mut one_row,
660            )?;
661            // timestamp
662            row_writer::write_ts_to_millis(
663                table_data,
664                greptime_timestamp(),
665                Some(series.samples[0].timestamp),
666                Precision::Millisecond,
667                &mut one_row,
668            )?;
669
670            table_data.add_row(one_row);
671        } else {
672            for Sample { value, timestamp } in &series.samples {
673                let mut one_row = table_data.alloc_one_row();
674
675                // labels
676                let kvs = kvs.clone();
677                row_writer::write_tags(table_data, kvs, &mut one_row)?;
678                // value
679                row_writer::write_f64(table_data, greptime_value(), *value, &mut one_row)?;
680                // timestamp
681                row_writer::write_ts_to_millis(
682                    table_data,
683                    greptime_timestamp(),
684                    Some(*timestamp),
685                    Precision::Millisecond,
686                    &mut one_row,
687                )?;
688
689                table_data.add_row(one_row);
690            }
691        }
692
693        if !series.histograms.is_empty() {
694            warn!("Native histograms are not supported yet, data ignored");
695        }
696    }
697
698    Ok(multi_table_data.into_row_insert_requests())
699}
700
701/// Hard cap on the decompressed size of a handler-decompressed request body
702/// (Prometheus remote read/write, Loki push).
703///
704/// The HTTP body limit only bounds the *encoded* bytes on the wire. Without
705/// this cap a tiny compressed payload (e.g. a five-byte raw-Snappy varint or a
706/// few KiB of zstd RLE blocks) could declare/expand to multiple GiB of heap
707/// before any protobuf validation runs, so the decompressed size must be
708/// bounded on its own.
709pub const MAX_DECOMPRESSED_REQUEST_SIZE: usize = 512 * 1024 * 1024;
710
711/// Size of the chunks a zstd body is decompressed and charged in.
712const ZSTD_DECOMPRESS_CHUNK: usize = 256 * 1024;
713
714/// Decompressed bytes together with the memory permits charged for them.
715/// The permits are released when the buffer is dropped, so the aggregate
716/// memory accounting covers the whole lifetime of the decompressed data.
717pub(crate) struct ChargedBuffer {
718    pub data: Vec<u8>,
719    guards: Vec<MemoryGuard<RequestMemoryMetrics>>,
720}
721
722impl std::ops::Deref for ChargedBuffer {
723    type Target = [u8];
724
725    fn deref(&self) -> &Self::Target {
726        &self.data
727    }
728}
729
730impl std::fmt::Debug for ChargedBuffer {
731    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
732        f.debug_struct("ChargedBuffer")
733            .field("data_len", &self.data.len())
734            .field("guards", &self.guards.len())
735            .finish()
736    }
737}
738
739impl ChargedBuffer {
740    pub(crate) fn reserved_bytes(&self) -> u64 {
741        self.guards.iter().map(MemoryGuard::granted_bytes).sum()
742    }
743
744    /// Creates a buffer with the permits charged for it.
745    pub(crate) fn new(data: Vec<u8>, guards: Vec<MemoryGuard<RequestMemoryMetrics>>) -> Self {
746        Self { data, guards }
747    }
748
749    /// Splits the buffer into the raw bytes and the memory permits charged for
750    /// them. Hold the permits as long as the bytes are kept.
751    pub(crate) fn into_parts(self) -> (Vec<u8>, Vec<MemoryGuard<RequestMemoryMetrics>>) {
752        (self.data, self.guards)
753    }
754}
755
756/// Decompresses a raw Snappy body after enforcing a hard cap on the decoded
757/// size and charging the aggregate request-memory limiter.
758///
759/// The raw Snappy format prefixes the stream with a varint of the decoded
760/// length, so the output size is known (and validated) before the output
761/// buffer is allocated by `decompress_vec`.
762pub(crate) async fn snappy_decompress_limited(
763    buf: &[u8],
764    max_decompressed: usize,
765    limiter: &ServerMemoryLimiter,
766    held_bytes: u64,
767) -> Result<ChargedBuffer> {
768    let decoded_len =
769        snap::raw::decompress_len(buf).context(error::DecompressSnappyPromRemoteRequestSnafu)?;
770    ensure!(
771        decoded_len <= max_decompressed,
772        error::DecompressedBodyTooLargeSnafu {
773            size: decoded_len as u64,
774            limit: max_decompressed as u64,
775        }
776    );
777    // Reserve the declared size before the allocation happens so concurrent
778    // decompressions cannot exceed the aggregate quota.
779    limiter.check_request_fits(decoded_len as u64, held_bytes)?;
780    let guard = limiter.acquire(decoded_len as u64).await?;
781    let mut decoder = Decoder::new();
782    let data = decoder
783        .decompress_vec(buf)
784        .context(error::DecompressSnappyPromRemoteRequestSnafu)?;
785    Ok(ChargedBuffer {
786        data,
787        guards: vec![guard],
788    })
789}
790
791/// Decompresses a zstd body with a hard cap on the decoded size, charging the
792/// aggregate request-memory limiter incrementally while the output is
793/// materialized (zstd streams don't declare their decoded size up front).
794pub(crate) async fn zstd_decompress_limited(
795    buf: &[u8],
796    max_decompressed: usize,
797    limiter: &ServerMemoryLimiter,
798    mut held_bytes: u64,
799) -> Result<ChargedBuffer> {
800    use std::io::Read;
801
802    let decoder = zstd::stream::read::Decoder::new(buf)
803        .context(error::DecompressZstdPromRemoteRequestSnafu)?;
804    // Allow reading one byte past the limit so oversized streams are detected
805    // instead of being silently truncated.
806    let mut limited = decoder.take(max_decompressed as u64 + 1);
807    let mut data = Vec::new();
808    let mut guards = Vec::new();
809    let mut chunk = vec![0u8; ZSTD_DECOMPRESS_CHUNK];
810    loop {
811        let n = limited
812            .read(&mut chunk)
813            .context(error::DecompressZstdPromRemoteRequestSnafu)?;
814        if n == 0 {
815            break;
816        }
817        ensure!(
818            data.len() + n <= max_decompressed,
819            error::DecompressedBodyTooLargeSnafu {
820                size: (data.len() + n) as u64,
821                limit: max_decompressed as u64,
822            }
823        );
824        // Charge each chunk before it is appended so the aggregate quota
825        // bounds the memory while it is being materialized.
826        limiter.check_request_fits(n as u64, held_bytes)?;
827        let guard = limiter.acquire(n as u64).await?;
828        held_bytes += guard.granted_bytes();
829        guards.push(guard);
830        data.extend_from_slice(&chunk[..n]);
831    }
832    Ok(ChargedBuffer { data, guards })
833}
834
835/// Decompresses a raw Snappy body with the hard decoded-size cap enforced,
836/// without charging the aggregate request-memory limiter.
837///
838/// Used for response bodies (remote read replies) and tests; request bodies
839/// must use [`snappy_decompress_limited`] instead so their decoded size is
840/// also charged to the aggregate quota.
841#[inline]
842pub fn snappy_decompress(buf: &[u8]) -> Result<Vec<u8>> {
843    let decoded_len =
844        snap::raw::decompress_len(buf).context(error::DecompressSnappyPromRemoteRequestSnafu)?;
845    ensure!(
846        decoded_len <= MAX_DECOMPRESSED_REQUEST_SIZE,
847        error::DecompressedBodyTooLargeSnafu {
848            size: decoded_len as u64,
849            limit: MAX_DECOMPRESSED_REQUEST_SIZE as u64,
850        }
851    );
852    let mut decoder = Decoder::new();
853    decoder
854        .decompress_vec(buf)
855        .context(error::DecompressSnappyPromRemoteRequestSnafu)
856}
857
858#[inline]
859pub fn snappy_compress(buf: &[u8]) -> Result<Vec<u8>> {
860    let mut encoder = Encoder::new();
861    encoder
862        .compress_vec(buf)
863        .context(error::CompressPromRemoteRequestSnafu)
864}
865
866/// Mock timeseries for test, it is both used in servers and frontend crate
867/// So we present it here
868pub fn mock_timeseries() -> Vec<TimeSeries> {
869    vec![
870        TimeSeries {
871            labels: vec![
872                new_label(METRIC_NAME_LABEL.to_string(), "metric1".to_string()),
873                new_label("job".to_string(), "spark".to_string()),
874            ],
875            samples: vec![
876                Sample {
877                    value: 1.0f64,
878                    timestamp: 1000,
879                },
880                Sample {
881                    value: 2.0f64,
882                    timestamp: 2000,
883                },
884            ],
885            ..Default::default()
886        },
887        TimeSeries {
888            labels: vec![
889                new_label(METRIC_NAME_LABEL.to_string(), "metric2".to_string()),
890                new_label("instance".to_string(), "test_host1".to_string()),
891                new_label("idc".to_string(), "z001".to_string()),
892            ],
893            samples: vec![
894                Sample {
895                    value: 3.0f64,
896                    timestamp: 1000,
897                },
898                Sample {
899                    value: 4.0f64,
900                    timestamp: 2000,
901                },
902            ],
903            ..Default::default()
904        },
905        TimeSeries {
906            labels: vec![
907                new_label(METRIC_NAME_LABEL.to_string(), "metric3".to_string()),
908                new_label("idc".to_string(), "z002".to_string()),
909                new_label("app".to_string(), "biz".to_string()),
910            ],
911            samples: vec![
912                Sample {
913                    value: 5.0f64,
914                    timestamp: 1000,
915                },
916                Sample {
917                    value: 6.0f64,
918                    timestamp: 2000,
919                },
920                Sample {
921                    value: 7.0f64,
922                    timestamp: 3000,
923                },
924            ],
925            ..Default::default()
926        },
927    ]
928}
929
930/// Add new labels to the mock timeseries.
931pub fn mock_timeseries_new_label() -> Vec<TimeSeries> {
932    let ts_demo_metrics = TimeSeries {
933        labels: vec![
934            new_label(METRIC_NAME_LABEL.to_string(), "demo_metrics".to_string()),
935            new_label("idc".to_string(), "idc3".to_string()),
936            new_label("new_label1".to_string(), "foo".to_string()),
937        ],
938        samples: vec![Sample {
939            value: 42.0,
940            timestamp: 3000,
941        }],
942        ..Default::default()
943    };
944    let ts_multi_labels = TimeSeries {
945        labels: vec![
946            new_label(METRIC_NAME_LABEL.to_string(), "metric1".to_string()),
947            new_label("idc".to_string(), "idc4".to_string()),
948            new_label("env".to_string(), "prod".to_string()),
949            new_label("host".to_string(), "host9".to_string()),
950            new_label("new_label2".to_string(), "bar".to_string()),
951        ],
952        samples: vec![Sample {
953            value: 99.0,
954            timestamp: 4000,
955        }],
956        ..Default::default()
957    };
958
959    vec![ts_demo_metrics, ts_multi_labels]
960}
961
962/// Add new labels to the mock timeseries.
963pub fn mock_timeseries_special_labels() -> Vec<TimeSeries> {
964    let idc3_schema = TimeSeries {
965        labels: vec![
966            new_label(METRIC_NAME_LABEL.to_string(), "idc3_lo_table".to_string()),
967            new_label(DATABASE_LABEL.to_string(), "idc3".to_string()),
968            new_label(PHYSICAL_TABLE_LABEL.to_string(), "f1".to_string()),
969        ],
970        samples: vec![Sample {
971            value: 42.0,
972            timestamp: 3000,
973        }],
974        ..Default::default()
975    };
976    let idc4_schema = TimeSeries {
977        labels: vec![
978            new_label(
979                METRIC_NAME_LABEL.to_string(),
980                "idc4_local_table".to_string(),
981            ),
982            new_label(DATABASE_LABEL.to_string(), "idc4".to_string()),
983            new_label(PHYSICAL_TABLE_LABEL.to_string(), "f2".to_string()),
984        ],
985        samples: vec![Sample {
986            value: 99.0,
987            timestamp: 4000,
988        }],
989        ..Default::default()
990    };
991
992    vec![idc3_schema, idc4_schema]
993}
994
995#[cfg(test)]
996mod tests {
997    use std::sync::Arc;
998
999    use api::prom_store::remote::LabelMatcher;
1000    use api::v1::{ColumnDataType, Row, SemanticType};
1001    use arrow::array::{
1002        DictionaryArray, Float64Array, StringArray, TimestampMillisecondArray, UInt32Array,
1003    };
1004    use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema, UInt32Type};
1005    use common_memory_manager::OnExhaustedPolicy;
1006    use common_recordbatch::DfRecordBatch;
1007    use datafusion::prelude::SessionContext;
1008    use datatypes::data_type::ConcreteDataType;
1009    use datatypes::schema::{ColumnSchema, Schema};
1010    use datatypes::vectors::{
1011        Float64Vector, Int32Vector, StringVector, TimestampMillisecondVector,
1012    };
1013    use table::table::adapter::DfTableProviderAdapter;
1014    use table::test_util::MemTable;
1015
1016    use super::*;
1017
1018    const EQ_TYPE: i32 = MatcherType::Eq as i32;
1019    const NEQ_TYPE: i32 = MatcherType::Neq as i32;
1020    const RE_TYPE: i32 = MatcherType::Re as i32;
1021
1022    #[test]
1023    fn test_validate_matchers_regex_syntax() {
1024        for op in [MatcherType::Re, MatcherType::Nre] {
1025            for (value, valid) in [
1026                ("api|web", true),
1027                ("(?s)api.web", true),
1028                ("(?x) api", true),
1029                ("(?x) api # comment", false),
1030                ("[", false),
1031                // Wrapping must not make an invalid original pattern valid.
1032                ("a)|(?:b", false),
1033            ] {
1034                let matcher = LabelMatcher {
1035                    name: "job".into(),
1036                    value: value.into(),
1037                    r#type: op as i32,
1038                };
1039                assert_eq!(
1040                    valid,
1041                    validate_matchers(&[matcher]).is_ok(),
1042                    "{op:?}: {value}"
1043                );
1044            }
1045        }
1046    }
1047
1048    #[test]
1049    fn test_table_name() {
1050        let q = Query {
1051            start_timestamp_ms: 1000,
1052            end_timestamp_ms: 2000,
1053            matchers: vec![],
1054            ..Default::default()
1055        };
1056        let err = table_name(&q).unwrap_err();
1057        assert!(matches!(err, error::Error::InvalidPromRemoteRequest { .. }));
1058
1059        let q = Query {
1060            start_timestamp_ms: 1000,
1061            end_timestamp_ms: 2000,
1062            matchers: vec![LabelMatcher {
1063                name: METRIC_NAME_LABEL.to_string(),
1064                value: "test".to_string(),
1065                r#type: EQ_TYPE,
1066            }],
1067            ..Default::default()
1068        };
1069        assert_eq!("test", table_name(&q).unwrap());
1070
1071        for matchers in [
1072            vec![LabelMatcher {
1073                name: METRIC_NAME_LABEL.to_string(),
1074                value: "test.*".to_string(),
1075                r#type: RE_TYPE,
1076            }],
1077            vec![LabelMatcher {
1078                name: METRIC_NAME_LABEL.to_string(),
1079                value: String::new(),
1080                r#type: EQ_TYPE,
1081            }],
1082            vec![
1083                LabelMatcher {
1084                    name: METRIC_NAME_LABEL.to_string(),
1085                    value: "test".to_string(),
1086                    r#type: EQ_TYPE,
1087                },
1088                LabelMatcher {
1089                    name: METRIC_NAME_LABEL.to_string(),
1090                    value: "other".to_string(),
1091                    r#type: EQ_TYPE,
1092                },
1093            ],
1094        ] {
1095            let q = Query {
1096                matchers,
1097                ..Default::default()
1098            };
1099            assert!(matches!(
1100                table_name(&q),
1101                Err(error::Error::InvalidPromRemoteRequest { .. })
1102            ));
1103        }
1104    }
1105
1106    #[test]
1107    #[allow(deprecated)]
1108    fn test_extract_schema_from_query() {
1109        let query = Query::default();
1110        assert_eq!(None, extract_schema_from_query(&query));
1111
1112        for label in [DATABASE_LABEL, DATABASE_LABEL_ALT, SCHEMA_LABEL] {
1113            let query = Query {
1114                matchers: vec![LabelMatcher {
1115                    name: label.to_string(),
1116                    value: "selected_schema".to_string(),
1117                    r#type: EQ_TYPE,
1118                }],
1119                ..Default::default()
1120            };
1121            assert_eq!(
1122                Some("selected_schema".to_string()),
1123                extract_schema_from_query(&query)
1124            );
1125        }
1126
1127        let query = Query {
1128            matchers: vec![LabelMatcher {
1129                name: DATABASE_LABEL.to_string(),
1130                value: "selected_schema".to_string(),
1131                r#type: NEQ_TYPE,
1132            }],
1133            ..Default::default()
1134        };
1135        assert_eq!(None, extract_schema_from_query(&query));
1136    }
1137
1138    #[test]
1139    fn test_query_to_plan() {
1140        let q = Query {
1141            start_timestamp_ms: 1000,
1142            end_timestamp_ms: 2000,
1143            matchers: vec![LabelMatcher {
1144                name: METRIC_NAME_LABEL.to_string(),
1145                value: "test".to_string(),
1146                r#type: EQ_TYPE,
1147            }],
1148            ..Default::default()
1149        };
1150
1151        let schema = Arc::new(Schema::new(vec![
1152            ColumnSchema::new(
1153                greptime_timestamp(),
1154                ConcreteDataType::timestamp_millisecond_datatype(),
1155                true,
1156            ),
1157            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
1158            ColumnSchema::new("instance", ConcreteDataType::string_datatype(), true),
1159            ColumnSchema::new("job", ConcreteDataType::string_datatype(), true),
1160            ColumnSchema::new("service.name", ConcreteDataType::string_datatype(), true),
1161            ColumnSchema::new("Region", ConcreteDataType::string_datatype(), true),
1162        ]));
1163        let recordbatch = RecordBatch::new(
1164            schema,
1165            vec![
1166                Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as _,
1167                Arc::new(Float64Vector::from_vec(vec![3.0])) as _,
1168                Arc::new(StringVector::from(vec!["host1"])) as _,
1169                Arc::new(StringVector::from(vec!["job"])) as _,
1170                Arc::new(StringVector::from(vec!["api"])) as _,
1171                Arc::new(StringVector::from(vec!["us"])) as _,
1172            ],
1173        )
1174        .unwrap();
1175
1176        let ctx = SessionContext::new();
1177        let table = MemTable::table("test", recordbatch);
1178        let table_provider = Arc::new(DfTableProviderAdapter::new(table));
1179
1180        let dataframe = ctx.read_table(table_provider.clone()).unwrap();
1181        let plan = query_to_plan(dataframe, &q, greptime_timestamp()).unwrap();
1182        let display_string = format!("{}", plan.display_indent());
1183
1184        let ts_col = greptime_timestamp();
1185        let expected = format!(
1186            "Filter: ?table?.{} >= TimestampMillisecond(1000, None) AND ?table?.{} <= TimestampMillisecond(2000, None)\n  TableScan: ?table?",
1187            ts_col, ts_col
1188        );
1189        assert_eq!(expected, display_string);
1190
1191        let q = Query {
1192            start_timestamp_ms: 1000,
1193            end_timestamp_ms: 2000,
1194            matchers: vec![
1195                LabelMatcher {
1196                    name: METRIC_NAME_LABEL.to_string(),
1197                    value: "test".to_string(),
1198                    r#type: EQ_TYPE,
1199                },
1200                LabelMatcher {
1201                    name: "job".to_string(),
1202                    value: ".*prom.*".to_string(),
1203                    r#type: RE_TYPE,
1204                },
1205                LabelMatcher {
1206                    name: "instance".to_string(),
1207                    value: "localhost".to_string(),
1208                    r#type: NEQ_TYPE,
1209                },
1210                LabelMatcher {
1211                    name: "service.name".to_string(),
1212                    value: "api".to_string(),
1213                    r#type: EQ_TYPE,
1214                },
1215                LabelMatcher {
1216                    name: "Region".to_string(),
1217                    value: "us".to_string(),
1218                    r#type: EQ_TYPE,
1219                },
1220            ],
1221            ..Default::default()
1222        };
1223
1224        let dataframe = ctx.read_table(table_provider).unwrap();
1225        let plan = query_to_plan(dataframe, &q, greptime_timestamp()).unwrap();
1226        let display_string = format!("{}", plan.display_indent());
1227
1228        let ts_col = greptime_timestamp();
1229        let expected = format!(
1230            "Filter: ?table?.{} >= TimestampMillisecond(1000, None) AND ?table?.{} <= TimestampMillisecond(2000, None) AND regexp_match(?table?.job, Utf8(\"^(?s:.*prom.*)$\")) IS NOT NULL AND (?table?.instance != Utf8(\"localhost\") OR ?table?.instance IS NULL) AND ?table?.service.name = Utf8(\"api\") AND ?table?.Region = Utf8(\"us\")\n  TableScan: ?table?",
1231            ts_col, ts_col
1232        );
1233        assert_eq!(expected, display_string);
1234    }
1235
1236    #[tokio::test]
1237    async fn test_remote_read_time_hints() {
1238        use api::prom_store::remote::ReadHints;
1239
1240        let ctx = SessionContext::new();
1241        let timestamps = vec![-1, 0, 999, 1000, 1500, 2000, 2001, 3000];
1242        let batch = DfRecordBatch::try_from_iter(vec![(
1243            greptime_timestamp(),
1244            Arc::new(TimestampMillisecondArray::from(timestamps)) as ArrayRef,
1245        )])
1246        .unwrap();
1247        ctx.register_batch("metrics", batch).unwrap();
1248
1249        for (outer, hinted, expected) in [
1250            ((1000, 2000), None, vec![1000, 1500, 2000]),
1251            ((1000, 2000), Some((0, 0)), vec![1000, 1500, 2000]),
1252            ((1000, 2000), Some((0, 1500)), vec![1000, 1500, 2000]),
1253            ((1000, 2000), Some((1500, 0)), vec![1000, 1500, 2000]),
1254            ((1000, 2000), Some((-1, 1500)), vec![1000, 1500, 2000]),
1255            ((1000, 2000), Some((1500, -1)), vec![1000, 1500, 2000]),
1256            ((1000, 2000), Some((2000, 1000)), vec![1000, 1500, 2000]),
1257            ((1000, 2000), Some((1000, 2000)), vec![1000, 1500, 2000]),
1258            ((1000, 2000), Some((1, 3000)), vec![1000, 1500, 2000]),
1259            ((1000, 2000), Some((1001, 1999)), vec![1500]),
1260            ((1000, 2000), Some((1500, 3000)), vec![1500, 2000]),
1261            ((1000, 2000), Some((1, 1500)), vec![1000, 1500]),
1262            ((1000, 2000), Some((1500, 1500)), vec![1500]),
1263            ((1000, 2000), Some((2000, 3000)), vec![2000]),
1264            ((1000, 2000), Some((2001, 3000)), vec![]),
1265            ((1000, 2000), Some((1, 999)), vec![]),
1266            ((2000, 1000), Some((1, 3000)), vec![]),
1267            ((-1, 1000), Some((0, 1000)), vec![-1, 0, 999, 1000]),
1268        ] {
1269            let query = Query {
1270                start_timestamp_ms: outer.0,
1271                end_timestamp_ms: outer.1,
1272                hints: hinted.map(|(start_ms, end_ms)| ReadHints {
1273                    start_ms,
1274                    end_ms,
1275                    // These describe evaluation, not sampling or aggregation instructions.
1276                    step_ms: 10000,
1277                    range_ms: 300000,
1278                    func: "rate".into(),
1279                    grouping: vec!["job".into()],
1280                    by: true,
1281                }),
1282                ..Default::default()
1283            };
1284            let plan = query_to_plan(
1285                ctx.table("metrics").await.unwrap(),
1286                &query,
1287                greptime_timestamp(),
1288            )
1289            .unwrap();
1290            let batches = ctx
1291                .execute_logical_plan(plan)
1292                .await
1293                .unwrap()
1294                .collect()
1295                .await
1296                .unwrap();
1297            let actual: Vec<i64> = batches
1298                .iter()
1299                .flat_map(|batch| {
1300                    batch
1301                        .column(0)
1302                        .as_primitive::<TimestampMillisecondType>()
1303                        .values()
1304                        .to_vec()
1305                })
1306                .collect();
1307            assert_eq!(expected, actual, "outer={outer:?}, hints={hinted:?}");
1308        }
1309    }
1310
1311    #[tokio::test]
1312    async fn test_remote_read_label_matcher_semantics() {
1313        let ctx = SessionContext::new();
1314        let batch = DfRecordBatch::try_from_iter(vec![
1315            (
1316                greptime_timestamp(),
1317                Arc::new(TimestampMillisecondArray::from(vec![1000; 6])) as ArrayRef,
1318            ),
1319            (
1320                "job",
1321                Arc::new(StringArray::from(vec![
1322                    Some("api"),
1323                    Some("my-api-server"),
1324                    Some(""),
1325                    None,
1326                    Some("web"),
1327                    Some("api\nweb"),
1328                ])) as ArrayRef,
1329            ),
1330            (
1331                "id",
1332                Arc::new(UInt32Array::from(vec![0, 1, 2, 3, 4, 5])) as ArrayRef,
1333            ),
1334        ])
1335        .unwrap();
1336        ctx.register_batch("metrics", batch).unwrap();
1337        for (name, op, value, expected) in [
1338            ("job", MatcherType::Eq, "api", vec![0]),
1339            ("job", MatcherType::Neq, "api", vec![1, 2, 3, 4, 5]),
1340            ("job", MatcherType::Eq, "", vec![2, 3]),
1341            ("job", MatcherType::Neq, "", vec![0, 1, 4, 5]),
1342            ("job", MatcherType::Re, "api", vec![0]),
1343            ("job", MatcherType::Nre, "api", vec![1, 2, 3, 4, 5]),
1344            ("job", MatcherType::Re, "api|web", vec![0, 4]),
1345            ("job", MatcherType::Nre, "api|web", vec![1, 2, 3, 5]),
1346            ("job", MatcherType::Re, "", vec![2, 3]),
1347            ("job", MatcherType::Nre, "", vec![0, 1, 4, 5]),
1348            ("job", MatcherType::Re, ".*", vec![0, 1, 2, 3, 4, 5]),
1349            ("job", MatcherType::Nre, ".*", vec![]),
1350            ("job", MatcherType::Re, ".+", vec![0, 1, 4, 5]),
1351            ("job", MatcherType::Nre, ".+", vec![2, 3]),
1352            ("job", MatcherType::Re, "(?m)api", vec![0]),
1353            ("job", MatcherType::Re, "api.web", vec![5]),
1354            ("job", MatcherType::Nre, "api.web", vec![0, 1, 2, 3, 4]),
1355            ("job", MatcherType::Re, "(?-s:api.web)", vec![]),
1356            ("job", MatcherType::Re, "(api)?", vec![0, 2, 3]),
1357            ("missing", MatcherType::Eq, "", vec![0, 1, 2, 3, 4, 5]),
1358            ("missing", MatcherType::Eq, "us", vec![]),
1359            ("missing", MatcherType::Neq, "us", vec![0, 1, 2, 3, 4, 5]),
1360            ("missing", MatcherType::Neq, "", vec![]),
1361            ("missing", MatcherType::Re, ".*", vec![0, 1, 2, 3, 4, 5]),
1362            ("missing", MatcherType::Re, ".+", vec![]),
1363            ("missing", MatcherType::Nre, ".*", vec![]),
1364            ("missing", MatcherType::Nre, ".+", vec![0, 1, 2, 3, 4, 5]),
1365            ("missing", MatcherType::Re, "", vec![0, 1, 2, 3, 4, 5]),
1366            ("missing", MatcherType::Nre, "", vec![]),
1367        ] {
1368            let query = Query {
1369                start_timestamp_ms: 1000,
1370                end_timestamp_ms: 1000,
1371                matchers: vec![LabelMatcher {
1372                    name: name.into(),
1373                    value: value.into(),
1374                    r#type: op as i32,
1375                }],
1376                ..Default::default()
1377            };
1378            let plan = query_to_plan(
1379                ctx.table("metrics").await.unwrap(),
1380                &query,
1381                greptime_timestamp(),
1382            )
1383            .unwrap_or_else(|err| panic!("{name} {op:?} {value:?}: {err}"));
1384            let batches = ctx
1385                .execute_logical_plan(plan)
1386                .await
1387                .unwrap()
1388                .collect()
1389                .await
1390                .unwrap();
1391            let actual: Vec<u32> = batches
1392                .iter()
1393                .flat_map(|batch| {
1394                    batch
1395                        .column(2)
1396                        .as_primitive::<UInt32Type>()
1397                        .values()
1398                        .to_vec()
1399                })
1400                .collect();
1401            assert_eq!(expected, actual, "{name} {op:?} {value:?}");
1402        }
1403    }
1404
1405    #[tokio::test]
1406    async fn test_remote_read_matcher_combinations_and_label_types() {
1407        let labels = StringArray::from(vec![Some("api"), Some("api"), None, Some("api")]);
1408        for label_type in [
1409            DataType::Utf8,
1410            DataType::LargeUtf8,
1411            DataType::Utf8View,
1412            DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
1413        ] {
1414            let ctx = SessionContext::new();
1415            let batch = DfRecordBatch::try_from_iter(vec![
1416                (
1417                    greptime_timestamp(),
1418                    Arc::new(TimestampMillisecondArray::from(vec![999, 1000, 2000, 2001]))
1419                        as ArrayRef,
1420                ),
1421                ("Job.Name", casts::cast(&labels, &label_type).unwrap()),
1422            ])
1423            .unwrap();
1424            ctx.register_batch("metrics", batch).unwrap();
1425            let mut cases = vec![
1426                (vec![("Job.Name", MatcherType::Re, ".*")], vec![1000, 2000]),
1427                (vec![("Job.Name", MatcherType::Nre, ".+")], vec![2000]),
1428            ];
1429            // Exercise combinations once; other representations only need regex/NULL coverage.
1430            if label_type == DataType::Utf8 {
1431                cases.extend([
1432                    (
1433                        vec![
1434                            ("Job.Name", MatcherType::Re, "api|web"),
1435                            ("Job.Name", MatcherType::Neq, "web"),
1436                        ],
1437                        vec![1000],
1438                    ),
1439                    (
1440                        vec![
1441                            ("Job.Name", MatcherType::Eq, ""),
1442                            ("Job.Name", MatcherType::Neq, "api"),
1443                        ],
1444                        vec![2000],
1445                    ),
1446                    (
1447                        vec![
1448                            ("Job.Name", MatcherType::Eq, "api"),
1449                            ("Job.Name", MatcherType::Eq, "web"),
1450                        ],
1451                        vec![],
1452                    ),
1453                    (
1454                        vec![
1455                            ("job.name", MatcherType::Eq, ""),
1456                            ("Job.Name", MatcherType::Re, ".*"),
1457                        ],
1458                        vec![1000, 2000],
1459                    ),
1460                ]);
1461            }
1462            for (matchers, expected) in cases {
1463                let mut query = Query {
1464                    start_timestamp_ms: 1000,
1465                    end_timestamp_ms: 2000,
1466                    matchers: matchers
1467                        .iter()
1468                        .map(|(name, op, value)| LabelMatcher {
1469                            name: (*name).into(),
1470                            value: (*value).into(),
1471                            r#type: *op as i32,
1472                        })
1473                        .collect(),
1474                    ..Default::default()
1475                };
1476                query.matchers.push(LabelMatcher {
1477                    name: METRIC_NAME_LABEL.into(),
1478                    value: "metrics".into(),
1479                    r#type: EQ_TYPE,
1480                });
1481                let plan = query_to_plan(
1482                    ctx.table("metrics").await.unwrap(),
1483                    &query,
1484                    greptime_timestamp(),
1485                )
1486                .unwrap();
1487                let batches = ctx
1488                    .execute_logical_plan(plan)
1489                    .await
1490                    .unwrap()
1491                    .collect()
1492                    .await
1493                    .unwrap();
1494                let actual: Vec<i64> = batches
1495                    .iter()
1496                    .flat_map(|batch| {
1497                        batch
1498                            .column(0)
1499                            .as_primitive::<TimestampMillisecondType>()
1500                            .values()
1501                            .to_vec()
1502                    })
1503                    .collect();
1504                assert_eq!(expected, actual, "{label_type:?}: {matchers:?}");
1505            }
1506        }
1507    }
1508
1509    fn column_schemas_with(
1510        mut kts_iter: Vec<(&str, ColumnDataType, SemanticType)>,
1511    ) -> Vec<api::v1::ColumnSchema> {
1512        kts_iter.push((
1513            greptime_value(),
1514            ColumnDataType::Float64,
1515            SemanticType::Field,
1516        ));
1517        kts_iter.push((
1518            greptime_timestamp(),
1519            ColumnDataType::TimestampMillisecond,
1520            SemanticType::Timestamp,
1521        ));
1522
1523        kts_iter
1524            .into_iter()
1525            .map(|(k, t, s)| api::v1::ColumnSchema {
1526                column_name: k.to_string(),
1527                datatype: t as i32,
1528                semantic_type: s as i32,
1529                ..Default::default()
1530            })
1531            .collect()
1532    }
1533
1534    fn make_row_with_label(l1: &str, value: f64, timestamp: i64) -> Row {
1535        Row {
1536            values: vec![
1537                api::v1::Value {
1538                    value_data: Some(api::v1::value::ValueData::StringValue(l1.to_string())),
1539                },
1540                api::v1::Value {
1541                    value_data: Some(api::v1::value::ValueData::F64Value(value)),
1542                },
1543                api::v1::Value {
1544                    value_data: Some(api::v1::value::ValueData::TimestampMillisecondValue(
1545                        timestamp,
1546                    )),
1547                },
1548            ],
1549        }
1550    }
1551
1552    fn make_row_with_2_labels(l1: &str, l2: &str, value: f64, timestamp: i64) -> Row {
1553        Row {
1554            values: vec![
1555                api::v1::Value {
1556                    value_data: Some(api::v1::value::ValueData::StringValue(l1.to_string())),
1557                },
1558                api::v1::Value {
1559                    value_data: Some(api::v1::value::ValueData::StringValue(l2.to_string())),
1560                },
1561                api::v1::Value {
1562                    value_data: Some(api::v1::value::ValueData::F64Value(value)),
1563                },
1564                api::v1::Value {
1565                    value_data: Some(api::v1::value::ValueData::TimestampMillisecondValue(
1566                        timestamp,
1567                    )),
1568                },
1569            ],
1570        }
1571    }
1572
1573    #[test]
1574    fn test_write_request_to_row_insert_exprs() {
1575        let write_request = WriteRequest {
1576            timeseries: mock_timeseries(),
1577            ..Default::default()
1578        };
1579
1580        let mut exprs = to_grpc_row_insert_requests(&write_request)
1581            .unwrap()
1582            .0
1583            .inserts;
1584        exprs.sort_unstable_by(|l, r| l.table_name.cmp(&r.table_name));
1585        assert_eq!(3, exprs.len());
1586        assert_eq!("metric1", exprs[0].table_name);
1587        assert_eq!("metric2", exprs[1].table_name);
1588        assert_eq!("metric3", exprs[2].table_name);
1589
1590        let rows = exprs[0].rows.as_ref().unwrap();
1591        let schema = &rows.schema;
1592        let rows = &rows.rows;
1593        assert_eq!(2, rows.len());
1594        assert_eq!(3, schema.len());
1595        assert_eq!(
1596            column_schemas_with(vec![("job", ColumnDataType::String, SemanticType::Tag)]),
1597            *schema
1598        );
1599        assert_eq!(
1600            &vec![
1601                make_row_with_label("spark", 1.0, 1000),
1602                make_row_with_label("spark", 2.0, 2000),
1603            ],
1604            rows
1605        );
1606
1607        let rows = exprs[1].rows.as_ref().unwrap();
1608        let schema = &rows.schema;
1609        let rows = &rows.rows;
1610        assert_eq!(2, rows.len());
1611        assert_eq!(4, schema.len());
1612        assert_eq!(
1613            column_schemas_with(vec![
1614                ("instance", ColumnDataType::String, SemanticType::Tag),
1615                ("idc", ColumnDataType::String, SemanticType::Tag)
1616            ]),
1617            *schema
1618        );
1619        assert_eq!(
1620            &vec![
1621                make_row_with_2_labels("test_host1", "z001", 3.0, 1000),
1622                make_row_with_2_labels("test_host1", "z001", 4.0, 2000),
1623            ],
1624            rows
1625        );
1626
1627        let rows = exprs[2].rows.as_ref().unwrap();
1628        let schema = &rows.schema;
1629        let rows = &rows.rows;
1630        assert_eq!(3, rows.len());
1631        assert_eq!(4, schema.len());
1632        assert_eq!(
1633            column_schemas_with(vec![
1634                ("idc", ColumnDataType::String, SemanticType::Tag),
1635                ("app", ColumnDataType::String, SemanticType::Tag)
1636            ]),
1637            *schema
1638        );
1639        assert_eq!(
1640            &vec![
1641                make_row_with_2_labels("z002", "biz", 5.0, 1000),
1642                make_row_with_2_labels("z002", "biz", 6.0, 2000),
1643                make_row_with_2_labels("z002", "biz", 7.0, 3000),
1644            ],
1645            rows
1646        );
1647    }
1648
1649    #[test]
1650    fn test_native_histogram_remote_read_wire_fixture() {
1651        use api::greptime_proto::io::prometheus::write::v2::{
1652            BucketSpan, Histogram,
1653            histogram::{Count, ZeroCount},
1654        };
1655        use api::prom_store::remote::{QueryResult, ReadResponse};
1656        use common_query::native_histogram::testing::histogram_array;
1657        use prost::Message;
1658
1659        let histograms = vec![
1660            Histogram {
1661                count: Some(Count::CountInt((1 << 53) + 13)),
1662                zero_count: Some(ZeroCount::ZeroCountInt((1 << 53) + 1)),
1663                sum: 10.0,
1664                schema: 1,
1665                zero_threshold: 0.001,
1666                reset_hint: 2,
1667                start_timestamp: 123,
1668                positive_spans: vec![
1669                    BucketSpan {
1670                        offset: -2,
1671                        length: 2,
1672                    },
1673                    BucketSpan {
1674                        offset: 3,
1675                        length: 1,
1676                    },
1677                ],
1678                positive_deltas: vec![1, 2, -1],
1679                negative_spans: vec![
1680                    BucketSpan {
1681                        offset: -3,
1682                        length: 1,
1683                    },
1684                    BucketSpan {
1685                        offset: 2,
1686                        length: 2,
1687                    },
1688                ],
1689                negative_deltas: vec![1, 2, -1],
1690                ..Default::default()
1691            },
1692            Histogram {
1693                count: Some(Count::CountFloat(6.0)),
1694                zero_count: Some(ZeroCount::ZeroCountFloat(0.5)),
1695                sum: 20.0,
1696                schema: 2,
1697                zero_threshold: 0.002,
1698                reset_hint: 3,
1699                positive_spans: vec![BucketSpan {
1700                    offset: 3,
1701                    length: 2,
1702                }],
1703                positive_counts: vec![2.0, 3.5],
1704                ..Default::default()
1705            },
1706            Histogram {
1707                count: Some(Count::CountInt(1)),
1708                sum: 1.0,
1709                schema: -53,
1710                custom_values: vec![1.0, 2.0],
1711                positive_spans: vec![BucketSpan {
1712                    offset: 0,
1713                    length: 1,
1714                }],
1715                positive_deltas: vec![1],
1716                ..Default::default()
1717            },
1718            Histogram {
1719                count: Some(Count::CountFloat(3.5)),
1720                sum: 4.0,
1721                schema: -53,
1722                custom_values: vec![1.0, 2.0],
1723                reset_hint: 3,
1724                positive_spans: vec![BucketSpan {
1725                    offset: 0,
1726                    length: 2,
1727                }],
1728                positive_counts: vec![1.0, 2.5],
1729                ..Default::default()
1730            },
1731            Histogram {
1732                count: Some(Count::CountInt(0)),
1733                ..Default::default()
1734            },
1735            Histogram {
1736                count: Some(Count::CountFloat(0.0)),
1737                ..Default::default()
1738            },
1739            Histogram {
1740                count: Some(Count::CountInt(8)),
1741                sum: f64::from_bits(0x7ff8_0000_0000_0123),
1742                positive_spans: vec![BucketSpan {
1743                    offset: 0,
1744                    length: 2,
1745                }],
1746                positive_deltas: vec![3, -1],
1747                ..Default::default()
1748            },
1749            Histogram {
1750                count: Some(Count::CountInt(0)),
1751                sum: f64::from_bits(0x7ff0_0000_0000_0002),
1752                ..Default::default()
1753            },
1754            Histogram {
1755                count: Some(Count::CountInt(i64::MAX as u64)),
1756                zero_count: Some(ZeroCount::ZeroCountInt(i64::MAX as u64)),
1757                ..Default::default()
1758            },
1759        ];
1760        let values = histograms
1761            .iter()
1762            .map(|h| Some(native_histogram::encode_native_histogram(h).unwrap()))
1763            .collect::<Vec<_>>();
1764        let array = histogram_array(&values);
1765        let buckets = array
1766            .column_by_name("positive_buckets_i64")
1767            .unwrap()
1768            .as_list::<i32>()
1769            .value(0);
1770        assert_eq!(
1771            buckets
1772                .as_primitive::<arrow::datatypes::Int64Type>()
1773                .values()
1774                .as_ref(),
1775            &[1, 3, 2]
1776        );
1777        let arrow_schema = Arc::new(ArrowSchema::new(vec![
1778            Field::new(
1779                "ts",
1780                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
1781                false,
1782            ),
1783            Field::new("histogram", array.data_type().clone(), true),
1784        ]));
1785        let schema = Arc::new(Schema::try_from(arrow_schema.clone()).unwrap());
1786        let batch = DfRecordBatch::try_new(
1787            arrow_schema,
1788            vec![
1789                Arc::new(TimestampMillisecondArray::from(
1790                    (1..=9).map(|i| i * 1000).collect::<Vec<_>>(),
1791                )),
1792                Arc::new(array),
1793            ],
1794        )
1795        .unwrap();
1796        let batches = RecordBatches::try_new(
1797            schema.clone(),
1798            vec![RecordBatch::from_df_record_batch(schema, batch)],
1799        )
1800        .unwrap();
1801        let response = ReadResponse {
1802            results: vec![QueryResult {
1803                timeseries: recordbatches_to_timeseries(
1804                    "native_histogram_remote_read",
1805                    "ts",
1806                    "histogram",
1807                    batches,
1808                )
1809                .unwrap(),
1810            }],
1811        };
1812        let body = snappy_compress(&response.encode_to_vec()).unwrap();
1813        let mut decoded =
1814            ReadResponse::decode(snappy_decompress(&body).unwrap().as_slice()).unwrap();
1815        let mut expected = ReadResponse::decode(
1816            include_bytes!(
1817                "../../../tests/compatibility/wire/native_histogram_remote_read/response.pb"
1818            )
1819            .as_slice(),
1820        )
1821        .unwrap();
1822        let actual_histograms = &mut decoded.results[0].timeseries[0].histograms;
1823        assert_eq!(actual_histograms[0].positive_deltas, vec![1, 2, -1]);
1824        assert_eq!(actual_histograms[0].negative_deltas, vec![1, 2, -1]);
1825        assert_eq!(actual_histograms[6].positive_deltas, vec![3, -1]);
1826        for (actual, expected) in actual_histograms
1827            .iter_mut()
1828            .zip(&mut expected.results[0].timeseries[0].histograms)
1829        {
1830            assert_eq!(actual.sum.to_bits(), expected.sum.to_bits());
1831            actual.sum = 0.0;
1832            expected.sum = 0.0;
1833        }
1834        assert_eq!(decoded, expected);
1835        // The optional output is consumed by the pinned Prometheus iterator check.
1836        if let Some(path) = std::env::var_os("GREPTIME_NATIVE_HISTOGRAM_REMOTE_READ_OUTPUT") {
1837            std::fs::write(path, body).unwrap();
1838        }
1839    }
1840
1841    #[test]
1842    fn test_native_histogram_remote_read_groups_and_sorts_batches() {
1843        use api::greptime_proto::io::prometheus::write::v2::{Histogram, histogram::Count};
1844        use common_query::native_histogram::testing::histogram_array;
1845
1846        let integer = native_histogram::encode_native_histogram(&Histogram {
1847            count: Some(Count::CountInt(0)),
1848            sum: f64::from_bits(0x7ff0_0000_0000_0002),
1849            ..Default::default()
1850        })
1851        .unwrap();
1852        let float = native_histogram::encode_native_histogram(&Histogram {
1853            count: Some(Count::CountFloat(0.0)),
1854            ..Default::default()
1855        })
1856        .unwrap();
1857        let histograms = histogram_array(&[Some(integer), Some(float.clone()), None, Some(float)]);
1858        let arrow_schema = Arc::new(ArrowSchema::new(vec![
1859            Field::new(
1860                "event_time",
1861                ArrowDataType::Timestamp(TimeUnit::Microsecond, None),
1862                true,
1863            ),
1864            Field::new("legacy_histogram", histograms.data_type().clone(), true),
1865            Field::new_dictionary("instance", ArrowDataType::UInt32, ArrowDataType::Utf8, true),
1866        ]));
1867        let schema = Arc::new(Schema::try_from(arrow_schema.clone()).unwrap());
1868        let batch = |timestamps: Vec<Option<i64>>, labels: Vec<Option<u32>>| {
1869            RecordBatch::from_df_record_batch(
1870                schema.clone(),
1871                DfRecordBatch::try_new(
1872                    arrow_schema.clone(),
1873                    vec![
1874                        Arc::new(arrow::array::TimestampMicrosecondArray::from(timestamps)),
1875                        Arc::new(histograms.clone()),
1876                        Arc::new(DictionaryArray::<UInt32Type>::new(
1877                            UInt32Array::from(labels),
1878                            Arc::new(StringArray::from(vec![Some("b"), Some("a"), None])),
1879                        )),
1880                    ],
1881                )
1882                .unwrap(),
1883            )
1884        };
1885        let batches = vec![
1886            batch(
1887                vec![Some(4000), Some(3000), Some(5000), Some(-1001)],
1888                vec![Some(0), None, Some(0), Some(0)],
1889            ),
1890            batch(
1891                vec![Some(2000), Some(1000), Some(6000), None],
1892                vec![Some(0), Some(2), Some(1), Some(0)],
1893            ),
1894        ];
1895        let series = recordbatches_to_timeseries(
1896            "latency",
1897            "event_time",
1898            "legacy_histogram",
1899            RecordBatches::try_new(schema.clone(), batches).unwrap(),
1900        )
1901        .unwrap();
1902        assert_eq!(series.len(), 3);
1903        assert_eq!(
1904            series[0].labels,
1905            vec![new_label(
1906                METRIC_NAME_LABEL.to_string(),
1907                "latency".to_string()
1908            )]
1909        );
1910        assert_eq!(
1911            series[0]
1912                .histograms
1913                .iter()
1914                .map(|h| h.timestamp)
1915                .collect::<Vec<_>>(),
1916            vec![1, 3]
1917        );
1918        assert_eq!(series[1].labels[1].value, "a");
1919        assert!(series[1].histograms.is_empty());
1920        assert_eq!(series[2].labels[1].value, "b");
1921        assert_eq!(
1922            series[2]
1923                .histograms
1924                .iter()
1925                .map(|h| h.timestamp)
1926                .collect::<Vec<_>>(),
1927            vec![-2, 2, 4]
1928        );
1929        assert!(matches!(
1930            series[2].histograms[0].count,
1931            Some(api::prom_store::remote::histogram::Count::CountFloat(0.0))
1932        ));
1933        for histogram in &series[2].histograms[1..] {
1934            assert!(matches!(
1935                histogram.count,
1936                Some(api::prom_store::remote::histogram::Count::CountInt(0))
1937            ));
1938            assert_eq!(histogram.sum.to_bits(), 0x7ff0_0000_0000_0002);
1939        }
1940        assert!(
1941            series
1942                .iter()
1943                .all(|s| s.samples.is_empty()
1944                    && s.labels.iter().all(|l| l.name != "legacy_histogram"))
1945        );
1946    }
1947
1948    #[test]
1949    fn test_recordbatches_to_timeseries() {
1950        let schema = Arc::new(Schema::new(vec![
1951            ColumnSchema::new(
1952                greptime_timestamp(),
1953                ConcreteDataType::timestamp_millisecond_datatype(),
1954                true,
1955            ),
1956            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
1957            ColumnSchema::new("instance", ConcreteDataType::string_datatype(), true),
1958        ]));
1959
1960        let recordbatches = RecordBatches::try_new(
1961            schema.clone(),
1962            vec![
1963                RecordBatch::new(
1964                    schema.clone(),
1965                    vec![
1966                        Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as _,
1967                        Arc::new(Float64Vector::from_vec(vec![3.0])) as _,
1968                        Arc::new(StringVector::from(vec!["host1"])) as _,
1969                    ],
1970                )
1971                .unwrap(),
1972                RecordBatch::new(
1973                    schema,
1974                    vec![
1975                        Arc::new(TimestampMillisecondVector::from_vec(vec![2000])) as _,
1976                        Arc::new(Float64Vector::from_vec(vec![7.0])) as _,
1977                        Arc::new(StringVector::from(vec!["host2"])) as _,
1978                    ],
1979                )
1980                .unwrap(),
1981            ],
1982        )
1983        .unwrap();
1984
1985        let timeseries = recordbatches_to_timeseries(
1986            "metric1",
1987            greptime_timestamp(),
1988            greptime_value(),
1989            recordbatches,
1990        )
1991        .unwrap();
1992        assert_eq!(2, timeseries.len());
1993
1994        assert_eq!(
1995            vec![
1996                Label {
1997                    name: METRIC_NAME_LABEL.to_string(),
1998                    value: "metric1".to_string(),
1999                },
2000                Label {
2001                    name: "instance".to_string(),
2002                    value: "host1".to_string(),
2003                },
2004            ],
2005            timeseries[0].labels
2006        );
2007
2008        assert_eq!(
2009            timeseries[0].samples,
2010            vec![Sample {
2011                value: 3.0,
2012                timestamp: 1000,
2013            }]
2014        );
2015
2016        assert_eq!(
2017            vec![
2018                Label {
2019                    name: METRIC_NAME_LABEL.to_string(),
2020                    value: "metric1".to_string(),
2021                },
2022                Label {
2023                    name: "instance".to_string(),
2024                    value: "host2".to_string(),
2025                },
2026            ],
2027            timeseries[1].labels
2028        );
2029        assert_eq!(
2030            timeseries[1].samples,
2031            vec![Sample {
2032                value: 7.0,
2033                timestamp: 2000,
2034            }]
2035        );
2036    }
2037
2038    #[test]
2039    fn test_recordbatches_to_timeseries_merges_across_batches() {
2040        let schema = Arc::new(Schema::new(vec![
2041            ColumnSchema::new(
2042                greptime_timestamp(),
2043                ConcreteDataType::timestamp_millisecond_datatype(),
2044                true,
2045            ),
2046            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
2047            ColumnSchema::new("instance", ConcreteDataType::string_datatype(), true),
2048        ]));
2049
2050        let recordbatches = RecordBatches::try_new(
2051            schema.clone(),
2052            vec![
2053                RecordBatch::new(
2054                    schema.clone(),
2055                    vec![
2056                        Arc::new(TimestampMillisecondVector::from_vec(vec![3000, 1500])) as _,
2057                        Arc::new(Float64Vector::from_vec(vec![30.0, 15.0])) as _,
2058                        Arc::new(StringVector::from(vec!["host1", "host2"])) as _,
2059                    ],
2060                )
2061                .unwrap(),
2062                RecordBatch::new(
2063                    schema.clone(),
2064                    vec![
2065                        Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as _,
2066                        Arc::new(Float64Vector::from_vec(vec![10.0])) as _,
2067                        Arc::new(StringVector::from(vec!["host1"])) as _,
2068                    ],
2069                )
2070                .unwrap(),
2071                RecordBatch::new(
2072                    schema,
2073                    vec![
2074                        Arc::new(TimestampMillisecondVector::from_vec(vec![2000, 2500])) as _,
2075                        Arc::new(Float64Vector::from_vec(vec![20.0, 25.0])) as _,
2076                        Arc::new(StringVector::from(vec!["host1", "host2"])) as _,
2077                    ],
2078                )
2079                .unwrap(),
2080            ],
2081        )
2082        .unwrap();
2083
2084        let timeseries = recordbatches_to_timeseries(
2085            "cpu_usage",
2086            greptime_timestamp(),
2087            greptime_value(),
2088            recordbatches,
2089        )
2090        .unwrap();
2091
2092        assert_eq!(2, timeseries.len());
2093
2094        assert_eq!(
2095            vec![
2096                Label {
2097                    name: METRIC_NAME_LABEL.to_string(),
2098                    value: "cpu_usage".to_string(),
2099                },
2100                Label {
2101                    name: "instance".to_string(),
2102                    value: "host1".to_string(),
2103                },
2104            ],
2105            timeseries[0].labels
2106        );
2107        assert_eq!(
2108            vec![
2109                Sample {
2110                    value: 10.0,
2111                    timestamp: 1000,
2112                },
2113                Sample {
2114                    value: 20.0,
2115                    timestamp: 2000,
2116                },
2117                Sample {
2118                    value: 30.0,
2119                    timestamp: 3000,
2120                },
2121            ],
2122            timeseries[0].samples
2123        );
2124
2125        assert_eq!(
2126            vec![
2127                Label {
2128                    name: METRIC_NAME_LABEL.to_string(),
2129                    value: "cpu_usage".to_string(),
2130                },
2131                Label {
2132                    name: "instance".to_string(),
2133                    value: "host2".to_string(),
2134                },
2135            ],
2136            timeseries[1].labels
2137        );
2138        assert_eq!(
2139            vec![
2140                Sample {
2141                    value: 15.0,
2142                    timestamp: 1500,
2143                },
2144                Sample {
2145                    value: 25.0,
2146                    timestamp: 2500,
2147                },
2148            ],
2149            timeseries[1].samples
2150        );
2151    }
2152
2153    #[test]
2154    fn test_recordbatches_to_timeseries_borrows_and_groups_dictionary_labels() {
2155        let arrow_schema = Arc::new(ArrowSchema::new(vec![
2156            Field::new(
2157                greptime_timestamp(),
2158                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
2159                false,
2160            ),
2161            Field::new(greptime_value(), ArrowDataType::Float64, false),
2162            Field::new_dictionary("instance", ArrowDataType::UInt32, ArrowDataType::Utf8, true),
2163        ]));
2164        let schema = Arc::new(Schema::try_from(arrow_schema.clone()).unwrap());
2165        let instance = DictionaryArray::<UInt32Type>::new(
2166            UInt32Array::from(vec![Some(0), None, Some(1), Some(0), Some(2)]),
2167            Arc::new(StringArray::from(vec![Some("host2"), Some("host1"), None])),
2168        );
2169        let batch = DfRecordBatch::try_new(
2170            arrow_schema,
2171            vec![
2172                Arc::new(TimestampMillisecondArray::from(vec![
2173                    1000, 2000, 3000, 4000, 5000,
2174                ])),
2175                Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0])),
2176                Arc::new(instance),
2177            ],
2178        )
2179        .unwrap();
2180        let recordbatch = RecordBatch::from_df_record_batch(schema.clone(), batch);
2181        let columns = label_columns(&recordbatch, greptime_timestamp(), greptime_value()).unwrap();
2182        assert!(matches!(
2183            columns[0].values,
2184            LabelValues::DictionaryUtf8 { .. }
2185        ));
2186        drop(columns);
2187        let recordbatches = RecordBatches::try_new(schema, vec![recordbatch]).unwrap();
2188
2189        let timeseries = recordbatches_to_timeseries(
2190            "metric1",
2191            greptime_timestamp(),
2192            greptime_value(),
2193            recordbatches,
2194        )
2195        .unwrap();
2196
2197        assert_eq!(3, timeseries.len());
2198        assert_eq!(
2199            vec![Label {
2200                name: METRIC_NAME_LABEL.to_string(),
2201                value: "metric1".to_string(),
2202            }],
2203            timeseries[0].labels
2204        );
2205        assert_eq!(
2206            vec![
2207                Sample {
2208                    value: 2.0,
2209                    timestamp: 2000,
2210                },
2211                Sample {
2212                    value: 5.0,
2213                    timestamp: 5000,
2214                },
2215            ],
2216            timeseries[0].samples
2217        );
2218        assert_eq!("host1", timeseries[1].labels[1].value);
2219        assert_eq!(
2220            vec![Sample {
2221                value: 3.0,
2222                timestamp: 3000,
2223            }],
2224            timeseries[1].samples
2225        );
2226        assert_eq!("host2", timeseries[2].labels[1].value);
2227        assert_eq!(
2228            vec![
2229                Sample {
2230                    value: 1.0,
2231                    timestamp: 1000,
2232                },
2233                Sample {
2234                    value: 4.0,
2235                    timestamp: 4000,
2236                },
2237            ],
2238            timeseries[2].samples
2239        );
2240    }
2241
2242    #[test]
2243    fn test_recordbatches_to_timeseries_groups_non_contiguous_series() {
2244        let schema = Arc::new(Schema::new(vec![
2245            ColumnSchema::new(
2246                greptime_timestamp(),
2247                ConcreteDataType::timestamp_millisecond_datatype(),
2248                true,
2249            ),
2250            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
2251            ColumnSchema::new("instance", ConcreteDataType::string_datatype(), true),
2252        ]));
2253        let recordbatch = RecordBatch::new(
2254            schema.clone(),
2255            vec![
2256                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as _,
2257                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as _,
2258                Arc::new(StringVector::from(vec!["host2", "host1", "host2"])) as _,
2259            ],
2260        )
2261        .unwrap();
2262
2263        let recordbatches = RecordBatches::try_new(schema, vec![recordbatch]).unwrap();
2264        let timeseries = recordbatches_to_timeseries(
2265            "metric1",
2266            greptime_timestamp(),
2267            greptime_value(),
2268            recordbatches,
2269        )
2270        .unwrap();
2271
2272        // The result stays sorted by labels as it was with the previous BTreeMap.
2273        assert_eq!("host1", timeseries[0].labels[1].value);
2274        assert_eq!("host2", timeseries[1].labels[1].value);
2275        assert_eq!(
2276            vec![
2277                Sample {
2278                    value: 1.0,
2279                    timestamp: 1000,
2280                },
2281                Sample {
2282                    value: 3.0,
2283                    timestamp: 3000,
2284                },
2285            ],
2286            timeseries[1].samples
2287        );
2288    }
2289
2290    #[test]
2291    fn test_recordbatches_to_timeseries_arrow_label_types_and_nulls() {
2292        let schema = Arc::new(Schema::new(vec![
2293            ColumnSchema::new(
2294                greptime_timestamp(),
2295                ConcreteDataType::timestamp_millisecond_datatype(),
2296                true,
2297            ),
2298            ColumnSchema::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
2299            ColumnSchema::new("instance", ConcreteDataType::large_string_datatype(), true),
2300            ColumnSchema::new("zone", ConcreteDataType::utf8_view_datatype(), true),
2301            ColumnSchema::new("shard", ConcreteDataType::int32_datatype(), true),
2302        ]));
2303        let recordbatch = RecordBatch::new(
2304            schema.clone(),
2305            vec![
2306                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as _,
2307                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as _,
2308                Arc::new(StringVector::from(LargeStringArray::from(vec![
2309                    "host2", "host1", "host2",
2310                ]))) as _,
2311                Arc::new(StringVector::from(StringViewArray::from(vec![
2312                    Some("west"),
2313                    None,
2314                    Some("west"),
2315                ]))) as _,
2316                Arc::new(Int32Vector::from_vec(vec![2, 1, 2])) as _,
2317            ],
2318        )
2319        .unwrap();
2320
2321        let recordbatches = RecordBatches::try_new(schema, vec![recordbatch]).unwrap();
2322        let timeseries = recordbatches_to_timeseries(
2323            "metric1",
2324            greptime_timestamp(),
2325            greptime_value(),
2326            recordbatches,
2327        )
2328        .unwrap();
2329
2330        assert_eq!(2, timeseries.len());
2331        assert_eq!(
2332            vec![
2333                new_label(METRIC_NAME_LABEL.to_string(), "metric1".to_string()),
2334                new_label("instance".to_string(), "host1".to_string()),
2335                new_label("shard".to_string(), "1".to_string()),
2336            ],
2337            timeseries[0].labels
2338        );
2339        assert_eq!(
2340            vec![
2341                new_label(METRIC_NAME_LABEL.to_string(), "metric1".to_string()),
2342                new_label("instance".to_string(), "host2".to_string()),
2343                new_label("zone".to_string(), "west".to_string()),
2344                new_label("shard".to_string(), "2".to_string()),
2345            ],
2346            timeseries[1].labels
2347        );
2348        assert_eq!(
2349            vec![
2350                Sample {
2351                    value: 1.0,
2352                    timestamp: 1000,
2353                },
2354                Sample {
2355                    value: 3.0,
2356                    timestamp: 3000,
2357                },
2358            ],
2359            timeseries[1].samples
2360        );
2361    }
2362
2363    #[tokio::test]
2364    async fn test_snappy_varint_bomb_is_rejected_before_allocation() {
2365        // A five-byte raw Snappy header declaring a ~4 GiB decoded length.
2366        // Regression test for the compression-bomb finding: the declared size
2367        // must be rejected by the cap check before any buffer is allocated.
2368        let bomb = [0xffu8, 0xff, 0xff, 0xff, 0x0f];
2369        let limiter = ServerMemoryLimiter::default();
2370
2371        let err = snappy_decompress_limited(&bomb, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2372            .await
2373            .unwrap_err();
2374        assert!(matches!(
2375            err,
2376            crate::error::Error::DecompressedBodyTooLarge { .. }
2377        ));
2378        assert_eq!(0, limiter.used_bytes());
2379    }
2380
2381    #[tokio::test]
2382    async fn test_snappy_decompress_limited_roundtrip() {
2383        let raw = vec![b'a'; 1024 * 1024];
2384        let mut encoder = snap::raw::Encoder::new();
2385        let compressed = encoder.compress_vec(&raw).unwrap();
2386        let limiter = ServerMemoryLimiter::default();
2387
2388        let decoded =
2389            snappy_decompress_limited(&compressed, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2390                .await
2391                .unwrap();
2392        assert_eq!(&decoded[..], &raw[..]);
2393    }
2394
2395    #[tokio::test]
2396    async fn test_snappy_charges_and_releases_quota() {
2397        let raw = vec![b'a'; 64 * 1024];
2398        let mut encoder = snap::raw::Encoder::new();
2399        let compressed = encoder.compress_vec(&raw).unwrap();
2400        let limiter = ServerMemoryLimiter::new(128 * 1024, OnExhaustedPolicy::Fail);
2401
2402        let decoded =
2403            snappy_decompress_limited(&compressed, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2404                .await
2405                .unwrap();
2406        // Rounding to the 1 KiB permit granularity.
2407        assert!(limiter.used_bytes() >= 64 * 1024);
2408        assert!(limiter.used_bytes() <= 65 * 1024);
2409        drop(decoded);
2410        assert_eq!(0, limiter.used_bytes());
2411    }
2412
2413    #[tokio::test]
2414    async fn test_snappy_rejects_when_quota_exhausted() {
2415        let raw = vec![b'a'; 64 * 1024];
2416        let mut encoder = snap::raw::Encoder::new();
2417        let compressed = encoder.compress_vec(&raw).unwrap();
2418        // Quota smaller than the decoded size.
2419        let limiter = ServerMemoryLimiter::new(1024, OnExhaustedPolicy::Fail);
2420
2421        let err =
2422            snappy_decompress_limited(&compressed, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2423                .await
2424                .unwrap_err();
2425        assert!(matches!(
2426            err,
2427            crate::error::Error::MemoryLimitExceeded { .. }
2428        ));
2429        assert_eq!(0, limiter.used_bytes(), "failed charge must be released");
2430    }
2431
2432    #[tokio::test]
2433    async fn test_zstd_at_and_over_the_cap() {
2434        let limiter = ServerMemoryLimiter::default();
2435        let small_cap = 8 * 1024;
2436
2437        // Exactly at the cap: accepted.
2438        let raw = vec![0u8; small_cap];
2439        let compressed = zstd::stream::encode_all(&raw[..], 3).unwrap();
2440        let decoded = zstd_decompress_limited(&compressed, small_cap, &limiter, 0)
2441            .await
2442            .unwrap();
2443        assert_eq!(decoded.len(), small_cap);
2444
2445        // One byte past the cap: rejected.
2446        let raw = vec![0u8; small_cap + 1];
2447        let compressed = zstd::stream::encode_all(&raw[..], 3).unwrap();
2448        let err = zstd_decompress_limited(&compressed, small_cap, &limiter, 0)
2449            .await
2450            .unwrap_err();
2451        assert!(matches!(
2452            err,
2453            crate::error::Error::DecompressedBodyTooLarge { .. }
2454        ));
2455    }
2456
2457    #[tokio::test(start_paused = true)]
2458    async fn test_zstd_charges_incrementally() {
2459        // 64 KiB wire that expands to 2 MiB must be charged chunk by chunk
2460        // against a quota that only fits the expanded size.
2461        let raw = vec![0u8; 2 * 1024 * 1024];
2462        let compressed = zstd::stream::encode_all(&raw[..], 19).unwrap();
2463        assert!(compressed.len() < 16 * 1024);
2464        let limiter = ServerMemoryLimiter::new(4 * 1024 * 1024, OnExhaustedPolicy::Fail);
2465
2466        let decoded =
2467            zstd_decompress_limited(&compressed, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2468                .await
2469                .unwrap();
2470        assert_eq!(decoded.len(), raw.len());
2471        assert!(limiter.used_bytes() >= raw.len() as u64);
2472        drop(decoded);
2473        assert_eq!(0, limiter.used_bytes());
2474        // The next chunk cannot fit alongside this request's earlier chunks.
2475        let limiter = ServerMemoryLimiter::new(
2476            (2 * ZSTD_DECOMPRESS_CHUNK) as u64,
2477            OnExhaustedPolicy::default(),
2478        );
2479        let started = tokio::time::Instant::now();
2480        let error =
2481            zstd_decompress_limited(&compressed, MAX_DECOMPRESSED_REQUEST_SIZE, &limiter, 0)
2482                .await
2483                .unwrap_err();
2484        assert!(matches!(error, error::Error::MemoryLimitExceeded { .. }));
2485        assert_eq!(started.elapsed(), std::time::Duration::ZERO);
2486        assert_eq!(limiter.used_bytes(), 0);
2487    }
2488
2489    #[test]
2490    fn test_snappy_response_decompress_is_capped() {
2491        // The response-side (uncharged) helper must enforce the cap too.
2492        let bomb = [0xffu8, 0xff, 0xff, 0xff, 0x0f];
2493        let err = snappy_decompress(&bomb).unwrap_err();
2494        assert!(matches!(
2495            err,
2496            crate::error::Error::DecompressedBodyTooLarge { .. }
2497        ));
2498    }
2499}