diff --git a/src/datatypes/src/series/raw.rs b/src/datatypes/src/series/raw.rs index 2605eb7d0af..8bdde54cd76 100644 --- a/src/datatypes/src/series/raw.rs +++ b/src/datatypes/src/series/raw.rs @@ -22,7 +22,8 @@ use crate::error::{InvalidSeriesSnafu, Result}; use crate::series::samples::{SeriesFields, SeriesSchema}; use crate::series::{SeriesLabels, invalid_series}; -/// Strictly increasing source timestamps in milliseconds for a raw series chunk. +/// Strictly increasing source timestamps for a raw series chunk, in the unit of the source's time +/// index. /// /// Its private buffer ensures timestamps are validated once at construction. Direct /// construction is intentionally unavailable: @@ -85,6 +86,12 @@ impl RawTimestamps { } } +impl AsRef<[i64]> for RawTimestamps { + fn as_ref(&self) -> &[i64] { + &self.values + } +} + /// One raw source batch, with fields aligned to its timestamps. /// /// `metric: None` means labels are not yet decoded because identity is bound by the source; it diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index 23dc073f3d7..865ceb5ebcc 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -43,7 +43,6 @@ use datatypes::prelude::ConcreteDataType; use datatypes::schema::SchemaRef; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; -use datatypes::types::TimestampType; use futures::{StreamExt, TryStreamExt}; use smallvec::SmallVec; use snafu::{OptionExt, ResultExt, ensure}; @@ -358,19 +357,16 @@ impl SeriesScan { name: Arc::from(output.name.as_str()), }); } - let time_is_millis = matches!(metadata.time_index_type(), TimestampType::Millisecond(_)); if fields.is_empty() || (input.append_mode && !narthex) || input.series_row_selector.is_some() - || !time_is_millis { debug!( - "Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}, time_is_millis={}", + "Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}", metadata.region_id, fields.len(), input.append_mode, input.series_row_selector.is_some(), - time_is_millis, ); return Ok(None); } diff --git a/src/mito2/src/read/series_scan/raw.rs b/src/mito2/src/read/series_scan/raw.rs index d146bee2c7e..fcc7b21f658 100644 --- a/src/mito2/src/read/series_scan/raw.rs +++ b/src/mito2/src/read/series_scan/raw.rs @@ -29,9 +29,7 @@ use common_query::native_histogram::{ use common_query::series_frame::label_decode_spec; use common_recordbatch::filter; use datafusion::physical_plan::PhysicalExpr; -use datatypes::arrow::array::{ - Array, BinaryArray, Float64Array, StructArray, TimestampMillisecondArray, -}; +use datatypes::arrow::array::{Array, BinaryArray, Float64Array, StructArray}; use datatypes::arrow::buffer::Buffer; use datatypes::arrow::compute::{cast, concat_batches}; use datatypes::arrow::datatypes::ArrowNativeType; @@ -42,6 +40,7 @@ use datatypes::series::SeriesOrdering; use datatypes::series::frame::LabelDecodeSpec; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{Samples, SeriesFields, SeriesSchema}; +use datatypes::timestamp::timestamp_array_to_primitive; use futures::stream::BoxStream; use futures::{FutureExt, Stream, StreamExt, TryStreamExt}; use snafu::Location; @@ -78,11 +77,10 @@ fn chunk( schema: &SeriesSchema, fields: &[(usize, ConcreteDataType)], ) -> Result { - let timestamp = batch - .column(time_index_column_index(batch.num_columns())) - .as_any() - .downcast_ref::() - .ok_or_else(|| invalid("non-millisecond timestamp array"))?; + // The ticks are handed over in the time index's own unit; the consumer is bound to that unit. + let (timestamp, _) = + timestamp_array_to_primitive(batch.column(time_index_column_index(batch.num_columns()))) + .ok_or_else(|| invalid("non-timestamp time index array"))?; if (start..end).any(|row| !timestamp.is_valid(row)) { return Err(invalid("null timestamp")); } diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index fcf77774269..fe964353801 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -116,6 +116,7 @@ use crate::native::plan::{ NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series, }; use crate::native::state::{StateChunk, state_row_from_frame_row}; +use crate::raw_time::RawTimeUnit; use crate::source::materialize_raw_labels; use crate::vector_match::{BinaryMatching, BinaryOp, DuplicateEvidence, MatchingLabels}; @@ -373,9 +374,12 @@ fn canonical_evaluated_local_prefix(node: &NativeNode) -> bool { } } -/// Experimental FusedSeries envelope version. The format is not persisted; any incompatible -/// layout change may reset this rather than reserving numbers for unreleased revisions. -const FUSED_SERIES_ENVELOPE_VERSION: u32 = 1; +/// FusedSeries envelope version. The format is not persisted, but a frontend and a datanode on +/// different builds exchange it during a rolling upgrade. +/// +/// Version 2 appends the time unit of every input leaf after the version 1 payload; a version 1 +/// payload reads every leaf in milliseconds. +const FUSED_SERIES_ENVELOPE_VERSION: u32 = 2; #[derive(serde::Serialize, serde::Deserialize)] struct FusedSeriesPayload { @@ -402,7 +406,8 @@ impl FusedSeries { /// another machine is a separate decision, made by the planner and the transport, not here. /// /// The envelope is [`FUSED_SERIES_ENVELOPE_VERSION`], the payload's length in bytes, then the - /// postcard payload itself. + /// postcard payload itself, followed by the input leaves' time units in + /// [`NativeNode::inputs`] order. pub fn serialize(&self) -> DataFusionResult> { let payload = FusedSeriesPayload { tree: self.tree.clone(), @@ -415,7 +420,14 @@ impl FusedSeries { output_schema: self.output_schema.as_arrow().clone(), canonical_producer: self.canonical_producer, }; - let encoded = postcard::to_stdvec(&payload).map_err(|e| { + let time_units = self + .tree + .root() + .inputs() + .iter() + .map(|input| input.time_unit) + .collect::>(); + let encoded = postcard::to_stdvec(&(payload, time_units)).map_err(|e| { DataFusionError::Plan(format!("cannot serialize FusedSeries payload: {e}")) })?; let len = u32::try_from(encoded.len()) @@ -436,7 +448,7 @@ impl FusedSeries { )); } let version = u32::from_le_bytes(bytes[..4].try_into().unwrap()); - if version != FUSED_SERIES_ENVELOPE_VERSION { + if version != 1 && version != FUSED_SERIES_ENVELOPE_VERSION { return Err(DataFusionError::Plan(format!( "unsupported FusedSeries envelope version {version}" ))); @@ -452,10 +464,18 @@ impl FusedSeries { "trailing bytes in FusedSeries payload".into() })); } - let (payload, remainder) = postcard::take_from_bytes::(&bytes[8..]) - .map_err(|e| { - DataFusionError::Plan(format!("cannot deserialize FusedSeries payload: {e}")) - })?; + let decode_error = + |e| DataFusionError::Plan(format!("cannot deserialize FusedSeries payload: {e}")); + let ((payload, time_units), remainder) = if version == 1 { + let (payload, remainder) = postcard::take_from_bytes::(&bytes[8..]) + .map_err(decode_error)?; + ((payload, None), remainder) + } else { + let ((payload, units), remainder) = + postcard::take_from_bytes::<(FusedSeriesPayload, Vec)>(&bytes[8..]) + .map_err(decode_error)?; + ((payload, Some(units)), remainder) + }; if !remainder.is_empty() { return Err(DataFusionError::Plan( "trailing bytes in FusedSeries payload".into(), @@ -472,6 +492,19 @@ impl FusedSeries { output_schema, canonical_producer: _, } = payload; + let tree = match time_units { + None => tree, + Some(units) => { + let leaves = tree.root().inputs().len(); + if units.len() != leaves { + return Err(DataFusionError::Plan(format!( + "FusedSeries payload carries {} input time units for {leaves} inputs", + units.len() + ))); + } + NativeTree::try_new(tree.root().with_leaf_time_units(&mut units.into_iter()))? + } + }; let grid = Arc::new( EvalGrid::try_deferred(grid) .map_err(|e| DataFusionError::Plan(format!("invalid FusedSeries grid: {e}")))?, diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 2d17e2d58e1..3bcc18213ae 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -124,6 +124,7 @@ use crate::native::plan::{ }; use crate::native::state::{StateChunk, state_bytes}; use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::raw_time::RawTimeUnit; use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; use common_query::series_frame::series_frame_ordering; use common_query::series_frame::unpack_aggregate_state; @@ -212,6 +213,7 @@ fn rate_tree_of(schema: Arc) -> NativeTree { output: raw.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -380,6 +382,7 @@ fn binary_tree_over_sources( source_index: left_source, output: NativeType::Samples(Arc::clone(&raw_left)), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::Samples(raw_left), }), @@ -400,6 +403,7 @@ fn binary_tree_over_sources( source_index: right_source, output: NativeType::Samples(Arc::clone(&raw_right)), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::Samples(raw_right), }), @@ -445,6 +449,7 @@ fn mixed_raw_evaluated_tree() -> NativeTree { output: raw_type.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw_type, }; @@ -470,6 +475,7 @@ fn mixed_raw_evaluated_tree() -> NativeTree { output: evaluated.clone(), source_index: 1, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: evaluated.clone(), }; @@ -514,6 +520,7 @@ fn instant_of(source_index: usize, grid: &Arc) -> NativeNode { source_index, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -1496,6 +1503,7 @@ async fn constant_topk_over_parameterized_topk_keeps_suffix_rows() { source_index: 0, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -1971,6 +1979,7 @@ fn state_tree(stage: AggregateStage, input: NativeType) -> NativeTree { output: child_type.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: child_type, }; @@ -2395,6 +2404,7 @@ fn canonical_producer_node() -> FusedSeries { output: raw.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }; @@ -2651,16 +2661,57 @@ fn fused_series_envelope_refuses_an_unsupported_payload_version() { assert!(FusedSeries::deserialize(&bytes).is_ok()); let mut unsupported = bytes.clone(); - unsupported[..4].copy_from_slice(&2u32.to_le_bytes()); + unsupported[..4].copy_from_slice(&3u32.to_le_bytes()); let message = FusedSeries::deserialize(&unsupported) .unwrap_err() .to_string(); assert!( - message.contains("version") && message.contains('2'), + message.contains("version") && message.contains('3'), "the version must be what is reported, not a field read at the wrong offset: {message}" ); } +/// `fused(rate_tree())` as encoded before input leaves carried a time unit (envelope version 1), +/// captured from a build of that revision. +const RATE_TREE_V1_ENVELOPE: &[&str] = &[ + "01000000a400000006000000010576616c7565000100010576616c75650000c0cf2400000000c0cf", + "24c0a9070500010576616c756501c0cf24c0a90705c0cf24c0a907050113687474705f7265717565", + "7374735f746f74616c0474696d650204686f7374085f5f6e616d655f5f000b7261746528785b356d", + "5d29040576616c75650c0100000004686f73741801000000085f5f6e616d655f5f18010000000474", + "696d650d0100000000000000", +]; + +/// A frontend and a datanode on different builds exchange this encoding during a rolling upgrade: +/// a version 1 payload decodes with millisecond inputs, and the current encoding keeps a finer unit. +#[test] +fn fused_series_decodes_a_version_1_payload_and_keeps_input_time_units() { + let hex = RATE_TREE_V1_ENVELOPE.concat(); + let v1 = (0..hex.len()) + .step_by(2) + .map(|at| u8::from_str_radix(&hex[at..at + 2], 16).unwrap()) + .collect::>(); + assert_eq!(1u32.to_le_bytes(), v1[..4]); + let expected = fused(rate_tree()); + let decoded = FusedSeries::deserialize(&v1).unwrap(); + assert_eq!(decoded.tree(), expected.tree()); + assert_eq!(decoded.binding(), expected.binding()); + assert_eq!(decoded.schema(), expected.schema()); + + let nanos = NativeTree::try_new( + rate_tree() + .root() + .with_input_time_units(&[RawTimeUnit::Nanosecond]), + ) + .unwrap(); + let node = fused(nanos); + let decoded = FusedSeries::deserialize(&node.serialize().unwrap()).unwrap(); + assert_eq!( + decoded.tree().root().inputs()[0].time_unit, + RawTimeUnit::Nanosecond + ); + assert_eq!(decoded.tree(), node.tree()); +} + /// The `SeriesFrame` node of [`rate_tree`] declaring `tags` as its labels. /// /// A `SeriesFrame` node is checked against the codec's own frame layout, so it is built with @@ -2684,11 +2735,12 @@ fn mutate_envelope_payload( bytes: &[u8], mutate: impl FnOnce(&mut super::FusedSeriesPayload), ) -> Vec { - let (mut payload, remainder) = - postcard::take_from_bytes::(&bytes[8..]).unwrap(); + let ((mut payload, time_units), remainder) = + postcard::take_from_bytes::<(super::FusedSeriesPayload, Vec)>(&bytes[8..]) + .unwrap(); assert!(remainder.is_empty()); mutate(&mut payload); - let changed = postcard::to_stdvec(&payload).unwrap(); + let changed = postcard::to_stdvec(&(payload, time_units)).unwrap(); let mut result = Vec::with_capacity(8 + changed.len()); result.extend(super::FUSED_SERIES_ENVELOPE_VERSION.to_le_bytes()); result.extend((changed.len() as u32).to_le_bytes()); @@ -4065,6 +4117,7 @@ fn instant_selecting( source_index, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -5461,6 +5514,7 @@ async fn hand_bound_fused_merge_canonicalizes_shared_labels() { output: raw.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }; @@ -7626,6 +7680,7 @@ fn final_root_refuses_samples_binding() { })), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::Samples(Arc::new(SeriesSchema { fields: raw_schema().fields.clone(), @@ -7663,6 +7718,7 @@ fn repeated_source_with_state_and_samples_is_refused() { output: NativeType::AggregateState(state), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }; let samples_input = BoundInput { output: NativeType::Samples(Arc::new(SeriesSchema { @@ -7671,6 +7727,7 @@ fn repeated_source_with_state_and_samples_is_refused() { })), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }; let error = super::collect_source_schemas_from_inputs(vec![&state_input, &samples_input]).unwrap_err(); @@ -7725,6 +7782,7 @@ fn series_frame_output_schema_matches_evaluated_packer() { output: output.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output, }) @@ -9300,6 +9358,7 @@ fn a_fold_across_groups_gathers_the_state_it_reads() { output: output.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output, }; @@ -9379,6 +9438,7 @@ fn a_ranking_above_the_final_gathers_the_state_it_ranks() { output: NativeType::AggregateState(Arc::clone(&state)), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::AggregateState(Arc::clone(&state)), }), @@ -9882,6 +9942,7 @@ fn aliased_count_tree() -> NativeTree { output: raw.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -9929,6 +9990,7 @@ fn summed_window_tree() -> NativeTree { source_index: 0, output: evaluated.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: evaluated.clone(), }; diff --git a/src/promql/src/extension_plan/fused_series/tests/frame_output.rs b/src/promql/src/extension_plan/fused_series/tests/frame_output.rs index ee7f59402e2..3955c07f610 100644 --- a/src/promql/src/extension_plan/fused_series/tests/frame_output.rs +++ b/src/promql/src/extension_plan/fused_series/tests/frame_output.rs @@ -29,6 +29,7 @@ fn instant_tree(schema: Arc, grid: Arc) -> NativeTree { source_index: 0, output: NativeType::Samples(Arc::clone(&schema)), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::Samples(Arc::clone(&schema)), }), diff --git a/src/promql/src/extension_plan/planner.rs b/src/promql/src/extension_plan/planner.rs index a26ee3d4003..192d6a0bdc8 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -536,6 +536,7 @@ mod tests { output: samples.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: samples, }) diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs index 4000bc20290..701ed44a6b9 100644 --- a/src/promql/src/extension_plan/series_repartition/tests.rs +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -2837,6 +2837,7 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { source_index: 0, output: raw.clone(), ordering: datatypes::series::SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), diff --git a/src/promql/src/instant_eval.rs b/src/promql/src/instant_eval.rs index 2eb96fe8df1..8d1b26035de 100644 --- a/src/promql/src/instant_eval.rs +++ b/src/promql/src/instant_eval.rs @@ -18,7 +18,6 @@ use std::sync::Arc; use common_query::prometheus::is_prometheus_stale_nan; use datafusion::error::{DataFusionError, Result}; use datatypes::series::SeriesLabels; -use datatypes::series::raw::RawTimestamps; use datatypes::series::samples::{SampleRef, Series, SeriesFields, SeriesSchema}; use crate::grid_series::{GridSeriesBuilder, label_set, render_label_set}; @@ -43,7 +42,7 @@ fn row_read() { /// /// `None` means the anchor selects nothing. pub fn select_instant_at( - time: &RawTimestamps, + time: &(impl AsRef<[i64]> + ?Sized), fields: &SeriesFields, at_ms: i64, lookback_ms: i64, @@ -106,14 +105,16 @@ pub(crate) fn instant_candidate_span( /// Selects source rows for an aligned PromQL instant-evaluation range. /// -/// Returns source row indices and evaluation timestamps from a complete source axis of strictly -/// increasing milliseconds. Any provided field's stale marker suppresses selection; missing samples -/// are not stale and remain selectable. +/// Returns source row indices and evaluation timestamps from a complete source axis of +/// non-decreasing milliseconds. Any provided field's stale marker suppresses selection; missing +/// samples are not stale and remain selectable. Among rows sharing a millisecond, the last one is +/// the candidate; a finer time index truncated to window times produces such rows +/// ([`crate::raw_time`]). /// /// Allocates 16 bytes per point of the `instant_candidate_span` and reserves none of it; callers /// grow their memory reservation before calling. pub fn select_instants( - time: &RawTimestamps, + time: &(impl AsRef<[i64]> + ?Sized), fields: &SeriesFields, range: RangeInclusive, step_ms: i64, @@ -137,7 +138,7 @@ pub fn select_instants( "InstantManipulate lookback must be non-negative".into(), )); } - let timestamps = time.as_buffer(); + let timestamps = time.as_ref(); if fields .as_slice() .iter() @@ -212,7 +213,7 @@ pub fn select_instants( pub fn timestamp_of_selection( schema: &Arc, metric: &SeriesLabels, - time: &RawTimestamps, + time: &(impl AsRef<[i64]> + ?Sized), fields: &SeriesFields, indices: &[u64], evaluation_timestamps: &[i64], @@ -220,7 +221,7 @@ pub fn timestamp_of_selection( project_selection( schema, drop_metric_name(metric)?, - time, + time.as_ref(), fields, indices, evaluation_timestamps, @@ -236,7 +237,7 @@ pub fn timestamp_of_selection( pub fn info_sample_times( schema: &Arc, metric: &SeriesLabels, - time: &RawTimestamps, + time: &(impl AsRef<[i64]> + ?Sized), fields: &SeriesFields, indices: &[u64], evaluation_timestamps: &[i64], @@ -244,7 +245,7 @@ pub fn info_sample_times( project_selection( schema, metric.clone(), - time, + time.as_ref(), fields, indices, evaluation_timestamps, @@ -317,7 +318,7 @@ fn collapsed<'a>(schema: &SeriesSchema, row: &'a mut Vec>) -> &'a [O fn project_selection( schema: &Arc, metric: SeriesLabels, - time: &RawTimestamps, + time: &[i64], fields: &SeriesFields, indices: &[u64], evaluation_timestamps: &[i64], @@ -364,7 +365,7 @@ fn project_selection( )); } _ => { - let time = time.timestamp(index).expect("checked against the axis"); + let time = time[index]; row.clear(); for cursor in &mut cursors { let sample = cursor diff --git a/src/promql/src/lib.rs b/src/promql/src/lib.rs index bf7f7404896..576fe95acfb 100644 --- a/src/promql/src/lib.rs +++ b/src/promql/src/lib.rs @@ -32,6 +32,7 @@ mod metrics; pub mod native; pub mod range_array; pub mod range_eval; +pub mod raw_time; pub mod select; pub mod source; pub mod vector_match; diff --git a/src/promql/src/native/canonicalize/tests.rs b/src/promql/src/native/canonicalize/tests.rs index 7027ba65f6e..1af5f3558c0 100644 --- a/src/promql/src/native/canonicalize/tests.rs +++ b/src/promql/src/native/canonicalize/tests.rs @@ -64,6 +64,7 @@ fn raw_input(source_index: usize) -> NativeNode { output: output.clone(), source_index, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 66a0caf766d..29fce0005c4 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -64,6 +64,7 @@ fn raw_input() -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -193,6 +194,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { output: contiguous.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: contiguous, }; @@ -211,6 +213,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { output: interleaved.clone(), source_index: 0, ordering: SeriesOrdering::Interleaved, + time_unit: Default::default(), }), output: interleaved, }; diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index b47a152db22..6d18a7df955 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -65,6 +65,7 @@ use crate::native::plan::{ }; use crate::native::state::{StateChunk, state_bytes}; use crate::range_eval::RangeEvaluator; +use crate::raw_time::RawTimeUnit; use crate::select::{self, SortOrder}; use crate::vector_match::{ BinaryKind, BinaryMatching, Cardinality, DuplicateEvidence, FillValues, MatchingLabels, @@ -564,10 +565,17 @@ struct InstantRuntime { chunks: Vec, /// The bytes `chunks` hold. held: usize, + /// The unit of the input's timestamps. + time_unit: RawTimeUnit, } impl InstantRuntime { - fn try_new(input: &SeriesSchema, output: &SeriesSchema, op: &BoundInstant) -> Result { + fn try_new( + input: &SeriesSchema, + output: &SeriesSchema, + op: &BoundInstant, + time_unit: RawTimeUnit, + ) -> Result { let schema = Arc::new(SeriesSchema { fields: Arc::clone(&input.fields), eval_grid: Some(Arc::clone(&op.output_grid)), @@ -583,6 +591,7 @@ impl InstantRuntime { answer, chunks: Vec::new(), held: 0, + time_unit, }) } @@ -612,7 +621,14 @@ impl InstantRuntime { .flat_map(|chunk| chunk.fields.as_slice()) .map(|field| field.segments().len()) .fold(0usize, usize::saturating_add); - let axis = rows.saturating_mul(std::mem::size_of::()); + // An input finer or coarser than milliseconds is also read as its window times and its + // payloads, one millisecond axis each. + let axes = if self.time_unit == RawTimeUnit::Millisecond { + 1 + } else { + 3 + }; + let axis = rows.saturating_mul(axes * std::mem::size_of::()); let layout = chunks .saturating_mul(fields) .saturating_mul(descriptor) @@ -653,12 +669,15 @@ impl InstantRuntime { return 0; } let series = || self.chunks.iter().chain(std::iter::once(closing)); + let window_ms = |tick| self.time_unit.window_ms(tick, 0).ok(); let endpoints = series() .find_map(|chunk| chunk.time.as_buffer().first().copied()) + .and_then(window_ms) .zip( series() .rev() - .find_map(|chunk| chunk.time.as_buffer().last().copied()), + .find_map(|chunk| chunk.time.as_buffer().last().copied()) + .and_then(window_ms), ); let span = instant_candidate_span( endpoints, @@ -718,8 +737,30 @@ impl InstantRuntime { )); }; let metric = first.metric.clone().ok_or_else(no_labels)?; - let time = buffered_time(&self.chunks)?; + let ticks = buffered_time(&self.chunks)?; let fields = buffered_fields(&self.chunks, self.schema.fields.len())?; + // The selection compares window times, and `timestamp()` reports payloads; on a millisecond + // input both are the stored ticks. + let (mut payloads, mut windows) = (Vec::new(), Vec::new()); + let (time, window_time): (&[i64], &[i64]) = if self.time_unit == RawTimeUnit::Millisecond { + (ticks.as_ref(), ticks.as_ref()) + } else { + self.time_unit + .convert(ticks.as_ref(), 0, &mut payloads, &mut windows)?; + if self.time_unit.is_whole_millis() { + (payloads.as_slice(), payloads.as_slice()) + } else { + (payloads.as_slice(), windows.as_slice()) + } + }; + // A zero lookback selects only a sample exactly at the instant, and the window time of a + // sample less than a millisecond before it is the instant too. The selection's candidate is + // the latest sample at or before the instant, so it is the exact one if there is one. + let exact_only = |lookback_ms: i64| lookback_ms == 0 && !self.time_unit.is_whole_millis(); + let at_instant = |index: u64, instant_ms: i128| { + self.time_unit + .is_at(ticks.as_ref()[index as usize], instant_ms) + }; // The existing planner's `InstantManipulate` reads a stale marker from the first field // only, so a marker in another field does not suppress the row. let staleness = fields @@ -751,18 +792,25 @@ impl InstantRuntime { let metric = drop_metric_name(&metric)?; return no_row_chunk(&self.answer, metric); }; + let selection_offset = if self.selection.value == InstantValue::Timestamp { + 0 + } else { + self.selection.offset_ms + }; let Some(index) = select_instant_at( - &time, + window_time, &staleness, selection_at, selection_lookback, - if self.selection.value == InstantValue::Timestamp { - 0 - } else { - self.selection.offset_ms - }, + selection_offset, )? - else { + .filter(|&index| { + !exact_only(selection_lookback) + || at_instant( + index, + i128::from(selection_at) - i128::from(selection_offset), + ) + }) else { return no_row_chunk(&self.answer, self.output_metric(&metric)?); }; let grid_len = usize::try_from(spec.len).unwrap_or(usize::MAX); @@ -772,7 +820,7 @@ impl InstantRuntime { .timestamps() .map_err(crate::grid_series::external)? .to_vec(); - return self.project(&metric, &time, &fields, &indices, ×tamps); + return self.project(&metric, time, &fields, &indices, ×tamps); } self.output.begin_series(); let mut cursors: Vec> = fields.iter().map(Samples::cursor).collect(); @@ -792,16 +840,24 @@ impl InstantRuntime { None => no_row_chunk(&self.answer, metric), }; } - let (indices, timestamps) = select_instants( - &time, + let (mut indices, mut timestamps) = select_instants( + window_time, &staleness, spec.start_ms..=grid_end_ms(spec), spec.step_ms, self.selection.lookback_ms, self.selection.offset_ms, )?; + if exact_only(self.selection.lookback_ms) { + let offset_ms = i128::from(self.selection.offset_ms); + (indices, timestamps) = indices + .into_iter() + .zip(timestamps) + .filter(|&(index, timestamp)| at_instant(index, i128::from(timestamp) - offset_ms)) + .unzip(); + } if self.selection.value != InstantValue::Sample { - return self.project(&metric, &time, &fields, &indices, ×tamps); + return self.project(&metric, time, &fields, &indices, ×tamps); } self.output.begin_series(); let mut cursors: Vec> = fields.iter().map(Samples::cursor).collect(); @@ -841,7 +897,7 @@ impl InstantRuntime { fn project( &self, metric: &SeriesLabels, - time: &RawTimestamps, + time: &[i64], fields: &SeriesFields, indices: &[u64], timestamps: &[i64], @@ -2161,6 +2217,15 @@ fn window_workspace_bytes( }) } +/// The unit of the timestamps `node` hands over: an input leaf's own; every other node answers on a +/// millisecond grid. +fn input_time_unit(node: &NativeNode) -> RawTimeUnit { + match &node.expr { + NativeExpr::Input(input) => input.time_unit, + _ => RawTimeUnit::Millisecond, + } +} + /// The time of the last sample a chunk carries, on its own timeline. fn last_sample_ms(chunk: &NativeChunk) -> Result> { match chunk { @@ -2630,7 +2695,12 @@ impl RuntimeNode { })?; RuntimeOp::Instant { input: Box::new(child), - instant: InstantRuntime::try_new(&input_schema, &output_schema, op)?, + instant: InstantRuntime::try_new( + &input_schema, + &output_schema, + op, + input_time_unit(input), + )?, state: { NodeState::new( format!("native.instant at {location}"), @@ -2690,12 +2760,15 @@ impl RuntimeNode { ); RuntimeOp::Window { input: Box::new(child), - window: Some(RangeEvaluator::try_new( - &input_schema, - Arc::clone(&op.output_grid), - op.window, - op.function, - )?), + window: Some( + RangeEvaluator::try_new( + &input_schema, + Arc::clone(&op.output_grid), + op.window, + op.function, + )? + .with_raw_time_unit(input_time_unit(input)), + ), merge, state, } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 93cb277b80a..35b660f35a7 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -266,6 +266,7 @@ fn raw_input_with_source_index_and_ordering( output: output.clone(), source_index, ordering, + time_unit: Default::default(), }), output, } @@ -279,6 +280,7 @@ fn raw_input_of(count: usize) -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -309,6 +311,7 @@ fn evaluated_input_with_source_index_and_ordering( output: output.clone(), source_index, ordering, + time_unit: Default::default(), }), output, } @@ -2261,6 +2264,7 @@ fn timestamp_projection_workspace_failure_releases_runtime() { source_index: 0, output: NativeType::Samples(Arc::clone(&schema)), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::Samples(Arc::clone(&schema)), }; @@ -6307,7 +6311,13 @@ fn instant_candidate_span_covers_native_selection_at_boundaries() { value: InstantValue::Sample, output_grid: Arc::clone(&out_grid), }; - let mut runtime = InstantRuntime::try_new(&schema, &schema, &selection).unwrap(); + let mut runtime = InstantRuntime::try_new( + &schema, + &schema, + &selection, + crate::raw_time::RawTimeUnit::Millisecond, + ) + .unwrap(); let values: Vec<_> = case .times .iter() @@ -6389,6 +6399,47 @@ fn instant_candidate_span_covers_native_selection_at_boundaries() { } } +/// A zero lookback selects only a sample at the instant itself. A microsecond sample just before +/// the instant shares its window millisecond, and must not stand in for it, anchored or not. +#[test] +fn zero_lookback_does_not_select_a_sub_millisecond_sample_before_the_instant() { + let schema = raw_schema(); + for (tick, selected) in [(999_001, false), (1_000_000, true)] { + for (value, offset_ms) in [ + (InstantValue::Sample, 0), + (InstantValue::Sample, 1), + (InstantValue::Timestamp, 0), + ] { + for anchored in [false, true] { + let instant = 1_000 + offset_ms; + let selection = BoundInstant { + lookback_ms: 0, + offset_ms, + at_ms: anchored.then_some(instant), + value, + output_grid: grid(instant, 1_000, 1), + }; + let mut runtime = InstantRuntime::try_new( + &schema, + &schema, + &selection, + crate::raw_time::RawTimeUnit::Microsecond, + ) + .unwrap(); + let out = runtime + .push(raw_chunk(&schema, &[tick], &[1.0], true)) + .unwrap() + .expect("the closing chunk gathers the series"); + assert_eq!( + sample_values(&out).iter().flatten().count(), + usize::from(selected), + "tick {tick}us, {value:?}, offset {offset_ms}, anchored {anchored}" + ); + } + } + } +} + /// A selection reserves the points it can decide, not the points the grid plans. /// /// One sample on a 10,081-point grid with a five-minute lookback is decided at five points, so a @@ -6707,6 +6758,7 @@ fn evaluated_input_of(count: usize, grid: Arc) -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -11953,6 +12005,7 @@ fn a_quantile_stage_the_runtime_does_not_compute_is_named() { output: NativeType::AggregateState(state_schema()), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::AggregateState(state_schema()), }; @@ -14294,6 +14347,7 @@ fn partial_final_matches_complete_over_concatenated_input() { output: NativeType::AggregateState(Arc::clone(&state_schema)), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::AggregateState(Arc::clone(&state_schema)), } diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index beb9975b1d2..381459fef9a 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -41,6 +41,7 @@ use crate::map::MathOp; use crate::map_label::LabelRewrite; use crate::map_time::DateFunction; use crate::range_eval::{RangeFunction, RangeWindow, fold_offset}; +use crate::raw_time::RawTimeUnit; use crate::select::SortOrder; use crate::vector_match::{ BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp, @@ -652,6 +653,13 @@ pub struct BoundInput { /// The ordering the input guarantees; an instant selection and a window reject an interleaved /// one. pub ordering: SeriesOrdering, + /// The unit of the timestamps a raw input hands over. Evaluated and state inputs are on a + /// millisecond grid. + /// + /// Not part of the tree's encoding: `FusedSeries` carries the units beside the tree, so a tree + /// encoded before the unit existed still decodes. + #[serde(skip)] + pub time_unit: RawTimeUnit, } /// A constant scalar. Varying scalars ([`NativeExpr::EvalTime`], [`NativeExpr::ScalarOf`], a @@ -1094,6 +1102,51 @@ impl NativeNode { .any(|child| child.any(predicate)) } + /// This node with the time unit of every input leaf set to `units[source_index]`; a leaf whose + /// index `units` does not reach keeps its unit. + pub fn with_input_time_units(&self, units: &[RawTimeUnit]) -> NativeNode { + let expr = match &self.expr { + NativeExpr::Input(input) => NativeExpr::Input(BoundInput { + time_unit: units + .get(input.source_index) + .copied() + .unwrap_or(input.time_unit), + ..input.clone() + }), + expr => expr.with_children( + expr.children() + .into_iter() + .map(|child| child.with_input_time_units(units)) + .collect(), + ), + }; + NativeNode { + expr, + output: self.output.clone(), + } + } + + /// This node with the time units of its input leaves taken from `units` in [`Self::inputs`] + /// order; a leaf `units` does not reach keeps its unit. + pub fn with_leaf_time_units(&self, units: &mut dyn Iterator) -> NativeNode { + let expr = match &self.expr { + NativeExpr::Input(input) => NativeExpr::Input(BoundInput { + time_unit: units.next().unwrap_or(input.time_unit), + ..input.clone() + }), + expr => expr.with_children( + expr.children() + .into_iter() + .map(|child| child.with_leaf_time_units(units)) + .collect(), + ), + }; + NativeNode { + expr, + output: self.output.clone(), + } + } + /// The input leaves below this node in evaluation order, one entry per leaf. pub fn inputs(&self) -> Vec<&BoundInput> { fn collect<'a>(node: &'a NativeNode, inputs: &mut Vec<&'a BoundInput>) { diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 810d3b06957..f6814b5b1c0 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -75,6 +75,7 @@ fn input() -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -87,6 +88,7 @@ fn input_on(grid: Arc) -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output, } @@ -103,6 +105,7 @@ fn input_with_fields(count: usize) -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -116,6 +119,7 @@ fn interleaved_input() -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::Interleaved, + time_unit: Default::default(), }), output, } @@ -1896,6 +1900,7 @@ fn an_input_must_report_the_binding_it_was_bound_to() { })), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: raw(), }; @@ -1911,6 +1916,7 @@ fn an_input_can_bind_aggregate_state() { output: state.output.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: state.output.clone(), }; @@ -1925,6 +1931,7 @@ fn an_input_can_bind_aggregate_state() { output: evaluated_a.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: evaluated(fields(2), grid(0, 60_000, 4)), }; @@ -1951,6 +1958,7 @@ fn an_input_can_bind_aggregate_state() { output: evaluated_a.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output, }; @@ -1973,6 +1981,7 @@ fn an_input_can_bind_aggregate_state() { output: state_a, source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: state_group_mismatch, }; @@ -1998,6 +2007,7 @@ fn an_input_can_bind_aggregate_state() { output: bound, source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output, }; @@ -2322,6 +2332,7 @@ fn an_included_metric_name_survives_an_arithmetic_match() { output: output.clone(), source_index, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } @@ -2907,6 +2918,7 @@ fn native_expr_variant_indices_are_a_wire_contract() { source_index: 0, output: raw(), ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), 0u8, "Input", @@ -3125,6 +3137,7 @@ fn native_tree_supported_declines_the_shapes_the_runtime_refuses() { output: evaluated(Arc::new([]), Arc::clone(&out)), source_index: 0, ordering: SeriesOrdering::Interleaved, + time_unit: Default::default(), }), output: evaluated(Arc::new([]), Arc::clone(&out)), }; diff --git a/src/promql/src/native/segment.rs b/src/promql/src/native/segment.rs index e77f4b881a3..b958dab1f22 100644 --- a/src/promql/src/native/segment.rs +++ b/src/promql/src/native/segment.rs @@ -276,6 +276,7 @@ fn rewrite_inner_segment(node: &NativeNode, sources: &[usize]) -> NativeNode { .expect("the segment collected every scan it reads"), output: input.output.clone(), ordering: input.ordering, + time_unit: input.time_unit, }), expr => expr.with_children( expr.children() @@ -306,6 +307,7 @@ fn rewrite_segment( .expect("the segment collected every scan it reads"), output: input.output.clone(), ordering: input.ordering, + time_unit: input.time_unit, }), expr => { let children = expr @@ -320,6 +322,7 @@ fn rewrite_segment( source_index: index, output: child.output.clone(), ordering: NATIVE_ORDERING, + time_unit: Default::default(), }), output: child.output.clone(), } @@ -504,6 +507,7 @@ pub fn canonical_boundary_stages( source_index: 0, output: evaluated.clone(), ordering: NATIVE_ORDERING, + time_unit: Default::default(), }), output: evaluated, }) @@ -1088,6 +1092,7 @@ mod tests { output: output.clone(), source_index: 0, ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: output.clone(), }; diff --git a/src/promql/src/native/split.rs b/src/promql/src/native/split.rs index 0e3be5e49f1..142eca59d1a 100644 --- a/src/promql/src/native/split.rs +++ b/src/promql/src/native/split.rs @@ -121,6 +121,7 @@ pub(crate) fn split( source_index: 0, output: node.output.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: node.output.clone(), }, @@ -488,6 +489,7 @@ impl Split { source_index: 0, output: NativeType::AggregateState(Arc::clone(&state)), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: NativeType::AggregateState(Arc::clone(&state)), }), diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index b3ac762f39a..71f442103dd 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -36,6 +36,7 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use crate::evaluated::EvaluatedChunk; use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external}; use crate::histogram_eval::float_histogram::FloatHistogram; +use crate::raw_time::RawTimeUnit; mod function; mod histogram; @@ -197,6 +198,10 @@ pub struct RangeEvaluator { pending: PendingBatch, /// Kept between chunks so the bulk ingest does not allocate per push. bulk_scratch: BulkScratch, + /// The unit of raw input timestamps; evaluated input is always on a millisecond grid. + raw_time_unit: RawTimeUnit, + /// The payloads and window times a raw chunk in another unit is converted into. + converted: (Vec, Vec), #[cfg(test)] batch_calls: usize, } @@ -206,13 +211,14 @@ pub struct RangeEvaluator { #[derive(Default)] struct BulkScratch { timestamps: Vec, + windows: Vec, columns: Vec>, } impl BulkScratch { /// The bytes these buffers hold, by capacity. fn bytes(&self) -> usize { - self.timestamps.capacity() * std::mem::size_of::() + (self.timestamps.capacity() + self.windows.capacity()) * std::mem::size_of::() + self.columns.capacity() * std::mem::size_of::>() + self .columns @@ -315,13 +321,14 @@ fn accumulate(pending: &mut PendingBatch, index: usize, eval_ts: i64, fields: &[ // forward; never revisit samples already behind every remaining window. pending.ends[field_index] = pending.ends[field_index].max(field.head); if !pending.positioned[field_index] { - pending.ends[field_index] = field.timestamps[field.head..] + pending.ends[field_index] = field.window_times()[field.head..] .partition_point(|×tamp| timestamp_le(timestamp, eval_ts)) + field.head; pending.positioned[field_index] = true; } else { - while pending.ends[field_index] < field.timestamps.len() - && timestamp_le(field.timestamps[pending.ends[field_index]], eval_ts) + let windows = field.window_times(); + while pending.ends[field_index] < windows.len() + && timestamp_le(windows[pending.ends[field_index]], eval_ts) { pending.ends[field_index] += 1; } @@ -425,7 +432,11 @@ enum Replay { #[derive(Default)] struct FieldSamples { + /// The sample times a kernel reads, shifted by the offset. timestamps: Vec, + /// The times window membership is decided on, aligned with `timestamps`, when they differ + /// from them: for raw input finer than a millisecond ([`crate::raw_time`]). + windows: Option>, values: Vec, /// Samples before `head` are behind every remaining window. head: usize, @@ -472,7 +483,8 @@ impl FieldSamples { /// The bytes this field's buffers hold, by capacity: the samples, the history behind `head` /// included, plus the estimated payload of the histograms still held. fn bytes(&self) -> usize { - self.timestamps.capacity() * std::mem::size_of::() + (self.timestamps.capacity() + self.windows.as_ref().map_or(0, Vec::capacity)) + * std::mem::size_of::() + self.values.capacity() * std::mem::size_of::() + self.histograms.capacity() * std::mem::size_of::<(i64, FloatHistogram)>() + self.resets.capacity() * std::mem::size_of::() @@ -486,13 +498,18 @@ impl FieldSamples { } } + /// The times window membership is decided on. + fn window_times(&self) -> &[i64] { + self.windows.as_deref().unwrap_or(&self.timestamps) + } + /// Appends one valid sample, recording a counter reset when it dropped below the previous /// float. /// /// The previous float may sit before an intervening native histogram. That is unobservable: /// a window holding both floats also holds the histogram, and counter functions report /// nothing for a mixed window. - fn push(&mut self, timestamp: i64, value: f64) { + fn push(&mut self, timestamp: i64, window: Option, value: f64) { if self.index_resets && let Some(&previous_value) = self.values.last() && value < previous_value @@ -503,11 +520,14 @@ impl FieldSamples { }); } self.timestamps.push(timestamp); + if let (Some(windows), Some(window)) = (self.windows.as_mut(), window) { + windows.push(window); + } self.values.push(value); } /// Same as calling [`push`](Self::push) once per sample. - fn push_bulk(&mut self, timestamps: &[i64], values: &[f64]) { + fn push_bulk(&mut self, timestamps: &[i64], windows: Option<&[i64]>, values: &[f64]) { debug_assert_eq!(timestamps.len(), values.len()); if self.index_resets { let start = self.values.len(); @@ -525,6 +545,9 @@ impl FieldSamples { } } self.timestamps.extend_from_slice(timestamps); + if let (Some(retained), Some(windows)) = (self.windows.as_mut(), windows) { + retained.extend_from_slice(windows); + } self.values.extend_from_slice(values); } @@ -536,6 +559,9 @@ impl FieldSamples { } self.base += head as u64; self.timestamps.drain(..head); + if let Some(windows) = self.windows.as_mut() { + windows.drain(..head); + } self.values.drain(..head); // A reset at `base` would add back the last dropped sample, so it goes with it. let dropped = self @@ -679,11 +705,22 @@ impl RangeEvaluator { batch: None, pending: PendingBatch::with_fields(input.fields.len()), bulk_scratch: BulkScratch::default(), + raw_time_unit: RawTimeUnit::Millisecond, + converted: (Vec::new(), Vec::new()), #[cfg(test)] batch_calls: 0, }) } + /// Reads raw chunks whose timestamps are in `unit`. + pub fn with_raw_time_unit(mut self, unit: RawTimeUnit) -> Self { + self.raw_time_unit = unit; + for field in &mut self.fields { + field.windows = (!unit.is_whole_millis()).then(Vec::new); + } + self + } + /// The evaluation grid the output is addressed on. pub fn grid(&self) -> &Arc { &self.grid @@ -721,6 +758,8 @@ impl RangeEvaluator { + self.series.as_ref().map_or(0, SeriesState::identity_bytes) + self.pending.bytes() + self.bulk_scratch.bytes() + + (self.converted.0.capacity() + self.converted.1.capacity()) + * std::mem::size_of::() } /// An upper bound of the rows the next push hands out, for input whose last sample is at @@ -735,6 +774,10 @@ impl RangeEvaluator { let Some(latest) = last_ts.or_else(|| state.and_then(|state| state.last_ts)) else { return 0; }; + // `latest` is on the input's own timeline; a time that does not convert fails the push. + let Ok(latest) = self.raw_time_unit.window_ms(latest, 0) else { + return len; + }; let cursor = state.map_or(0, |state| state.cursor); if !matches!(self.replay, Replay::PerPoint) { return if cursor == 0 { len } else { 0 }; @@ -796,13 +839,28 @@ impl RangeEvaluator { )); } self.check_chunk(chunk)?; - self.ingest(chunk.time.as_buffer(), &chunk.fields, true)?; - let last_ts = chunk.time.as_buffer()[chunk.time.len() - 1]; + let ticks = chunk.time.as_buffer(); + let read_through = if self.raw_time_unit == RawTimeUnit::Millisecond { + self.ingest(ticks, None, self.window.offset_ms, &chunk.fields, true)?; + i128::from(ticks[ticks.len() - 1]) + i128::from(self.window.offset_ms) + } else { + let (mut payloads, mut windows) = std::mem::take(&mut self.converted); + let ingested = self + .raw_time_unit + .convert(ticks, self.window.offset_ms, &mut payloads, &mut windows) + .and_then(|()| { + let windows = (!self.raw_time_unit.is_whole_millis()).then_some(&windows[..]); + self.ingest(&payloads, windows, 0, &chunk.fields, true)?; + self.raw_time_unit + .floor_ms(ticks[ticks.len() - 1], self.window.offset_ms) + }); + self.converted = (payloads, windows); + i128::from(ingested?) + }; if !chunk.is_last { - // Later chunks only hold samples after `last_ts`. - self.evaluate(Some( - i128::from(last_ts) + i128::from(self.window.offset_ms), - ))?; + // Later chunks only hold samples after this one's last, but one in the same + // millisecond shares its window time, so only the millisecond before it is settled. + self.evaluate(Some(read_through))?; return self.emit(); } self.close_series() @@ -882,7 +940,13 @@ impl RangeEvaluator { } } if let Some(last_ts) = last_ts { - self.ingest(×tamps, &series.fields, false)?; + self.ingest( + ×tamps, + None, + self.window.offset_ms, + &series.fields, + false, + )?; if last { return self.close_series(); } @@ -1032,6 +1096,8 @@ impl RangeEvaluator { fn ingest_in_bulk( &mut self, timestamps: &[i64], + windows: Option<&[i64]>, + offset_ms: i64, fields: &SeriesFields, drop_stale: bool, ) -> Result { @@ -1061,7 +1127,13 @@ impl RangeEvaluator { } else { None }; - self.append_float_chunk(timestamps, &columns, stale_rows.as_deref())?; + self.append_float_chunk( + timestamps, + windows, + offset_ms, + &columns, + stale_rows.as_deref(), + )?; #[cfg(test)] { self.bulk_ingests += 1; @@ -1074,22 +1146,39 @@ impl RangeEvaluator { fn append_float_chunk( &mut self, timestamps: &[i64], + windows: Option<&[i64]>, + offset_ms: i64, columns: &[&[f64]], stale: Option<&[bool]>, ) -> Result<()> { - let offset_ms = self.window.offset_ms; + debug_assert!( + windows.is_none() || offset_ms == 0, + "window times are already shifted" + ); if offset_ms == 0 && stale.is_none() { for (field, values) in self.fields.iter_mut().zip(columns) { - field.push_bulk(timestamps, values); + field.push_bulk(timestamps, windows, values); } return Ok(()); } let BulkScratch { timestamps: mut shifted, + windows: mut kept_windows, columns: mut compacted, } = std::mem::take(&mut self.bulk_scratch); shifted.clear(); shifted.reserve(timestamps.len()); + kept_windows.clear(); + if let Some(windows) = windows { + kept_windows.extend( + windows + .iter() + .enumerate() + .filter(|(row, _)| !stale.is_some_and(|stale| stale[*row])) + .map(|(_, &window)| window), + ); + } + let kept = windows.map(|_| kept_windows.as_slice()); for (row, ×tamp) in timestamps.iter().enumerate() { if stale.is_some_and(|stale| stale[row]) { continue; @@ -1098,6 +1187,7 @@ impl RangeEvaluator { let Some(shifted_timestamp) = timestamp.checked_add(offset_ms) else { self.bulk_scratch = BulkScratch { timestamps: shifted, + windows: kept_windows, columns: compacted, }; return Err(DataFusionError::Execution(format!( @@ -1109,7 +1199,7 @@ impl RangeEvaluator { match stale { None => { for (field, values) in self.fields.iter_mut().zip(columns) { - field.push_bulk(&shifted, values); + field.push_bulk(&shifted, kept, values); } } Some(stale) => { @@ -1125,26 +1215,37 @@ impl RangeEvaluator { ); } for (field, values) in self.fields.iter_mut().zip(&compacted) { - field.push_bulk(&shifted, values); + field.push_bulk(&shifted, kept, values); } } } self.bulk_scratch = BulkScratch { timestamps: shifted, + windows: kept_windows, columns: compacted, }; Ok(()) } - /// Retains the samples of `fields` at `timestamps`. From `raw` input a row holding a stale - /// marker in any field is dropped; evaluated input keeps it as a value. - fn ingest(&mut self, timestamps: &[i64], fields: &SeriesFields, raw: bool) -> Result<()> { - if self.ingest_in_bulk(timestamps, fields, raw)? { + /// Retains the samples of `fields` at `timestamps` shifted by `offset_ms`. From `raw` input a + /// row holding a stale marker in any field is dropped; evaluated input keeps it as a value. + /// + /// `windows` are the already shifted window times of raw input finer than a millisecond, whose + /// `timestamps` are then already shifted payloads and `offset_ms` is zero. + fn ingest( + &mut self, + timestamps: &[i64], + windows: Option<&[i64]>, + offset_ms: i64, + fields: &SeriesFields, + raw: bool, + ) -> Result<()> { + if self.ingest_in_bulk(timestamps, windows, offset_ms, fields, raw)? { return Ok(()); } let mut samples: Vec<_> = fields.iter().map(|field| field.iter()).collect(); let mut row = Vec::with_capacity(samples.len()); - for ×tamp in timestamps { + for (index, ×tamp) in timestamps.iter().enumerate() { row.clear(); let mut stale = false; for field in &mut samples { @@ -1153,7 +1254,7 @@ impl RangeEvaluator { SampleRef::Missing => {} SampleRef::Float(value) => stale |= is_prometheus_stale_nan(*value), SampleRef::Histogram(view) => { - if self.function.is_none() { + if self.function.is_none() || windows.is_some() { return Err(DataFusionError::NotImplemented( "range evaluation of histogram samples".into(), )); @@ -1167,14 +1268,12 @@ impl RangeEvaluator { continue; } // Like RangeManipulate, any kept sample whose shifted time leaves i64 fails the series. - let shifted = timestamp - .checked_add(self.window.offset_ms) - .ok_or_else(|| { - DataFusionError::Execution(format!( - "sample timestamp {timestamp} overflows with offset {} ms", - self.window.offset_ms - )) - })?; + let shifted = timestamp.checked_add(offset_ms).ok_or_else(|| { + DataFusionError::Execution(format!( + "sample timestamp {timestamp} overflows with offset {offset_ms} ms" + )) + })?; + let window = windows.map(|windows| windows[index]); // Refused here rather than when a point is evaluated: a smoothed point can be decided // before the rest of its window arrives, so whether a later histogram is seen would // depend on how the input is chunked. @@ -1193,7 +1292,7 @@ impl RangeEvaluator { match sample { SampleRef::Missing => {} SampleRef::Float(value) => { - field.push(shifted, *value); + field.push(shifted, window, *value); } SampleRef::Histogram(view) => { let mut h = FloatHistogram::try_from_view(view)?; @@ -1258,7 +1357,7 @@ impl RangeEvaluator { .iter() .map(|field| { field - .timestamps + .window_times() .last() .map_or(i128::MIN, |&t| i128::from(t)) }) @@ -1277,13 +1376,13 @@ impl RangeEvaluator { // Later windows start no earlier, so samples behind this one go even when the point // itself is not ready yet. for field in &mut self.fields { - field.head += field.timestamps[field.head..] + field.head += field.window_times()[field.head..] .partition_point(|×tamp| i128::from(timestamp) <= lower); field.histogram_head += field.histograms[field.histogram_head..] .partition_point(|(timestamp, _)| i128::from(*timestamp) <= lower); let first_histogram = field.histograms.get(field.histogram_head); for ×tamp in field - .timestamps + .window_times() .get(field.head) .into_iter() .chain(first_histogram.map(|(timestamp, _)| timestamp)) @@ -1467,10 +1566,10 @@ impl RowEvaluator<'_> { // A smoothed window also reads the samples after its end. let window_end = window_end + self.modifier.map_or(0, RangeModifier::after_ms); for field in self.fields { - let timestamps = &field.timestamps[field.head..]; - let len = timestamps.partition_point(|×tamp| timestamp <= window_end); + let len = field.window_times()[field.head..] + .partition_point(|×tamp| timestamp <= window_end); let floats = (len > 0).then(|| FloatWindow { - timestamps: ×tamps[..len], + timestamps: &field.timestamps[field.head..field.head + len], values: &field.values[field.head..field.head + len], counter_resets: field.resets_in(len), eval_ts, diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index fb89e35cdd0..2c187644d65 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -53,6 +53,7 @@ use crate::grid_series::reference::{ use crate::grid_series::{GridSample, GridSeriesBuilder}; use crate::histogram_eval::float_histogram::FloatHistogram; use crate::range_array::RangeArray; +use crate::raw_time::RawTimeUnit; use crate::select::{LabelMatcher, MatchOp, absent, absent_labels}; /// One raw row: source timestamp and a value per field, `None` when missing. @@ -1961,6 +1962,46 @@ fn a_series_that_ends_early_still_closes() { assert_eq!(rows_with_a_value(&closed.series), 0); } +/// Two microsecond samples in one millisecond share a window time, so a chunk ending on the first +/// one has not settled the window ending at that millisecond: the second may arrive next. +#[test] +fn samples_of_one_millisecond_split_across_chunks_stay_in_one_window() { + let window = RangeWindow { + range_ms: 1, + offset_ms: 0, + anchor_ms: None, + modifier: None, + }; + let rows: Vec = vec![(1_001, vec![Some(1.0)]), (1_500, vec![Some(2.0)])]; + for pieces in [ + vec![chunk(&rows, 1, 0, true)], + vec![ + chunk(&rows[..1], 1, 0, false), + chunk(&rows[1..], 1, 0, true), + ], + ] { + let mut evaluator = RangeEvaluator::try_new( + &raw_schema(1), + grid(2, 1, 1), + window, + RangeFunction::CountOverTime, + ) + .unwrap() + .with_raw_time_unit(RawTimeUnit::Microsecond); + let chunks = collect_chunks(&mut evaluator, &pieces); + let series = + fold_chunks(&chunks, evaluator.output_schema()).expect("the window has samples"); + let counts: Vec<_> = series.fields.as_slice()[0] + .iter() + .filter_map(|sample| match sample { + SampleRef::Float(value) => Some(value), + _ => None, + }) + .collect(); + assert_eq!(counts, [2.0], "{} chunks", pieces.len()); + } +} + /// An empty closing chunk drops `__name__` like the chunks before it. #[test] fn the_closing_chunk_is_labelled_like_the_chunks_before_it() { diff --git a/src/promql/src/raw_time.rs b/src/promql/src/raw_time.rs new file mode 100644 index 00000000000..f78624dfb57 --- /dev/null +++ b/src/promql/src/raw_time.rs @@ -0,0 +1,159 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The unit of the timestamps a raw source hands over, and how a sample stored in it is placed on +//! the millisecond timeline PromQL evaluates on. +//! +//! A raw source hands its time index over as stored. The existing PromQL plan decides which +//! samples a window or a lookback holds on those stored ticks, and only the timestamp a kernel reads +//! is converted to milliseconds, truncated toward zero after the offset is applied +//! (`RangeManipulate`, and `timestamp()` through an Arrow cast). Two samples less than a millisecond +//! apart therefore stay two samples, sharing one millisecond. +//! +//! Every bound the evaluation compares against is a whole millisecond, so a sample at `s` lies at +//! or before the bound `t` exactly when `ceil(s) <= t`, and after it exactly when `ceil(s) > t`. +//! The ceiling is the sample's *window* time: comparing it reproduces the stored-tick decision. +//! The truncated time is its *payload*, the time a kernel reads. They differ only for a positive +//! sample that does not fall on a whole millisecond. + +use datafusion::arrow::datatypes::TimeUnit; +use datafusion::error::{DataFusionError, Result}; + +const NANOS_PER_MILLI: i128 = 1_000_000; + +/// The unit of a raw input's timestamps: its time index's own. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, +)] +pub enum RawTimeUnit { + Second, + #[default] + Millisecond, + Microsecond, + Nanosecond, +} + +impl From for RawTimeUnit { + fn from(unit: TimeUnit) -> Self { + match unit { + TimeUnit::Second => Self::Second, + TimeUnit::Millisecond => Self::Millisecond, + TimeUnit::Microsecond => Self::Microsecond, + TimeUnit::Nanosecond => Self::Nanosecond, + } + } +} + +impl RawTimeUnit { + fn nanos_per_tick(self) -> i128 { + match self { + Self::Second => 1_000_000_000, + Self::Millisecond => 1_000_000, + Self::Microsecond => 1_000, + Self::Nanosecond => 1, + } + } + + /// Whether every tick is a whole millisecond, so a sample's window time and payload agree. + pub fn is_whole_millis(self) -> bool { + matches!(self, Self::Second | Self::Millisecond) + } + + /// The window time of `tick` shifted by `offset_ms`: the millisecond the sample is compared at. + pub fn window_ms(self, tick: i64, offset_ms: i64) -> Result { + let nanos = i128::from(tick) * self.nanos_per_tick(); + let ceil = -(-nanos).div_euclid(NANOS_PER_MILLI); + narrow(ceil + i128::from(offset_ms), tick, offset_ms) + } + + /// `tick` shifted by `offset_ms` and rounded down to a millisecond: once a sample at `tick` has + /// been read, the last bound no later sample can reach. A later sample in the same millisecond + /// shares its window time. + pub fn floor_ms(self, tick: i64, offset_ms: i64) -> Result { + let nanos = i128::from(tick) * self.nanos_per_tick(); + narrow( + nanos.div_euclid(NANOS_PER_MILLI) + i128::from(offset_ms), + tick, + offset_ms, + ) + } + + /// Whether `tick` is exactly the millisecond `millis`, which a window time cannot tell for a + /// sample just before it. + pub fn is_at(self, tick: i64, millis: i128) -> bool { + i128::from(tick) * self.nanos_per_tick() == millis * NANOS_PER_MILLI + } + + /// The payload of `tick` shifted by `offset_ms`: the millisecond a kernel reads. + pub fn payload_ms(self, tick: i64, offset_ms: i64) -> Result { + let nanos = + i128::from(tick) * self.nanos_per_tick() + i128::from(offset_ms) * NANOS_PER_MILLI; + narrow(nanos / NANOS_PER_MILLI, tick, offset_ms) + } + + /// The payloads of `ticks` shifted by `offset_ms` into `payloads`, and, when the unit is finer + /// than a millisecond, their window times into `windows`. Both are cleared first. + pub fn convert( + self, + ticks: &[i64], + offset_ms: i64, + payloads: &mut Vec, + windows: &mut Vec, + ) -> Result<()> { + payloads.clear(); + windows.clear(); + payloads.reserve(ticks.len()); + for &tick in ticks { + payloads.push(self.payload_ms(tick, offset_ms)?); + } + if !self.is_whole_millis() { + windows.reserve(ticks.len()); + for &tick in ticks { + windows.push(self.window_ms(tick, offset_ms)?); + } + } + Ok(()) + } +} + +fn narrow(millis: i128, tick: i64, offset_ms: i64) -> Result { + i64::try_from(millis).map_err(|_| { + DataFusionError::Execution(format!( + "sample timestamp {tick} overflows with offset {offset_ms} ms" + )) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn window_time_rounds_up_and_payload_truncates_toward_zero() { + let us = RawTimeUnit::Microsecond; + // 1s + 1us: after the 1s bound, read as 1000ms. + assert_eq!(us.window_ms(1_000_001, 0).unwrap(), 1001); + assert_eq!(us.payload_ms(1_000_001, 0).unwrap(), 1000); + // A negative sub-millisecond time truncates toward zero, as `RangeManipulate` does. + assert_eq!(us.window_ms(-298_999_999, 0).unwrap(), -298_999); + assert_eq!(us.payload_ms(-298_999_999, 0).unwrap(), -298_999); + // The payload is truncated after the offset is applied, so a shift across zero moves it. + assert_eq!(us.payload_ms(1_500, -2).unwrap(), 0); + assert_eq!(us.window_ms(1_500, -2).unwrap(), 0); + let s = RawTimeUnit::Second; + assert_eq!(s.window_ms(-3, 500).unwrap(), -2500); + assert_eq!(s.payload_ms(-3, 500).unwrap(), -2500); + assert!(s.payload_ms(i64::MAX, 0).is_err()); + } +} diff --git a/src/promql/tests/native_binary.rs b/src/promql/tests/native_binary.rs index 3d4a7c931d6..ef13eadd68a 100644 --- a/src/promql/tests/native_binary.rs +++ b/src/promql/tests/native_binary.rs @@ -112,6 +112,7 @@ fn source(schema: &Arc) -> NativeNode { output: output.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output, } diff --git a/src/query/src/analyze.rs b/src/query/src/analyze.rs index 7b0448fa471..add3abf64fe 100644 --- a/src/query/src/analyze.rs +++ b/src/query/src/analyze.rs @@ -601,6 +601,7 @@ mod tests { source_index: 0, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), diff --git a/src/query/src/dist_plan/commutativity.rs b/src/query/src/dist_plan/commutativity.rs index 9a3ac94f88d..2fda182a9c3 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -647,6 +647,7 @@ mod tests { output: evaluated.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: evaluated.clone(), }), @@ -900,6 +901,7 @@ mod tests { output: raw.clone(), source_index: 0, ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: raw, }; diff --git a/src/query/src/optimizer/series_frame_output.rs b/src/query/src/optimizer/series_frame_output.rs index c27dbf04ba4..473db84f069 100644 --- a/src/query/src/optimizer/series_frame_output.rs +++ b/src/query/src/optimizer/series_frame_output.rs @@ -357,6 +357,7 @@ mod tests { source_index: 0, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), @@ -428,6 +429,7 @@ mod tests { source_index: 0, output: raw.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw, }), diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 41be1e2a37b..434228811ef 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -1759,6 +1759,7 @@ fn window_selection( output: raw.clone(), source_index, ordering: context.ordering, + time_unit: Default::default(), }), output: raw, }), @@ -1942,6 +1943,7 @@ fn instant_selection_of( output: raw.clone(), source_index, ordering: context.ordering, + time_unit: Default::default(), }), output: raw, }), diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index f7f7ab03fab..f54d9b55ef4 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -4849,6 +4849,7 @@ fn validate_inputs_accepts_distinct_occurrences_sharing_a_schema() { source_index, output: NativeType::Samples(Arc::clone(&schema)), ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: NativeType::Samples(Arc::clone(&schema)), }; diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 0e480338199..adf935a508a 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -32,7 +32,7 @@ use common_catalog::consts::{FILE_ENGINE, METRIC_ENGINE, MITO_ENGINE, MITO2_ENGI use common_query::native_histogram::native_histogram_value_type; use common_query::series_frame::raw_series_frame_schema_with_ordering; use common_telemetry::debug; -use datafusion::arrow::datatypes::DataType as ArrowDataType; +use datafusion::arrow::datatypes::{DataType as ArrowDataType, TimeUnit as ArrowTimeUnit}; use datafusion::common::{Column, DFSchema, DFSchemaRef}; use datafusion::error::DataFusionError; use datafusion::logical_expr::UserDefinedLogicalNode; @@ -66,6 +66,7 @@ use promql::native::segment::{ pub(crate) use promql::native::segment::{ independent_scan_pair, is_empty_discovered_input, pointwise_operand, }; +use promql::raw_time::RawTimeUnit; use promql_parser::label::{METRIC_NAME, MatchOp, Matcher, Matchers}; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ @@ -344,9 +345,9 @@ impl PromPlanner { } None => match &input { LogicalPlan::TableScan(scan) => scan.clone(), - // A second-precision time index is read through a projection that casts it to - // milliseconds. Only a row source reads that projection; the engine check below - // declines it for any other engine. + // A time index in another unit than milliseconds is read through a projection that + // casts it. A row source reads that projection; the raw series scan reads the + // column as stored, so that route takes the scan below it once the engine is known. LogicalPlan::Projection(projection) => match projection.input.as_ref() { LogicalPlan::TableScan(scan) => scan.clone(), _ => return Ok(declined("selector_plan_is_not_a_table_scan")), @@ -384,24 +385,43 @@ impl PromPlanner { } // The region's raw-series preflight refuses these, and the physical layer turns that // refusal into an error, so decline this route here instead. - let time_index_type = table_meta + if table_meta + .options + .extra_options + .get(store_api::mito_engine_options::APPEND_MODE_KEY) + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + return Ok(declined("append_mode_table")); + } + let time_index_unit = table_meta .schema .timestamp_column() - .map(|column| &column.data_type); - // A row source reads a second-precision time index as the milliseconds it is exactly. - let readable_time_index = time_index_type - == Some(&datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype()) - || (reads_rows - && time_index_type - == Some(&datatypes::prelude::ConcreteDataType::timestamp_second_datatype())); - if !readable_time_index - || table_meta - .options - .extra_options - .get(store_api::mito_engine_options::APPEND_MODE_KEY) - .is_some_and(|value| value.eq_ignore_ascii_case("true")) + .map(|column| column.data_type.as_arrow_type()); + // A row source reads milliseconds, and a second-precision time index as the milliseconds + // it is exactly. + if reads_rows + && !matches!( + time_index_unit, + Some(ArrowDataType::Timestamp( + ArrowTimeUnit::Millisecond | ArrowTimeUnit::Second, + _ + )) + ) { - return Ok(declined("unsupported_time_index_type_or_append_mode")); + return Ok(declined("row_source_sub_millisecond_time_index")); + } + let sub_millisecond_time_index = matches!( + time_index_unit, + Some(ArrowDataType::Timestamp( + ArrowTimeUnit::Microsecond | ArrowTimeUnit::Nanosecond, + _ + )) + ); + if !reads_rows + && let LogicalPlan::Projection(projection) = &input + && let LogicalPlan::TableScan(scan) = projection.input.as_ref() + { + input = LogicalPlan::TableScan(scan.clone()); } // Admitted: such inputs are read through a raw source, which reconciles the fragments. let split_series = !table_meta @@ -423,6 +443,11 @@ impl PromPlanner { if statement_kind.is_some_and(|kind| kind != field_kind) { return Ok(declined("selectors_disagree_on_field_kind")); } + // A histogram window keeps one time per sample, where a time index finer than milliseconds + // needs the window time beside the payload (`promql::raw_time`). + if field_kind == FieldKind::Histogram && sub_millisecond_time_index { + return Ok(declined("histogram_over_a_sub_millisecond_time_index")); + } *statement_kind = Some(field_kind); let series_schema = Arc::new(SeriesSchema { fields: fields @@ -473,6 +498,22 @@ impl PromPlanner { ))) } + /// The unit of the time index `scan` reads. + fn scan_time_unit(&self, scan: &datafusion::logical_expr::TableScan) -> Result { + let table = self.table_from_source(&scan.source)?; + match table + .schema() + .timestamp_column() + .map(|column| column.data_type.as_arrow_type()) + { + Some(ArrowDataType::Timestamp(unit, _)) => Ok(unit), + _ => TimeIndexNotFoundSnafu { + table: scan.table_name.to_string(), + } + .fail(), + } + } + /// Offers a statement root to the native route, including a TQL `AS` alias over the expression /// it names. /// @@ -697,6 +738,7 @@ impl PromPlanner { source_index, output: output.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: output.clone(), }; @@ -1269,7 +1311,7 @@ impl PromPlanner { let bind_index = std::cell::Cell::new(0usize); let mut compile_stmt = stmt.clone(); compile_stmt.expr = effective_expr.clone(); - let compiled = match compile_selectors_with_grid( + let mut compiled = match compile_selectors_with_grid( &compile_stmt, &|req| { let i = bind_index.get(); @@ -1312,6 +1354,8 @@ impl PromPlanner { )) .context(DataFusionPlanningSnafu); } + // The unit each input hands its timestamps over in, which its evaluation is bound to. + let mut input_time_units = Vec::with_capacity(prepared.len()); for (index, (compiled_input, (scan, _, _, time, _, _, _, _))) in compiled.inputs.iter().zip(prepared.iter_mut()).enumerate() { @@ -1322,7 +1366,6 @@ impl PromPlanner { .requirement .raw_scan_bounds() .context(DataFusionPlanningSnafu)?; - let filter = scan_time_filter(start, end, inclusive, time); if let LogicalPlan::Extension(extension) = scan && extension.node.as_any().is::() { @@ -1338,7 +1381,11 @@ impl PromPlanner { )) .context(DataFusionPlanningSnafu); }; - table_scan.filters.push(filter); + let unit = self.scan_time_unit(table_scan)?; + table_scan + .filters + .push(scan_time_filter(start, end, inclusive, time, unit)); + input_time_units.push(RawTimeUnit::from(unit)); let replacement = extension .node .with_exprs_and_inputs(vec![], inputs) @@ -1347,6 +1394,7 @@ impl PromPlanner { } else if let LogicalPlan::Union(union) = scan { // Discovered metrics may name their time columns differently, so each source is // bounded on its own column. + let mut union_unit = None; for child in &mut union.inputs { let LogicalPlan::Extension(extension) = child.as_ref() else { return Err(DataFusionError::Internal(format!( @@ -1388,7 +1436,14 @@ impl PromPlanner { ))) .context(DataFusionPlanningSnafu); }; - let source_filter = scan_time_filter(start, end, inclusive, &source_time); + // Logical metrics on different physical tables may disagree on the unit, and + // the union is one input read in one unit. Answering needs a per-source + // rescale, which the planned fix puts on the wire (#10767). + let unit = self.scan_time_unit(table_scan)?; + if *union_unit.get_or_insert(unit) != unit { + return Ok(declined("discovered_metrics_disagree_on_time_unit")); + } + let source_filter = scan_time_filter(start, end, inclusive, &source_time, unit); table_scan.filters.push(source_filter); let replacement = extension .node @@ -1396,14 +1451,26 @@ impl PromPlanner { .context(DataFusionPlanningSnafu)?; *child = Arc::new(LogicalPlan::Extension(Extension { node: replacement })); } + input_time_units + .push(union_unit.map_or(RawTimeUnit::Millisecond, RawTimeUnit::from)); } else if let LogicalPlan::Extension(extension) = scan && let Some(source) = extension.node.as_any().downcast_ref::() { + // A row source hands over milliseconds, whatever unit its file stores. + let filter = + scan_time_filter(start, end, inclusive, time, ArrowTimeUnit::Millisecond); *scan = bind_row_source_filters(source, filter, time) .context(DataFusionPlanningSnafu)?; + input_time_units.push(RawTimeUnit::Millisecond); } else if let LogicalPlan::TableScan(table_scan) = scan { - table_scan.filters.push(filter); + let unit = self.scan_time_unit(table_scan)?; + table_scan + .filters + .push(scan_time_filter(start, end, inclusive, time, unit)); + input_time_units.push(RawTimeUnit::from(unit)); } else if let LogicalPlan::EmptyRelation(_) = scan { + // The typed empty input hands over no timestamps. + input_time_units.push(RawTimeUnit::Millisecond); } else { return Err(DataFusionError::Internal(format!( "the child at {index} is not the table scan this route prepared" @@ -1411,6 +1478,23 @@ impl PromPlanner { .context(DataFusionPlanningSnafu); } } + compiled.tree = NativeTree::try_new( + compiled + .tree + .root() + .with_input_time_units(&input_time_units), + ) + .context(DataFusionPlanningSnafu)?; + // A range modifier reads the samples around its window, which this route only places on a + // millisecond timeline. + if compiled.tree.root().any(&|node| { + matches!(&node.expr, NativeExpr::Window { input, op } + if op.window.modifier.is_some() + && matches!(&input.expr, NativeExpr::Input(input) + if !input.time_unit.is_whole_millis())) + }) { + return Ok(declined("range_modifier_over_a_sub_millisecond_time_index")); + } let multi_input = selectors.len() > 1; // The tags each input declares for the output layout. With several inputs, `__name__` is // declared so a grouping keeps two metrics apart; a single input only gets it appended by @@ -2233,23 +2317,60 @@ fn plan_split_aggregate( .context(DataFusionPlanningSnafu) } -/// The time-range filter a selector's scan reads, from the bounds its compiled requirement names. -fn scan_time_filter(start: i64, end: i64, inclusive: bool, time_column: &str) -> DfExpr { +/// The time-range filter a selector's scan reads, from the millisecond bounds its compiled +/// requirement names, over a time index stored in `unit`. +fn scan_time_filter( + start: i64, + end: i64, + inclusive: bool, + time_column: &str, + unit: ArrowTimeUnit, +) -> DfExpr { + use datafusion::scalar::ScalarValue; + let column = DfExpr::Column(datafusion::common::Column::from_name(time_column)); - let lower = DfExpr::Literal( - datafusion::scalar::ScalarValue::TimestampMillisecond(Some(start), None), - None, - ); - let upper = DfExpr::Literal( - datafusion::scalar::ScalarValue::TimestampMillisecond(Some(end), None), - None, - ); - let lower = if inclusive { - column.clone().gt_eq(lower) - } else { - column.clone().gt(lower) + if unit == ArrowTimeUnit::Millisecond { + let lower = DfExpr::Literal(ScalarValue::TimestampMillisecond(Some(start), None), None); + let upper = DfExpr::Literal(ScalarValue::TimestampMillisecond(Some(end), None), None); + let lower = if inclusive { + column.clone().gt_eq(lower) + } else { + column.clone().gt(lower) + }; + return lower.and(column.lt_eq(upper)); + } + // The bounds are on the window time `ceil(s)` the evaluation places a sample at + // (`promql::raw_time`): `ceil(s) >= start` holds iff `s > start - 1ms`, `ceil(s) > start` iff + // `s > start`, and `ceil(s) <= end` iff `s <= end`. In ticks, `s > l` iff + // `tick > floor(l / tick)` and `s <= e` iff `tick <= floor(e / tick)`. + let nanos_per_tick: i128 = match unit { + ArrowTimeUnit::Second => 1_000_000_000, + ArrowTimeUnit::Millisecond => 1_000_000, + ArrowTimeUnit::Microsecond => 1_000, + ArrowTimeUnit::Nanosecond => 1, }; - lower.and(column.lt_eq(upper)) + let ticks = |millis: i128| (millis * 1_000_000).div_euclid(nanos_per_tick); + let literal = |tick: i64| { + let value = match unit { + ArrowTimeUnit::Second => ScalarValue::TimestampSecond(Some(tick), None), + ArrowTimeUnit::Millisecond => ScalarValue::TimestampMillisecond(Some(tick), None), + ArrowTimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(Some(tick), None), + ArrowTimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(Some(tick), None), + }; + DfExpr::Literal(value, None) + }; + let lower = ticks(i128::from(start) - i128::from(inclusive)); + let upper = ticks(i128::from(end)); + if lower >= i128::from(i64::MAX) || upper < i128::from(i64::MIN) { + return datafusion::prelude::lit(false); + } + let lower = (lower >= i128::from(i64::MIN)).then(|| column.clone().gt(literal(lower as i64))); + let upper = (upper <= i128::from(i64::MAX)).then(|| column.lt_eq(literal(upper as i64))); + match (lower, upper) { + (Some(lower), Some(upper)) => lower.and(upper), + (Some(bound), None) | (None, Some(bound)) => bound, + (None, None) => datafusion::prelude::lit(true), + } } /// Whether any aggregate in `node` consumes histogram samples, wherever it sits in the tree. @@ -3549,16 +3670,18 @@ mod tests { #[test] fn millisecond_scan_bounds_preserve_open_closed_and_maximum_edges() { - let inclusive = scan_time_filter(0, 10, true, "ts").to_string(); + let inclusive = scan_time_filter(0, 10, true, "ts", ArrowTimeUnit::Millisecond).to_string(); assert!(inclusive.contains(">="), "{inclusive}"); assert!(inclusive.contains("<="), "{inclusive}"); - let exclusive = scan_time_filter(0, 10, false, "ts").to_string(); + let exclusive = + scan_time_filter(0, 10, false, "ts", ArrowTimeUnit::Millisecond).to_string(); assert!(exclusive.contains("> "), "{exclusive}"); assert!(!exclusive.contains(">="), "{exclusive}"); assert!(exclusive.contains("<="), "{exclusive}"); - let maximum = scan_time_filter(i64::MAX, i64::MAX, false, "ts").to_string(); + let maximum = scan_time_filter(i64::MAX, i64::MAX, false, "ts", ArrowTimeUnit::Millisecond) + .to_string(); assert!(maximum.contains("> "), "{maximum}"); assert!(!maximum.contains(">="), "{maximum}"); assert!(maximum.contains("<="), "{maximum}"); diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 59ad0d3ac24..d6497ab335f 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -4249,40 +4249,46 @@ async fn native_fused_time_partitioned_table_reads_through_a_raw_source() { ); } +/// A time index stored in seconds, microseconds or nanoseconds is read as stored, and the scan is +/// bounded by literals in that unit rather than by a cast of the column. #[tokio::test] -async fn native_fused_non_millisecond_time_index_falls_back() { - let table_provider = build_test_table_provider_with_options( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - vec![], - ConcreteDataType::timestamp_microsecond_datatype(), - false, - ConcreteDataType::float64_datatype(), - NATIVE_ENGINE, - ) - .await; - let native = - build_native_fused_plan_with_provider("rate(some_metric[5m])", true, table_provider).await; - let fallback_provider = build_test_table_provider_with_options( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - vec![], - ConcreteDataType::timestamp_microsecond_datatype(), - false, - ConcreteDataType::float64_datatype(), - NATIVE_ENGINE, - ) - .await; - let without_flag = - build_native_fused_plan_with_provider("rate(some_metric[5m])", false, fallback_provider) - .await; - assert!(!native.display_indent().to_string().contains("FusedSeries")); - assert_eq!( - native.display_indent().to_string(), - without_flag.display_indent().to_string() - ); +async fn native_fused_reads_a_non_millisecond_time_index() { + for (time_index, literal) in [ + ( + ConcreteDataType::timestamp_second_datatype(), + "TimestampSecond(", + ), + ( + ConcreteDataType::timestamp_microsecond_datatype(), + "TimestampMicrosecond(", + ), + ( + ConcreteDataType::timestamp_nanosecond_datatype(), + "TimestampNanosecond(", + ), + ] { + let table_provider = build_test_table_provider_with_options( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 1, + 1, + vec![], + time_index.clone(), + false, + ConcreteDataType::float64_datatype(), + NATIVE_ENGINE, + ) + .await; + let native = + build_native_fused_plan_with_provider("rate(some_metric[5m])", true, table_provider) + .await; + let display = native.display_indent().to_string(); + assert!( + find_fused_series(&native).is_some(), + "{time_index:?}: {display}" + ); + assert_eq!(take_reported_decline(), None, "{time_index:?}: {display}"); + assert!(display.contains(literal), "{time_index:?}: {display}"); + } } #[tokio::test] diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index fa3a8afe9eb..094e5b0af5c 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -954,6 +954,7 @@ mod tests { source_index: 0, output: raw_type.clone(), ordering: SeriesOrdering::Contiguous, + time_unit: Default::default(), }), output: raw_type, }), diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 4c79565668c..d6120ff946a 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -3351,6 +3351,177 @@ async fn native_promql_otlp_delta_histogram_rates_match_legacy() { } } +/// A time index in seconds, microseconds or nanoseconds is read natively with the existing route's +/// semantics: windows and lookbacks are decided on the stored ticks, a kernel reads the time +/// truncated to milliseconds, and samples less than a millisecond apart stay distinct samples. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_non_millisecond_time_index_answers_like_legacy() { + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_non_millisecond_time_index", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE native_us (ts TIMESTAMP(6) TIME INDEX, series STRING PRIMARY KEY, val DOUBLE); \ + INSERT INTO native_us VALUES (0, 'window', 1), (1, 'window', 2), (2, 'window', 5), \ + (1000000, 'window', 3), (1000001, 'window', 4), (999500, 'past', 7), \ + (1000001, 'future', 9), (999999, 'counter', 1), (1000500, 'counter', 3), \ + (1999700, 'counter', 8), (-1500, 'negative', 6); \ + CREATE TABLE native_ns (ts TIMESTAMP(9) TIME INDEX, job STRING PRIMARY KEY, val DOUBLE); \ + INSERT INTO native_ns VALUES (999999900, 'sub_ms', 999), (999999100, 'sub_ms', 10), \ + (999999500, 'sub_ms', 13), (998000000, 'one_ms', 10), (999000000, 'one_ms', 13); \ + CREATE TABLE native_sec (ts TIMESTAMP(0) TIME INDEX, host STRING PRIMARY KEY, val DOUBLE); \ + INSERT INTO native_sec VALUES (0, 'a', 1), (1, 'a', 2), (2, 'a', 4), (3, 'a', 8)", + QueryContext::arc(), + ) + .await; + let queries = [ + ( + "TQL EVAL (1, 2, '1s', '300s') native_us", + ReportedName::Metric("native_us"), + ), + ( + "TQL EVAL (0, 0, '1s', '300s') native_us offset -1s", + ReportedName::Metric("native_us"), + ), + ( + "TQL EVAL (1, 2, '1s', '300s') timestamp(native_us)", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 1, '1s', '0') native_us", + ReportedName::Metric("native_us"), + ), + ( + "TQL EVAL (1, 1, '1s', '0') native_us @ 1", + ReportedName::Metric("native_us"), + ), + ( + "TQL EVAL (1, 2, '1s') count_over_time(native_us[1s])", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 2, '1s') sum_over_time(native_us[1s] offset 1ms)", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 2, '1s') last_over_time(native_us[1s])", + ReportedName::Metric("native_us"), + ), + ( + "TQL EVAL (2, 2, '1s') rate(native_us[2s])", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 1, '1s') irate(native_ns[5s])", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 1, '1s') idelta(native_ns[5s])", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 1, '1s') count_over_time(native_ns[5s])", + ReportedName::Nothing, + ), + ( + "TQL EVAL (1, 1, '1s', '1s') native_sec offset 500ms", + ReportedName::Metric("native_sec"), + ), + ( + "TQL EVAL (3, 3, '1s') rate(native_sec[3s])", + ReportedName::Nothing, + ), + // Two selectors over tables in different units, each read in its own. + ( + "TQL EVAL (1, 2, '1s') sum(count_over_time(native_us[2s])) + sum(count_over_time(native_ns[2s]))", + ReportedName::Nothing, + ), + ( + "TQL EVAL (2, 3, '1s') sum(rate(native_sec[3s])) - sum(rate(native_us[2s]))", + ReportedName::Nothing, + ), + ]; + // Once from the memtables and once from the flushed files. + for flushed in [false, true] { + if flushed { + for table in ["native_us", "native_ns", "native_sec"] { + execute_all( + &instance, + &format!("ADMIN FLUSH_TABLE('{table}')"), + QueryContext::arc(), + ) + .await; + } + } + for (sql, reported) in queries { + observer.clear(); + let native = eval_text_rows( + collected(native_tql_output(&instance, sql, true).await).await, + reported, + ); + assert_native_rows_plan(&observer); + let legacy = eval_text(collected(native_tql_output(&instance, sql, false).await).await); + assert_text_rows_close(&legacy, &native, &format!("flushed={flushed}: {sql}")); + } + } +} + +/// Discovery across physical tables whose time indexes differ in unit is deliberately unsupported: +/// a native input carries one time unit, so answering would read one source's ticks in the other's. +/// Fixing it needs a per-source rescale, and the planned one changes the `RawSeriesSource` wire +/// format (#10767). +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_discovery_over_mixed_time_units_is_unsupported() { + let (standalone, _observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_discovery_mixed_units", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE mixed_phy_ms (ts TIMESTAMP TIME INDEX, v DOUBLE) \ + ENGINE=metric WITH (\"physical_metric_table\" = \"\"); \ + CREATE TABLE mixed_phy_us (ts TIMESTAMP(6) TIME INDEX, v DOUBLE) \ + ENGINE=metric WITH (\"physical_metric_table\" = \"\"); \ + CREATE TABLE mixed_a (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'mixed_phy_ms'); \ + CREATE TABLE mixed_b (host STRING NULL, ts TIMESTAMP(6) NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'mixed_phy_us'); \ + INSERT INTO mixed_a (host, ts, v) VALUES ('a', 1000, 2); \ + INSERT INTO mixed_b (host, ts, v) VALUES ('b', 1000000, 8)", + QueryContext::arc(), + ) + .await; + let mut ctx = QueryContext::with_db_name(None); + ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); + let declined = || { + query::metrics::NATIVE_PROMQL_DECLINED_TOTAL + .with_label_values(&["discovered_metrics_disagree_on_time_unit"]) + .get() + }; + let declined_before = declined(); + let result = instance + .do_query( + r#"TQL EVAL (2, 2, '1s') count_over_time({host=~"a|b"}[2s])"#, + Arc::new(ctx), + ) + .await + .remove(0); + assert_eq!( + declined() - declined_before, + 1, + "the native route must decline for the mixed units, not for another cause" + ); + // The existing plan, which the statement keeps, refuses a nameless selector. + if let Ok(output) = result { + panic!("answered natively: {:?}", native_rows(output, None).await); + } +} + /// `output` with its stream read here: [`eval_text_rows`] blocks on the stream, which inside this /// runtime stops being woken once the test task has spent its cooperative budget. async fn collected(output: Output) -> Output { @@ -3362,6 +3533,30 @@ async fn collected(output: Output) -> Output { } } +/// Two [`eval_text`] answers that agree cell by cell, a float cell up to its last digits: the two +/// routes sum the same terms in a different order. +fn assert_text_rows_close(expected: &str, actual: &str, context: &str) { + let rows = |text: &str| { + text.lines() + .map(|line| line.split(" | ").map(str::to_string).collect::>()) + .collect::>() + }; + let (expected_rows, actual_rows) = (rows(expected), rows(actual)); + let close = expected_rows.len() == actual_rows.len() + && expected_rows.iter().zip(&actual_rows).all(|(left, right)| { + left.len() == right.len() + && left.iter().zip(right).all(|(left, right)| { + left == right + || matches!( + (left.parse::(), right.parse::()), + (Ok(left), Ok(right)) + if (left - right).abs() <= 1e-12 * left.abs().max(right.abs()) + ) + }) + }); + assert!(close, "{context}\nexpected: {expected}\nactual: {actual}"); +} + /// The plan the last query ran is the native one, so a row assertion above is about this route. fn assert_native_rows_plan(observer: &NativePlanObserver) { let root = observer.root_plan(); diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index b48e245093a..e7e0f3b0dd9 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -2079,6 +2079,7 @@ async fn assert_raw_scan_fused_formats(observer: &NativeFusedObserver, frontend: source_index: 0, output: raw_type.clone(), ordering, + time_unit: Default::default(), }), output: raw_type, }), diff --git a/tests-integration/tests/native_prefix.rs b/tests-integration/tests/native_prefix.rs index 4004c8069dc..5f21def40d6 100644 --- a/tests-integration/tests/native_prefix.rs +++ b/tests-integration/tests/native_prefix.rs @@ -131,6 +131,7 @@ async fn native_prefix_multi_partition_single_position_chains() { source_index: 0, output: raw_type.clone(), ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: raw_type, }), @@ -321,6 +322,7 @@ async fn native_prefix_multi_partition_multi_chunk_chains() { source_index: 0, output: raw_type.clone(), ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: raw_type, }), @@ -504,6 +506,7 @@ async fn native_prefix_executes_over_real_mito_region() { source_index: 0, output: raw_type.clone(), ordering: SeriesOrdering::KeyThenTime, + time_unit: Default::default(), }), output: raw_type, }), @@ -634,7 +637,7 @@ async fn native_prefix_executes_over_real_mito_region() { .try_into() .unwrap_or_else(|_| panic!("missing version bytes at {envelope_at}")); let version = u32::from_le_bytes(version_bytes); - assert_eq!(version, 1, "observed version bytes: {version_bytes:?}"); + assert_eq!(version, 2, "observed version bytes: {version_bytes:?}"); let length_bytes: [u8; 4] = tampered[envelope_at + 4..envelope_at + 8] .try_into() .unwrap_or_else(|_| panic!("missing length bytes at {}", envelope_at + 4));