From 5b649daaeaf019616cb6e6b05798e73a54b73227 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:30:55 +0800 Subject: [PATCH 01/10] feat(mito2): produce typed raw series from RegionScanner with truthful ordering Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- Cargo.lock | 1 + src/mito2/Cargo.toml | 1 + src/mito2/src/engine/scan_test.rs | 918 +++++++++++++++++++- src/mito2/src/read/series_scan.rs | 383 ++++---- src/mito2/src/read/series_scan/raw.rs | 13 +- src/mito2/src/read/series_scan/raw/tests.rs | 76 +- 6 files changed, 1211 insertions(+), 181 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ea2a530d6b5..43d65a03bd8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8742,6 +8742,7 @@ dependencies = [ "partition", "pin-project", "prometheus 0.14.0", + "promql", "prost 0.14.1", "puffin", "rand 0.9.4", diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index 02c134e964c..151694c40d1 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -101,6 +101,7 @@ dotenv.workspace = true log-store = { workspace = true, features = ["testing"] } mito-codec = { workspace = true, features = ["testing"] } object-store = { workspace = true, features = ["services-memory"] } +promql.workspace = true rskafka.workspace = true rstest.workspace = true rstest_reuse.workspace = true diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index a893a234adc..3ad13fac11e 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -4772,6 +4772,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { use datatypes::series::samples::SampleRef; use datatypes::value::Value as DatumValue; use mito_codec::row_converter::build_primary_key_codec; + use promql::source::materialize_raw_labels; use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; use store_api::region_request::RegionDeleteRequest; use table::predicate::Predicate; @@ -4907,7 +4908,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) .unwrap() .expect("supported millisecond PerSeries scan"); - assert_eq!(SeriesOrdering::Contiguous, stream.ordering()); + assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering()); assert!(stream.schema().eval_grid.is_none()); assert_eq!( vec!["field_1", "field_0"], @@ -4925,7 +4926,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { !closed_keys.contains(chunk.primary_key.as_slice()), "no chunk may follow a key's is_last chunk" ); - let times = chunk.time.as_buffer().as_ref(); + let times = chunk.time.as_buffer(); assert_eq!(2, chunk.fields.len()); assert_eq!(times.len(), chunk.fields.get(0).unwrap().len()); assert_eq!(times.len(), chunk.fields.get(1).unwrap().len()); @@ -4994,7 +4995,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { } // Compare keyed visible tuples through a separately opened legacy scanner. // A partition cannot be consumed through both paths. - let mut legacy_request = request; + let mut legacy_request = request.clone(); legacy_request.projection = Some(vec![0, 3, 2, 1, 4]); legacy_request.preserve_pk_dictionary_encoding = false; let legacy = engine @@ -5090,6 +5091,133 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { .collect::>(); raw_visible.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))); assert_eq!(raw_visible, visible); + + // Exercise the production table physical consumer over a fresh real Mito scanner. + use common_query::series_frame::unpack_raw_series; + use datafusion::execution::TaskContext; + use datafusion::physical_plan::ExecutionPlan; + use table::table::scan::RegionScanExec; + let native_scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let native_metadata = native_scanner.metadata(); + let native_tags = native_metadata + .column_metadatas + .iter() + .filter(|c| c.semantic_type == SemanticType::Tag) + .map(|c| BoundTag { + column_id: c.column_id, + name: Arc::from(c.column_schema.name.as_str()), + }) + .collect::>(); + let native_source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: native_metadata, + logical_tags: native_tags.into(), + }; + let native_plan = Arc::new(RegionScanExec::new(native_scanner, request.clone(), None).unwrap()); + let native_plan = native_plan + .try_to_series_scan(native_source.clone()) + .unwrap() + .expect("Mito raw-series capability"); + let native_schema = native_plan.series_schema().clone(); + let native_frames = native_plan + .execute(0, Arc::new(TaskContext::default())) + .unwrap(); + let unpacked = unpack_raw_series( + native_frames, + native_schema, + native_source, + SeriesOrdering::Contiguous, + ) + .unwrap(); + let native_schema = unpacked.schema().clone(); + let materialized = materialize_raw_labels(unpacked).unwrap(); + assert!(matches!( + materialized.label_source(), + RawLabelSource::Explicit + )); + let mut native = materialized.try_collect::>().await.unwrap(); + assert_eq!( + vec!["field_1", "field_0"], + native_schema + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>() + ); + let mut native_visible = native + .drain(..) + .flat_map(|chunk| { + let metric = chunk.metric.as_ref().expect("materialized complete metric"); + assert_eq!(Some("fixture_metric"), metric.name()); + let labels = metric + .tags() + .iter() + .map(|label| (label.name.as_ref(), label.value.as_ref())) + .collect::>(); + assert_eq!(1, labels.len()); + let tag = labels["tag_0"].to_string(); + assert!(tag == "A" || tag == "B"); + let times = chunk.time.as_buffer(); + let key = chunk.primary_key.to_vec(); + let is_last = chunk.is_last; + let mut rows = Vec::with_capacity(times.len()); + for (i, time) in times.iter().enumerate() { + let SampleRef::Float(f1) = chunk.fields.get(0).unwrap().sample(i) else { + panic!("expected f1 float") + }; + let f0 = match chunk.fields.get(1).unwrap().sample(i) { + SampleRef::Float(value) => Some(value), + SampleRef::Missing => None, + _ => panic!("expected f0 float or null"), + }; + rows.push(( + key.clone(), + tag.clone(), + *time, + f1, + f0, + is_last && i + 1 == times.len(), + )); + } + rows + }) + .collect::>(); + let mut expected_native = raw + .iter() + .map(|(key, time, f1, f0, _)| (key.to_vec(), *time, *f1, *f0)) + .collect::>(); + type NativeRow = (Vec, String, i64, f64, Option, bool); + let sort_native = |rows: &mut Vec| { + rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2))); + }; + sort_native(&mut native_visible); + expected_native.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))); + assert_eq!( + expected_native, + native_visible + .iter() + .map(|(key, _, time, f1, f0, _)| (key.clone(), *time, *f1, *f0)) + .collect::>() + ); + for key in &expected_keys { + assert_eq!( + 1, + native_visible + .iter() + .filter(|(row_key, _, _, _, _, is_last)| row_key == key && *is_last) + .count() + ); + } + let mut decoded_visible = native_visible + .iter() + .map(|(_, tag, time, f1, f0, _)| (tag.clone(), *time, *f1, *f0)) + .collect::>(); + decoded_visible.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))); + assert_eq!(visible, decoded_visible); + // Apply the typed predicate and final projection through the ordinary legacy filter path. assert_eq!(3, visible.len()); assert_eq!( @@ -5102,6 +5230,602 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { ); } +#[tokio::test] +async fn test_mito_regional_raw_merge_preserves_global_key_order_and_labels() { + use api::v1::{Row, Value}; + use common_query::series_frame::{pack_raw_series, unpack_raw_series}; + use datatypes::arrow::array::Array; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::{SampleRef, SeriesSchema}; + use datatypes::value::Value as DatumValue; + use mito_codec::row_converter::build_primary_key_codec; + use promql::source::{materialize_raw_labels, merge_ordered_raw_series}; + use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; + use store_api::region_request::RegionDeleteRequest; + + let mut env = TestEnv::with_prefix("test_mito_regional_raw_merge").await; + let engine = env.create_engine(MitoConfig::default()).await; + let regions = [RegionId::new(1, 1), RegionId::new(1, 2)]; + let mut request = CreateRequestBuilder::new().field_num(3).build(); + request + .options + .insert("memtable.type".into(), "bulk".into()); + let schema = test_util::rows_schema(&request); + for region in regions { + engine + .handle_request(region, RegionRequest::Create(request.clone())) + .await + .unwrap(); + } + let make_row = |tag: &str, f0: Option, f1: f64, gate: f64, time: i64| Row { + values: vec![ + Some(ValueData::StringValue(tag.into())), + f0.map(ValueData::F64Value), + Some(ValueData::F64Value(f1)), + Some(ValueData::F64Value(gate)), + Some(ValueData::TimestampMillisecondValue(time)), + ] + .into_iter() + .map(|value_data| Value { value_data }) + .collect(), + }; + for (region, rows) in [ + ( + regions[0], + vec![ + make_row("A", Some(10.0), 1.0, 1.0, 10), + make_row("A", None, 3.0, 1.0, 30), + make_row("B", Some(-0.0), 5.0, 1.0, 10), + ], + ), + ( + regions[1], + vec![ + make_row("A", Some(20.0), 2.0, 1.0, 20), + make_row("A", Some(40.0), 4.0, 1.0, 40), + make_row("C", Some(60.0), 6.0, 1.0, 10), + ], + ), + ] { + test_util::put_rows( + &engine, + region, + Rows { + schema: schema.clone(), + rows, + }, + ) + .await; + } + test_util::flush_region(&engine, regions[0], None).await; + test_util::flush_region(&engine, regions[1], None).await; + test_util::put_rows( + &engine, + regions[0], + Rows { + schema: schema.clone(), + rows: vec![ + make_row("A", Some(11.0), 11.0, 1.0, 10), + make_row("A", Some(50.0), 5.0, 0.0, 50), + make_row("B", Some(60.0), 6.0, 1.0, 60), + ], + }, + ) + .await; + engine + .handle_request( + regions[0], + RegionRequest::Delete(RegionDeleteRequest { + rows: Rows { + schema: test_util::delete_rows_schema( + &CreateRequestBuilder::new().field_num(3).build(), + ), + rows: vec![row(vec![ + ValueData::StringValue("B".into()), + ValueData::TimestampMillisecondValue(60), + ])], + }, + hint: None, + partition_expr_version: None, + }), + ) + .await + .unwrap(); + let request = ScanRequest { + projection: Some(vec![2, 1, 4]), + filters: vec![col("field_2").gt(lit(0.0_f64))], + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let mut streams = Vec::new(); + let mut metadata_for_codec = None; + let mut expected_schema: Option> = None; + let metrics = ExecutionPlanMetricsSet::default(); + for region in regions { + let selected = engine.scanner(region, request.clone()).await.unwrap(); + let mut scanner: Box = match selected { + Scanner::Series(series) => { + assert_eq!("legacy", series.mode()); + Box::new(series) + } + _ => panic!("PerSeries request must select a series scanner"), + }; + assert_eq!(SeriesOrdering::KeyThenTime, scanner.raw_series_ordering()); + let metadata = scanner.metadata(); + metadata_for_codec.get_or_insert_with(|| metadata.clone()); + let source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: metadata.clone(), + logical_tags: metadata + .column_metadatas + .iter() + .filter(|column| { + column.semantic_type == SemanticType::Tag + && !store_api::storage::consts::is_internal_column( + &column.column_schema.name, + ) + && !store_api::metric_engine_consts::is_metric_engine_internal_column( + &column.column_schema.name, + ) + }) + .map(|column| BoundTag { + column_id: column.column_id, + name: Arc::from(column.column_schema.name.as_str()), + }) + .collect::>() + .into(), + }; + let ranges = scanner + .properties() + .partitions + .clone() + .into_iter() + .flatten() + .collect::>(); + assert!(!ranges.is_empty(), "region scan needs an input range"); + let partition_count = 2; + let mut partitions = vec![Vec::new(); partition_count]; + for (index, range) in ranges.into_iter().enumerate() { + partitions[index % partition_count].push(range); + } + scanner + .prepare(PrepareRequest { + ranges: Some(partitions), + target_partitions: Some(partition_count), + ..Default::default() + }) + .unwrap(); + let partition_count = scanner.properties().num_partitions(); + assert!( + partition_count > 1, + "prepare must use multiple supplied native range partitions" + ); + for partition in 0..partition_count { + let stream = scanner + .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) + .unwrap() + .expect("native raw input"); + assert_eq!(scanner.raw_series_ordering(), stream.ordering()); + assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering()); + assert_eq!( + vec!["field_1", "field_0"], + stream + .schema() + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>() + ); + if let Some(schema) = &expected_schema { + assert_eq!( + schema + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>(), + stream + .schema() + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>() + ); + } else { + expected_schema = Some(Arc::clone(stream.schema())); + } + streams.push(stream); + } + // Each scanner owns the same schema and explicitly bound source. + } + let merged = merge_ordered_raw_series(streams).unwrap(); + let merged_schema = Arc::clone(merged.schema()); + let binding = merged.label_source().clone(); + let ordering = merged.ordering(); + assert_eq!(SeriesOrdering::KeyThenTime, ordering); + let packed = pack_raw_series(merged).unwrap(); + let unpacked = unpack_raw_series(packed, merged_schema, binding, ordering).unwrap(); + let mut materialized = materialize_raw_labels(unpacked).unwrap(); + let mut actual = Vec::new(); + while let Some(chunk) = materialized.try_next().await.unwrap() { + let metric = chunk.metric.as_ref().unwrap(); + assert_eq!(Some("fixture_metric"), metric.name()); + let tag = metric.get("tag_0").unwrap().to_string(); + for index in 0..chunk.time.len() { + let SampleRef::Float(f1) = chunk.fields.get(0).unwrap().sample(index) else { + panic!("field_1 float") + }; + let f0 = match chunk.fields.get(1).unwrap().sample(index) { + SampleRef::Float(value) => Some(value.to_bits()), + SampleRef::Missing => None, + _ => panic!("unexpected field_0 sample type"), + }; + actual.push(( + chunk.primary_key.to_vec(), + tag.clone(), + chunk.time.timestamp(index).unwrap(), + f1.to_bits(), + f0, + chunk.is_last && index + 1 == chunk.time.len(), + )); + } + } + assert!( + actual + .windows(2) + .all(|pair| pair[0].0 < pair[1].0 || (pair[0].0 == pair[1].0 && pair[0].2 < pair[1].2)), + "merged stream must be ordered by full read key then time" + ); + let metadata = metadata_for_codec.unwrap(); + let codec = build_primary_key_codec(&metadata); + let mut expected = Vec::new(); + for (tag, time, f1, f0) in [ + ("A", 10, 11.0_f64, Some(11.0_f64)), + ("A", 20, 2.0, Some(20.0)), + ("A", 30, 3.0, None), + ("A", 40, 4.0, Some(40.0)), + ("B", 10, 5.0, Some(-0.0_f64)), + ("C", 10, 6.0, Some(60.0)), + ] { + let mut key = Vec::new(); + codec + .encode_values( + &[(metadata.primary_key[0], DatumValue::String(tag.into()))], + &mut key, + ) + .unwrap(); + expected.push((key, tag, time, f1.to_bits(), f0.map(f64::to_bits))); + } + let duplicate_key = expected[0].0.clone(); + assert_eq!( + expected + .iter() + .map(|(key, _, _, _, _)| key.clone()) + .collect::>(), + actual.iter().map(|row| row.0.clone()).collect::>() + ); + let visible = actual + .iter() + .map(|(_, tag, time, f1, f0, _)| (tag.as_str(), *time, *f1, *f0)) + .collect::>(); + assert_eq!( + expected + .iter() + .map(|(_, tag, time, f1, f0)| (*tag, *time, *f1, *f0)) + .collect::>(), + visible + ); + let mut legacy_batches = Vec::new(); + for region in regions { + let mut legacy_request = request.clone(); + legacy_request.projection = Some(vec![0, 1, 2, 3, 4]); + legacy_request.filters.clear(); + legacy_request.preserve_pk_dictionary_encoding = false; + let legacy = engine.handle_query(region, legacy_request).await.unwrap(); + for partition in 0..legacy.properties().num_partitions() { + legacy_batches.extend( + legacy + .scan_partition(&QueryScanContext::default(), &metrics, partition) + .unwrap() + .try_collect::>() + .await + .unwrap(), + ); + } + } + let mut legacy_visible = Vec::new(); + for batch in &legacy_batches { + let batch = batch.df_record_batch(); + let tags = batch + .column_by_name("tag_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let f0 = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let f1 = batch + .column_by_name("field_1") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let times = batch + .column_by_name("ts") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let gate = batch + .column_by_name("field_2") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + if gate.value(row) > 0.0 { + legacy_visible.push(( + tags.value(row).to_string(), + times.value(row), + f1.value(row).to_bits(), + if f0.is_null(row) { + None + } else { + Some(f0.value(row).to_bits()) + }, + )); + } + } + } + legacy_visible.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1))); + let mut raw_visible = actual + .iter() + .map(|(_, tag, time, f1, f0, _)| (tag.clone(), *time, *f1, *f0)) + .collect::>(); + raw_visible.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1))); + assert_eq!( + legacy_visible, raw_visible, + "raw candidates after field_2 predicate must match legacy scan" + ); + test_util::put_rows( + &engine, + regions[1], + Rows { + schema: schema.clone(), + rows: vec![make_row("A", Some(99.0), 99.0, 1.0, 30)], + }, + ) + .await; + let mut duplicate_inputs = Vec::new(); + for region in regions { + let scanner = engine.handle_query(region, request.clone()).await.unwrap(); + let metadata = scanner.metadata(); + let source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: metadata.clone(), + logical_tags: metadata + .column_metadatas + .iter() + .filter(|column| { + column.semantic_type == SemanticType::Tag + && !store_api::storage::consts::is_internal_column( + &column.column_schema.name, + ) + && !store_api::metric_engine_consts::is_metric_engine_internal_column( + &column.column_schema.name, + ) + }) + .map(|column| BoundTag { + column_id: column.column_id, + name: Arc::from(column.column_schema.name.as_str()), + }) + .collect::>() + .into(), + }; + let mut scanner = scanner; + let ranges = scanner + .properties() + .partitions + .clone() + .into_iter() + .flatten() + .collect::>(); + let partition_count = 2; + let mut partitions = vec![Vec::new(); partition_count]; + for (index, range) in ranges.into_iter().enumerate() { + partitions[index % partition_count].push(range); + } + scanner + .prepare(PrepareRequest { + ranges: Some(partitions), + target_partitions: Some(partition_count), + ..Default::default() + }) + .unwrap(); + for partition in 0..scanner.properties().num_partitions() { + duplicate_inputs.push( + scanner + .scan_series_partition( + &QueryScanContext::default(), + &metrics, + partition, + &source, + ) + .unwrap() + .unwrap(), + ); + } + } + let mut duplicate_merge = merge_ordered_raw_series(duplicate_inputs).unwrap(); + let mut affected_key_last = Vec::new(); + let duplicate_error = loop { + match duplicate_merge.try_next().await { + Ok(Some(chunk)) => { + if chunk.primary_key.as_slice() == duplicate_key.as_slice() { + affected_key_last.push(chunk.is_last); + } + } + Ok(None) => panic!("same full key/timestamp across regions must fail"), + Err(error) => break error.to_string(), + } + }; + assert!( + duplicate_error.contains("timestamp") || duplicate_error.contains("time"), + "unexpected duplicate timestamp error: {duplicate_error}" + ); + assert!(!affected_key_last.is_empty()); + assert!(affected_key_last.iter().all(|is_last| !is_last)); + assert!( + duplicate_merge.try_next().await.unwrap().is_none(), + "merge error must fuse stream" + ); + for tag in ["A", "B", "C"] { + let key_rows = actual.iter().filter(|row| row.1 == tag).collect::>(); + assert_eq!( + 1, + key_rows.iter().filter(|row| row.5).count(), + "global finality for {tag}" + ); + assert!(key_rows.last().unwrap().5); + assert!(key_rows[..key_rows.len() - 1].iter().all(|row| !row.5)); + } +} + +#[tokio::test] +async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { + use datatypes::series::SeriesOrdering; + use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; + use store_api::region_request::RegionPutRequest; + + let mut env = TestEnv::with_prefix("test_two_phase_native_raw_merge_rejection").await; + let engine = env + .create_engine(MitoConfig { + experimental_series_scan_v2: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let metadata = Arc::new(sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + )); + let mut create = CreateRequestBuilder::new().build(); + create.column_metadatas = metadata.column_metadatas.clone(); + create.primary_key = metadata.primary_key.clone(); + create + .options + .insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string()); + create + .options + .insert("memtable.type".to_string(), "bulk".to_string()); + create + .options + .insert("sst_format".to_string(), "flat".to_string()); + let full_schema = test_util::rows_schema(&create); + let mut key_schema = full_schema[0].clone(); + key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string(); + key_schema.datatype = ColumnDataType::Binary.into(); + key_schema.semantic_type = SemanticType::Tag.into(); + let row_schema = vec![key_schema, full_schema[5].clone(), full_schema[4].clone()]; + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + let sparse_rows = Rows { + schema: row_schema, + rows: vec![ + row(vec![ + ValueData::BinaryValue(new_sparse_primary_key(&["a", "x"], &metadata, 10, 0)), + ValueData::TimestampMillisecondValue(10), + ValueData::U64Value(1), + ]), + row(vec![ + ValueData::BinaryValue(new_sparse_primary_key(&["b", "y"], &metadata, 20, 0)), + ValueData::TimestampMillisecondValue(20), + ValueData::U64Value(2), + ]), + ], + }; + engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: sparse_rows, + hint: Some(WriteHint { + primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(), + }), + skip_wal: false, + partition_expr_version: None, + }), + ) + .await + .unwrap(); + test_util::flush_region(&engine, region_id, None).await; + let request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let selected = engine.scanner(region_id, request.clone()).await.unwrap(); + let Scanner::Series(series) = selected else { + panic!("sparse PerSeries request must use SeriesScan"); + }; + assert_eq!("two_phase", series.mode()); + let mut scanner = engine.handle_query(region_id, request).await.unwrap(); + assert_eq!(SeriesOrdering::Contiguous, scanner.raw_series_ordering()); + let metadata = scanner.metadata(); + let source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: metadata.clone(), + logical_tags: metadata + .column_metadatas + .iter() + .filter(|column| { + column.semantic_type == SemanticType::Tag + && !store_api::storage::consts::is_internal_column(&column.column_schema.name) + && !store_api::metric_engine_consts::is_metric_engine_internal_column( + &column.column_schema.name, + ) + }) + .map(|column| BoundTag { + column_id: column.column_id, + name: Arc::from(column.column_schema.name.as_str()), + }) + .collect::>() + .into(), + }; + let ranges = scanner.properties().partitions.clone(); + scanner + .prepare(PrepareRequest { + ranges: Some(ranges.clone()), + target_partitions: Some(ranges.len()), + ..Default::default() + }) + .unwrap(); + let metrics = ExecutionPlanMetricsSet::default(); + let mut streams = Vec::new(); + for partition in 0..ranges.len() { + let stream = scanner + .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) + .unwrap() + .unwrap(); + assert_eq!(scanner.raw_series_ordering(), stream.ordering()); + assert_eq!(SeriesOrdering::Contiguous, stream.ordering()); + streams.push(stream); + } + let error = match promql::source::merge_ordered_raw_series(streams) { + Ok(_) => panic!("Contiguous two-phase input cannot satisfy ordered merge ordering"), + Err(error) => error, + }; + assert!( + error.to_string().contains("ordering") || error.to_string().contains("ordered"), + "expected ordering rejection, got: {error}" + ); +} + #[tokio::test] async fn test_mito_raw_series_int64_predicate_uses_original_precision() { use datatypes::series::samples::SampleRef; @@ -5199,7 +5923,7 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() { ); let chunks = stream.try_collect::>().await.unwrap(); for chunk in chunks { - let axis = chunk.time.as_buffer().as_ref(); + let axis = chunk.time.as_buffer(); times.extend(axis.iter().copied()); for (index, &time) in axis.iter().enumerate() { output_values.push(( @@ -5214,6 +5938,112 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() { } assert_eq!(vec![2], times); assert_eq!(vec![(2, 20.0)], output_values); + + // Validate the typed integer gate through RegionScanExec's actual physical consumer. + use common_query::series_frame::unpack_raw_series; + use datafusion::execution::TaskContext; + use datafusion::physical_plan::ExecutionPlan; + use datatypes::series::SeriesOrdering; + use table::table::scan::RegionScanExec; + let native_request = ScanRequest { + projection: Some(vec![2, 3]), + filters: vec![ + col("tag_0").eq(lit("series")), + col("field_0").gt(lit(boundary)), + ], + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let native_scanner = engine + .handle_query(region_id, native_request.clone()) + .await + .unwrap(); + let native_metadata = native_scanner.metadata(); + let native_source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: native_metadata.clone(), + logical_tags: Arc::from([BoundTag { + column_id: native_metadata.primary_key[0], + name: Arc::from("tag_0"), + }]), + }; + let native_plan = Arc::new(RegionScanExec::new(native_scanner, native_request, None).unwrap()) + .try_to_series_scan(native_source.clone()) + .unwrap() + .expect("typed int64 gate is supported"); + let native_schema = native_plan.series_schema().clone(); + let frames = native_plan + .execute(0, Arc::new(TaskContext::default())) + .unwrap(); + let chunks = unpack_raw_series( + frames, + native_schema, + native_source, + SeriesOrdering::Contiguous, + ) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let native_rows = chunks + .iter() + .flat_map(|chunk| { + let times = chunk.time.as_buffer(); + (0..times.len()) + .map(|i| { + let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(i) else { + panic!("expected float output field") + }; + (times[i], value) + }) + .collect::>() + }) + .collect::>(); + assert_eq!(vec![(2, 20.0)], native_rows); + + let empty_request = ScanRequest { + projection: Some(vec![2, 3]), + filters: vec![ + col("tag_0").eq(lit("series")), + col("field_0").gt(lit(boundary + 1)), + ], + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let empty_scanner = engine + .handle_query(region_id, empty_request.clone()) + .await + .unwrap(); + let empty_metadata = empty_scanner.metadata(); + let empty_source = RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: empty_metadata.clone(), + logical_tags: Arc::from([BoundTag { + column_id: empty_metadata.primary_key[0], + name: Arc::from("tag_0"), + }]), + }; + let empty_plan = Arc::new(RegionScanExec::new(empty_scanner, empty_request, None).unwrap()) + .try_to_series_scan(empty_source.clone()) + .unwrap() + .expect("statically empty scan still has native capability"); + let empty_schema = empty_plan.series_schema().clone(); + let empty_frames = empty_plan + .execute(0, Arc::new(TaskContext::default())) + .unwrap(); + let empty_chunks = unpack_raw_series( + empty_frames, + empty_schema, + empty_source, + SeriesOrdering::Contiguous, + ) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!(empty_chunks.is_empty()); } /// Invalid predicate bindings decline before consumption; explicit labels decline and legacy still reads. @@ -5304,6 +6134,11 @@ async fn test_mito_raw_series_invalid_binding_before_legacy_read() { name: Arc::from("tag_0"), }]), }; + assert_eq!( + supported, + scanner.raw_series_schema(&valid_source).unwrap().is_some(), + "schema preflight case: {name}" + ); let raw = scanner .scan_series_partition(&ctx, &metrics, 0, &valid_source) .unwrap(); @@ -5313,7 +6148,7 @@ async fn test_mito_raw_series_invalid_binding_before_legacy_read() { let tuples = chunks .iter() .map(|chunk| { - let times = chunk.time.as_buffer().as_ref(); + let times = chunk.time.as_buffer(); let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(0) else { panic!("expected raw float sample"); }; @@ -5387,6 +6222,13 @@ async fn test_mito_raw_series_invalid_binding_before_legacy_read() { .unwrap() .is_none() ); + assert!( + scanner + .raw_series_schema(&RawLabelSource::Explicit) + .unwrap() + .is_none() + ); + assert!(scanner.raw_series_schema(&valid_shape_bad_tag).is_err()); assert!( scanner .scan_series_partition(&ctx, &metrics, 0, &valid_shape_bad_tag) @@ -5427,4 +6269,70 @@ async fn test_mito_raw_series_invalid_binding_before_legacy_read() { vec![("0".to_string(), 0.0, 0), ("1".to_string(), 1.0, 1000)], rows ); + + // Runtime pruning wrappers are deliberately ineligible for native planning, and + // wrappers installed after planning must be caught at execute time. + use datafusion::execution::TaskContext; + use datafusion::physical_plan::ExecutionPlan; + use table::table::scan::RegionScanExec; + let dynamic_request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let dynamic_source_for = |scanner: &dyn RegionScanner| { + let metadata = scanner.metadata(); + RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: metadata.clone(), + logical_tags: Arc::from([BoundTag { + column_id: metadata.primary_key[0], + name: Arc::from("tag_0"), + }]), + } + }; + let make_dynamic = || { + Arc::new(DynamicFilterPhysicalExpr::new( + vec![Arc::new(Column::new("field_0", 1))], + physical_lit(true), + )) + }; + let before = engine + .handle_query(region_id, dynamic_request.clone()) + .await + .unwrap(); + let before_source = dynamic_source_for(before.as_ref()); + let before_scan = Arc::new(RegionScanExec::new(before, dynamic_request.clone(), None).unwrap()); + assert_eq!( + vec![true], + before_scan.add_dyn_filters_to_predicate(vec![make_dynamic()]) + ); + assert!( + before_scan + .clone() + .try_to_series_scan(before_source) + .unwrap() + .is_none() + ); + + let after = engine + .handle_query(region_id, dynamic_request.clone()) + .await + .unwrap(); + let after_source = dynamic_source_for(after.as_ref()); + let after_scan = Arc::new(RegionScanExec::new(after, dynamic_request, None).unwrap()); + let after_plan = after_scan + .clone() + .try_to_series_scan(after_source) + .unwrap() + .expect("native plan before dynamic wrapper installation"); + assert_eq!( + vec![true], + after_scan.add_dyn_filters_to_predicate(vec![make_dynamic()]) + ); + assert!( + after_plan + .execute(0, Arc::new(TaskContext::default())) + .is_err() + ); } diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index eb5c1048ab5..8b4ad2acf20 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -31,13 +31,15 @@ use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream}; use common_telemetry::tracing::{self, Instrument}; use common_telemetry::{debug, warn}; use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; -use datafusion::physical_plan::{DisplayAs, DisplayFormatType}; +use datafusion::physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr}; use datafusion_common::tree_node::TreeNode; use datafusion_expr::{Expr, Volatility}; use datatypes::arrow::array::BinaryArray; use datatypes::arrow::datatypes::DataType as ArrowDataType; use datatypes::arrow::record_batch::RecordBatch; +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}; @@ -88,6 +90,12 @@ type CandidateReceiverList = Vec>; /// Candidate assignment senders for output partitions. type CandidateSenderList = Vec>>>; +struct RawScanPreparation { + schema: Arc, + fields: Vec<(usize, ConcreteDataType)>, + predicates: Vec>, +} + struct CandidateReceiver { receiver: mpsc::UnboundedReceiver>, active_receivers: Arc, @@ -194,6 +202,189 @@ impl SeriesScan { } } + fn prepare_raw_scan( + &self, + label_source: &RawLabelSource, + ) -> Result, BoxedError> { + let input = &self.stream_ctx.input; + let metadata = input.mapper.metadata(); + match label_source { + RawLabelSource::PrimaryKey { + physical_metadata, + logical_tags, + .. + } => { + if !Arc::ptr_eq(metadata, physical_metadata) { + debug!( + "Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}", + metadata.region_id, + physical_metadata.region_id, + metadata.schema_version, + physical_metadata.schema_version, + ); + return Err(BoxedError::new( + InvalidRecordBatchSnafu { + reason: "raw label source metadata does not match scanner snapshot" + .to_string(), + } + .build(), + )); + } + let mut ids = HashSet::new(); + let mut names = HashSet::new(); + for tag in logical_tags.iter() { + let column = metadata.column_by_id(tag.column_id).filter(|column| { + column.semantic_type == SemanticType::Tag + && metadata.primary_key.contains(&tag.column_id) + }); + let valid = column.is_some_and(|column| { + column.column_schema.name == tag.name.as_ref() + && tag.name.as_ref() != "__name__" + && !is_internal_column(tag.name.as_ref()) + && !is_metric_engine_internal_column(tag.name.as_ref()) + && !ReservedColumnId::is_reserved(tag.column_id) + }); + let unique_id = valid && ids.insert(tag.column_id); + let unique_name = unique_id && names.insert(tag.name.as_ref()); + if !valid || !unique_id || !unique_name { + debug!( + "Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}", + metadata.region_id, tag.column_id, valid, unique_id, unique_name, + ); + return Err(BoxedError::new( + InvalidRecordBatchSnafu { + reason: "invalid raw label binding".to_string(), + } + .build(), + )); + } + } + } + RawLabelSource::Explicit => { + debug!( + "Raw series scan preflight rejected explicit labels: region_id={}", + metadata.region_id, + ); + return Ok(None); + } + } + let selected = input.mapper.output_schema(); + let mut fields = Vec::new(); + let mut specs = Vec::new(); + for output in selected.column_schemas() { + let Some(column) = metadata.column_metadatas.iter().find(|column| { + column.column_schema.name == output.name + && column.semantic_type == SemanticType::Field + }) else { + continue; + }; + let Some((index, (_, data_type))) = input + .mapper + .batch_schema() + .iter() + .enumerate() + .find(|(_, (id, _))| *id == column.column_id) + else { + debug!( + "Raw series scan preflight missing mapper field: region_id={}, column_id={}", + metadata.region_id, column.column_id, + ); + return Err(BoxedError::new( + InvalidRecordBatchSnafu { + reason: format!( + "selected field {} is missing from mapper batch schema", + output.name + ), + } + .build(), + )); + }; + if !data_type.is_numeric() && !is_native_histogram_value_type(data_type) { + debug!( + "Raw series scan preflight rejected field type: region_id={}, column_id={}", + metadata.region_id, column.column_id, + ); + return Ok(None); + } + fields.push((index, data_type.clone())); + specs.push(FieldSpec { + 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 + || 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={}", + metadata.region_id, + fields.len(), + input.append_mode, + input.series_row_selector.is_some(), + time_is_millis, + ); + return Ok(None); + } + let schema = Arc::new(SeriesSchema { + fields: specs.into(), + eval_grid: None, + }); + let typed_schema = input.mapper.input_arrow_schema(false); + let mut predicates = Vec::new(); + if let Some(predicate) = input.predicate_group().predicate_without_region() { + if !predicate.dyn_filters().is_empty() { + debug!( + "Raw series scan preflight rejected dynamic predicate filters: region_id={}", + metadata.region_id, + ); + return Ok(None); + } + for expr in predicate.exprs() { + // Fresh execution properties cannot preserve Stable or query-dependent semantics. + if expr + .exists(|node| { + Ok(matches!(node, Expr::ScalarFunction(function) + if function.func.signature().volatility != Volatility::Immutable) + || matches!(node, Expr::ScalarVariable(..))) + }) + .unwrap_or(true) + { + debug!( + "Raw series scan preflight rejected predicate volatility or variable: region_id={}", + metadata.region_id, + ); + return Ok(None); + } + // Evaluate residuals with original types before raw conversion to Float64. + let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else { + debug!( + "Raw series scan preflight failed predicate compilation: region_id={}", + metadata.region_id, + ); + return Ok(None); + }; + if !matches!( + physical.data_type(&typed_schema), + Ok(ArrowDataType::Boolean | ArrowDataType::Null) + ) { + debug!( + "Raw series scan preflight rejected predicate type: region_id={}", + metadata.region_id, + ); + return Ok(None); + } + predicates.push(physical); + } + } + Ok(Some(RawScanPreparation { + schema, + fields, + predicates, + })) + } + fn supports_two_phase(input: &ScanInput) -> bool { if !is_sparse_metric_metadata(input.region_metadata()) { return false; @@ -578,6 +769,22 @@ impl RegionScanner for SeriesScan { .map_err(BoxedError::new) } + fn raw_series_ordering(&self) -> SeriesOrdering { + match self.mode { + SeriesScanMode::Legacy => SeriesOrdering::KeyThenTime, + SeriesScanMode::TwoPhase => SeriesOrdering::Contiguous, + } + } + + fn raw_series_schema( + &self, + label_source: &RawLabelSource, + ) -> Result>, BoxedError> { + Ok(self + .prepare_raw_scan(label_source)? + .map(|preparation| preparation.schema)) + } + fn scan_series_partition( &self, ctx: &QueryScanContext, @@ -585,171 +792,9 @@ impl RegionScanner for SeriesScan { partition: usize, label_source: &RawLabelSource, ) -> Result, BoxedError> { - let input = &self.stream_ctx.input; - let metadata = input.mapper.metadata(); - match label_source { - RawLabelSource::PrimaryKey { - physical_metadata, - logical_tags, - .. - } => { - if !Arc::ptr_eq(metadata, physical_metadata) { - debug!( - "Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}", - metadata.region_id, - physical_metadata.region_id, - metadata.schema_version, - physical_metadata.schema_version, - ); - return Err(BoxedError::new( - InvalidRecordBatchSnafu { - reason: "raw label source metadata does not match scanner snapshot" - .to_string(), - } - .build(), - )); - } - let mut ids = HashSet::new(); - let mut names = HashSet::new(); - for tag in logical_tags.iter() { - let column = metadata.column_by_id(tag.column_id).filter(|column| { - column.semantic_type == SemanticType::Tag - && metadata.primary_key.contains(&tag.column_id) - }); - let valid = column.is_some_and(|column| { - column.column_schema.name == tag.name.as_ref() - && tag.name.as_ref() != "__name__" - && !is_internal_column(tag.name.as_ref()) - && !is_metric_engine_internal_column(tag.name.as_ref()) - && !ReservedColumnId::is_reserved(tag.column_id) - }); - let unique_id = valid && ids.insert(tag.column_id); - let unique_name = unique_id && names.insert(tag.name.as_ref()); - if !valid || !unique_id || !unique_name { - debug!( - "Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}", - metadata.region_id, tag.column_id, valid, unique_id, unique_name, - ); - return Err(BoxedError::new( - InvalidRecordBatchSnafu { - reason: "invalid raw label binding".to_string(), - } - .build(), - )); - } - } - } - RawLabelSource::Explicit => { - debug!( - "Raw series scan preflight rejected explicit labels: region_id={}", - metadata.region_id, - ); - return Ok(None); - } - } - let selected = input.mapper.output_schema(); - let mut fields = Vec::new(); - let mut specs = Vec::new(); - for output in selected.column_schemas() { - let Some(column) = metadata.column_metadatas.iter().find(|column| { - column.column_schema.name == output.name - && column.semantic_type == SemanticType::Field - }) else { - continue; - }; - let Some((index, (_, data_type))) = input - .mapper - .batch_schema() - .iter() - .enumerate() - .find(|(_, (id, _))| *id == column.column_id) - else { - debug!( - "Raw series scan preflight missing mapper field: region_id={}, column_id={}", - metadata.region_id, column.column_id, - ); - return Err(BoxedError::new( - InvalidRecordBatchSnafu { - reason: format!( - "selected field {} is missing from mapper batch schema", - output.name - ), - } - .build(), - )); - }; - if !data_type.is_numeric() && !is_native_histogram_value_type(data_type) { - debug!( - "Raw series scan preflight rejected field type: region_id={}, column_id={}", - metadata.region_id, column.column_id, - ); - return Ok(None); - } - fields.push((index, data_type.clone())); - specs.push(FieldSpec { - 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 - || 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={}", - metadata.region_id, - fields.len(), - input.append_mode, - input.series_row_selector.is_some(), - time_is_millis, - ); + let Some(preparation) = self.prepare_raw_scan(label_source)? else { return Ok(None); - } - let schema = Arc::new(SeriesSchema { - fields: specs.into(), - eval_grid: None, - }); - let typed_schema = input.mapper.input_arrow_schema(false); - let mut predicates = Vec::new(); - if let Some(predicate) = input.predicate_group().predicate_without_region() { - for expr in predicate.exprs() { - // Fresh execution properties cannot preserve Stable or query-dependent semantics. - if expr - .exists(|node| { - Ok(matches!(node, Expr::ScalarFunction(function) - if function.func.signature().volatility != Volatility::Immutable) - || matches!(node, Expr::ScalarVariable(..))) - }) - .unwrap_or(true) - { - debug!( - "Raw series scan preflight rejected predicate volatility or variable: region_id={}", - metadata.region_id, - ); - return Ok(None); - } - // Evaluate residuals with original types before raw conversion to Float64. - let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else { - debug!( - "Raw series scan preflight failed predicate compilation: region_id={}", - metadata.region_id, - ); - return Ok(None); - }; - if !matches!( - physical.data_type(&typed_schema), - Ok(ArrowDataType::Boolean | ArrowDataType::Null) - ) { - debug!( - "Raw series scan preflight rejected predicate type: region_id={}", - metadata.region_id, - ); - return Ok(None); - } - predicates.push(physical); - } - } + }; let metrics = new_partition_metrics( &self.stream_ctx, ctx.explain_verbose, @@ -760,13 +805,15 @@ impl RegionScanner for SeriesScan { let batches = self .scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set) .map_err(BoxedError::new)?; + let ordering = self.raw_series_ordering(); Ok(Some(raw::make_stream( batches, - schema, + preparation.schema, label_source.clone(), - fields, + preparation.fields, metrics, - predicates, + preparation.predicates, + ordering, ))) } diff --git a/src/mito2/src/read/series_scan/raw.rs b/src/mito2/src/read/series_scan/raw.rs index 6ed41bf8c14..4adac4263ae 100644 --- a/src/mito2/src/read/series_scan/raw.rs +++ b/src/mito2/src/read/series_scan/raw.rs @@ -128,6 +128,7 @@ fn chunk( struct RawStream { schema: Arc, label_source: RawLabelSource, + ordering: SeriesOrdering, inner: BoxStream<'static, Result>, } @@ -146,7 +147,7 @@ impl RawSeriesStream for RawStream { &self.label_source } fn ordering(&self) -> SeriesOrdering { - SeriesOrdering::Contiguous + self.ordering } } @@ -157,15 +158,16 @@ pub(crate) fn make_stream( fields: Vec<(usize, ConcreteDataType)>, metrics: PartitionMetrics, predicates: Vec>, + ordering: SeriesOrdering, ) -> SendableRawSeriesStream { let output_schema = schema.clone(); let stream = async_stream::stream! { let mut input = inner; let mut pending: Option = None; while let Some(item) = input.next().await { - let (records, is_legacy) = match item { - Ok(ScanBatch::Series(SeriesBatch::Flat(flat))) => (flat.batches.into_vec(), true), - Ok(ScanBatch::RecordBatch(batch)) => (vec![batch], false), + let records = match item { + Ok(ScanBatch::Series(SeriesBatch::Flat(flat))) => flat.batches.into_vec(), + Ok(ScanBatch::RecordBatch(batch)) => vec![batch], Err(error) => { yield Err(BoxedError::new(error)); return; } }; for record in records { @@ -238,7 +240,7 @@ pub(crate) fn make_stream( }; metrics.inc_convert_batch_cost(begun.elapsed()); if let Some(old) = pending.as_ref() - && is_legacy + && ordering == SeriesOrdering::KeyThenTime && old.primary_key.as_slice() != current.primary_key.as_slice() && current.primary_key.as_slice() <= old.primary_key.as_slice() { @@ -265,6 +267,7 @@ pub(crate) fn make_stream( Box::pin(RawStream { schema, label_source, + ordering, inner: Box::pin(stream), }) } diff --git a/src/mito2/src/read/series_scan/raw/tests.rs b/src/mito2/src/read/series_scan/raw/tests.rs index 22dd3eefa15..1fdd703b00d 100644 --- a/src/mito2/src/read/series_scan/raw/tests.rs +++ b/src/mito2/src/read/series_scan/raw/tests.rs @@ -37,6 +37,7 @@ use datatypes::arrow::record_batch::RecordBatch; use datatypes::data_type::DataType as _; use datatypes::prelude::ConcreteDataType; use datatypes::schema::ColumnSchema; +use datatypes::series::SeriesOrdering; use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{FieldSpec, SampleRef, SeriesSchema}; use futures::{Stream, StreamExt, stream}; @@ -239,6 +240,7 @@ fn convert_with_source( schema: Arc, source: RawLabelSource, field_type: ConcreteDataType, + ordering: SeriesOrdering, ) -> SendableRawSeriesStream { make_stream( inner, @@ -247,6 +249,7 @@ fn convert_with_source( vec![(0, field_type)], metrics(), vec![], + ordering, ) } @@ -267,6 +270,17 @@ fn convert(inner: ScanBatchStream, schema: Arc) -> SendableRawSeri schema, primary_key_source(metadata()), ConcreteDataType::int64_datatype(), + SeriesOrdering::Contiguous, + ) +} + +fn convert_ordered(inner: ScanBatchStream, schema: Arc) -> SendableRawSeriesStream { + convert_with_source( + inner, + schema, + primary_key_source(metadata()), + ConcreteDataType::int64_datatype(), + SeriesOrdering::KeyThenTime, ) } @@ -370,6 +384,59 @@ async fn chunks_preserve_keys_values_times_and_final_flags_for_both_input_shapes } } +#[tokio::test] +async fn raw_stream_reports_and_enforces_declared_ordering() { + let stream = convert(input(vec![]), schema()); + assert_eq!(stream.ordering(), SeriesOrdering::Contiguous); + drop(stream); + let stream = convert_ordered(input(vec![]), schema()); + assert_eq!(stream.ordering(), SeriesOrdering::KeyThenTime); + drop(stream); + + let mut output = convert_ordered( + input(vec![ + Ok(ScanBatch::RecordBatch(dictionary_batch( + &[b"z"], + &[1], + &[Some(1)], + ))), + Ok(ScanBatch::RecordBatch(dictionary_batch( + &[b"a"], + &[1], + &[Some(2)], + ))), + ]), + schema(), + ); + assert!(output.next().await.unwrap().is_err()); + assert!(output.next().await.is_none()); + + let mut output = convert( + input(vec![ + Ok(ScanBatch::RecordBatch(dictionary_batch( + &[b"z"], + &[1], + &[Some(1)], + ))), + Ok(ScanBatch::RecordBatch(dictionary_batch( + &[b"a"], + &[1], + &[Some(2)], + ))), + ]), + schema(), + ); + assert_eq!( + output.next().await.unwrap().unwrap().primary_key.as_slice(), + b"z" + ); + assert_eq!( + output.next().await.unwrap().unwrap().primary_key.as_slice(), + b"a" + ); + assert!(output.next().await.is_none()); +} + #[tokio::test] async fn typed_predicate_filters_before_numeric_samples_are_cast() { let threshold = 1_i64 << 53; @@ -395,6 +462,7 @@ async fn typed_predicate_filters_before_numeric_samples_are_cast() { vec![(0, ConcreteDataType::int64_datatype())], metrics(), vec![predicate], + SeriesOrdering::Contiguous, ); let chunk = output.next().await.unwrap().unwrap(); assert!(chunk.is_last); @@ -424,6 +492,7 @@ async fn predicate_error_is_terminal() { vec![(0, ConcreteDataType::int64_datatype())], metrics(), vec![predicate], + SeriesOrdering::Contiguous, ); assert!(output.next().await.unwrap().is_err()); assert!(output.next().await.is_none()); @@ -515,7 +584,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() { let mut batches = smallvec::SmallVec::new(); batches.push(dictionary_batch(&[b"b"], &[1], &[Some(1)])); batches.push(dictionary_batch(&[b"a"], &[2], &[Some(2)])); - let mut output = convert( + let mut output = convert_ordered( input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat( FlatSeriesBatch { batches }, )))]), @@ -528,7 +597,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() { batches.push(dictionary_batch(&[b"a"], &[1], &[Some(1)])); batches.push(dictionary_batch(&[b"b"], &[1], &[Some(2)])); batches.push(dictionary_batch(&[b"a"], &[2], &[Some(3)])); - let mut output = convert( + let mut output = convert_ordered( input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat( FlatSeriesBatch { batches }, )))]), @@ -545,7 +614,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() { let mut batches = smallvec::SmallVec::new(); batches.push(dictionary_batch(&[b"a"], &[1], &[Some(1)])); batches.push(dictionary_batch(&[b"b"], &[1], &[Some(2)])); - let mut output = convert( + let mut output = convert_ordered( input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat( FlatSeriesBatch { batches }, )))]), @@ -636,6 +705,7 @@ async fn native_histogram_adapter_preserves_complete_payload() { native_histogram_value_type().clone(), )), native_histogram_value_type().clone(), + SeriesOrdering::Contiguous, ); assert!(matches!( raw.label_source(), From 8e90db600d10ee226b42d66c64856766ddb259d2 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 20:27:44 +0800 Subject: [PATCH 02/10] test(mito2): cover raw partition bounds and contiguity across assignments The raw-series path had two untested behaviours. An out-of-range partition must fail without consuming the scanner's partition state: the range check runs before the receiver is taken, so a later in-bounds scan on the same scanner still reads its complete data, and a repeat scan of that partition then reports the one-shot violation. A two-phase stream must stay contiguous in the sense the raw contract advertises, including across candidate assignments: chunks are checked per partition for a non-empty, disjoint key set, the whole stream is routed through the frame codec so its own sequence validator runs, and a series may appear in only one run so a non-adjacent recurrence would fail. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/mito2/src/engine/scan_test.rs | 501 ++++++++++++++++++++++++++++++ 1 file changed, 501 insertions(+) diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 3ad13fac11e..6fe07d63ecd 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -5826,6 +5826,507 @@ async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { ); } +#[tokio::test] +async fn test_two_phase_raw_partition_out_of_range_keeps_scanner_usable() { + use datatypes::series::samples::SampleRef; + use store_api::region_engine::QueryScanContext; + + let mut env = TestEnv::with_prefix("test_two_phase_raw_partition_out_of_range").await; + let engine = env + .create_engine(MitoConfig { + experimental_series_scan_v2: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await; + let expected = [ + (new_sparse_primary_key(&["a", "x"], &metadata, 10, 0), 10, 1), + (new_sparse_primary_key(&["b", "x"], &metadata, 10, 0), 20, 2), + ]; + put_sparse_rows( + &engine, + region_id, + &row_schema, + expected + .iter() + .map(|(key, time, value)| (key.clone(), *time, *value)) + .collect(), + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + + let request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let Scanner::Series(selected) = engine.scanner(region_id, request.clone()).await.unwrap() + else { + panic!("sparse PerSeries request must use SeriesScan"); + }; + assert_eq!("two_phase", selected.mode()); + let mut scanner = engine.handle_query(region_id, request).await.unwrap(); + let source = primary_key_label_source(&scanner.metadata()); + let ranges = scanner.properties().partitions.clone(); + scanner + .prepare(PrepareRequest { + ranges: Some(ranges.clone()), + target_partitions: Some(ranges.len()), + ..Default::default() + }) + .unwrap(); + let partitions = scanner.properties().num_partitions(); + assert!(partitions > 0, "prepared scan needs an output partition"); + let metrics = ExecutionPlanMetricsSet::default(); + let ctx = QueryScanContext::default(); + + // `scan_batch_in_partition` validates the index before it takes that partition's receiver, so + // the first index past the last partition must fail without disturbing scanner state. + let error = match scanner.scan_series_partition(&ctx, &metrics, partitions, &source) { + Ok(_) => { + panic!("partition {partitions} must be rejected by a {partitions}-partitions scan") + } + Err(error) => error, + }; + let message = error.to_string(); + assert!( + message.contains("out of range") && message.contains(&partitions.to_string()), + "expected a partition range error, got: {message}" + ); + + // The in-range partition must still read the complete data set. + let stream = scanner + .scan_series_partition(&ctx, &metrics, 0, &source) + .unwrap() + .expect("the raw series scan stays available after a rejected partition"); + let mut actual = HashMap::new(); + for chunk in stream.try_collect::>().await.unwrap() { + let times = chunk.time.as_buffer(); + for (index, time) in times.iter().enumerate() { + let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(index) else { + panic!("raw fields are converted to float samples"); + }; + actual.insert((chunk.primary_key.to_vec(), *time), value); + } + } + assert_eq!( + expected.len(), + actual.len(), + "the rejected call must not consume rows" + ); + for (key, time, value) in expected { + assert_eq!(Some(&(value as f64)), actual.get(&(key, time))); + } + + // A partition can only be scanned once, so this proves the rejected index never took the + // in-range partition's receiver: the error above is raised by the range check alone. + let repeated = match scanner.scan_series_partition(&ctx, &metrics, 0, &source) { + Ok(_) => panic!("partition 0 was already scanned"), + Err(error) => error.to_string(), + }; + assert!( + repeated.contains("scan multiple times"), + "expected a repeated-scan error, got: {repeated}" + ); +} + +#[tokio::test] +async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { + use common_query::series_frame::{pack_raw_series, unpack_raw_series}; + use datatypes::series::SeriesOrdering; + use datatypes::series::raw::RawSeriesChunk; + use datatypes::series::samples::{SampleRef, SeriesSchema}; + use store_api::region_engine::QueryScanContext; + + let mut env = TestEnv::with_prefix("test_two_phase_raw_contiguous_assignments").await; + let engine = env + .create_engine(MitoConfig { + experimental_series_scan_v2: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await; + + // A sparse primary key carries the TSID, and `SeriesRange::partition_for` splits the u64 TSID + // domain over the output partitions, so the fixture splits into two disjoint groups of series: + // tsids below 2^63 own partition 0 and tsids at or above 2^63 own partition 1. + let series = [ + ("a0", 0_u64), + ("a1", 1), + ("b0", 1_u64 << 63), + ("b1", (1_u64 << 63) + 1), + ]; + let keys = series + .iter() + .map(|(tag, tsid)| new_sparse_primary_key(&[tag, "x"], &metadata, 10, *tsid)) + .collect::>(); + + // Three write rounds put every series into two SST ranges plus one memtable range, and the + // large rounds make a series span more than one read batch, so one series is emitted as + // multiple chunks instead of exactly one. + const LARGE: i64 = 20_000; + const SMALL: i64 = 3; + let rounds: [&[(usize, i64, i64)]; 3] = [ + &[(0, 0, LARGE), (1, 0, SMALL), (2, 0, SMALL), (3, 0, LARGE)], + &[ + (0, LARGE, 5), + (1, SMALL, SMALL), + (2, SMALL, SMALL), + (3, LARGE, 5), + ], + &[ + (0, LARGE + 5, 2), + (1, 2 * SMALL, 2), + (2, 2 * SMALL, 2), + (3, LARGE + 5, 2), + ], + ]; + let mut expected_times = HashMap::, Vec>::new(); + for spec in rounds { + for &(index, first, count) in spec { + expected_times + .entry(keys[index].clone()) + .or_default() + .extend(first..first + count); + } + } + for (round, spec) in rounds.iter().enumerate() { + let rows = spec + .iter() + .flat_map(|&(index, first, count)| { + let key = keys[index].clone(); + (0..count).map(move |offset| { + let time = first + offset; + (key.clone(), time, (time + 1) as u64) + }) + }) + .collect::>(); + put_sparse_rows(&engine, region_id, &row_schema, rows).await; + if round + 1 < rounds.len() { + test_util::flush_region(&engine, region_id, None).await; + } + } + + let request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let mut scanner = engine.handle_query(region_id, request).await.unwrap(); + assert_eq!(SeriesOrdering::Contiguous, scanner.raw_series_ordering()); + let source = primary_key_label_source(&scanner.metadata()); + let ranges = scanner + .properties() + .partitions + .clone() + .into_iter() + .flatten() + .collect::>(); + assert!(!ranges.is_empty(), "region scan needs an input range"); + // Two output partitions make the candidate distributor create one reader assignment per + // partition, so the scan runs more than one assignment. + let partition_count = 2; + let mut partitions = vec![Vec::new(); partition_count]; + for (index, range) in ranges.into_iter().enumerate() { + partitions[index % partition_count].push(range); + } + scanner + .prepare(PrepareRequest { + ranges: Some(partitions), + target_partitions: Some(partition_count), + ..Default::default() + }) + .unwrap(); + assert_eq!(partition_count, scanner.properties().num_partitions()); + + let metrics = ExecutionPlanMetricsSet::default(); + let ctx = QueryScanContext::default(); + let mut per_partition = Vec::with_capacity(partition_count); + let mut schema: Option> = None; + for partition in 0..partition_count { + let stream = scanner + .scan_series_partition(&ctx, &metrics, partition, &source) + .unwrap() + .expect("two-phase raw scan is supported"); + assert_eq!(SeriesOrdering::Contiguous, stream.ordering()); + assert_eq!( + vec!["field_0"], + stream + .schema() + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>() + ); + schema.get_or_insert_with(|| Arc::clone(stream.schema())); + let chunks = stream.try_collect::>().await.unwrap(); + assert!( + !chunks.is_empty(), + "partition {partition} must own a reader assignment" + ); + // Each partition owns exactly the series the TSID split assigned to it, so the two + // assignment streams are non-empty and disjoint. + let mut observed = chunks + .iter() + .map(|chunk| chunk.primary_key.to_vec()) + .collect::>(); + observed.sort(); + observed.dedup(); + let mut assigned = vec![keys[2 * partition].clone(), keys[2 * partition + 1].clone()]; + assigned.sort(); + assert_eq!( + assigned, observed, + "partition {partition} must own exactly its assigned series" + ); + per_partition.push(chunks); + } + + // The complete raw series stream of the multi-assignment scan: every assignment's chunks in + // partition order. + let complete = per_partition + .into_iter() + .flatten() + .collect::>(); + let schema = schema.unwrap(); + let complete_rows = complete.iter().map(|chunk| chunk.time.len()).sum::(); + assert_eq!( + expected_times.values().map(Vec::len).sum::(), + complete_rows, + "the complete stream must carry every written row" + ); + + // Reuse the frame adapter's cross-chunk validator (private to + // `common_query::series_frame`) by packing and unpacking the complete stream. It rejects a key + // change that was not preceded by that key's final chunk, a key that recurs right after its + // final chunk, timestamps that do not increase across chunks, and a stream whose last chunk is + // not final. + let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new( + Arc::clone(&schema), + source.clone(), + SeriesOrdering::Contiguous, + complete.clone(), + ))) + .unwrap(); + let unpacked = unpack_raw_series( + packed, + Arc::clone(&schema), + source, + SeriesOrdering::Contiguous, + ) + .unwrap(); + let validated = unpacked.try_collect::>().await.unwrap(); + assert_eq!( + complete_rows, + validated + .iter() + .map(|chunk| chunk.time.len()) + .sum::(), + "packing and unpacking must preserve the complete stream" + ); + + // `SequenceValidator` checks adjacent chunks only, so also reject non-adjacent recurrence: a + // series interrupted by another series and resumed later would break `Contiguous`. + let mut runs = Vec::>::new(); + let mut chunks_per_series = HashMap::, usize>::new(); + for chunk in &complete { + let key = chunk.primary_key.to_vec(); + *chunks_per_series.entry(key.clone()).or_default() += 1; + if runs.last() != Some(&key) { + assert!( + !runs.contains(&key), + "a series' chunks must stay contiguous across assignments" + ); + runs.push(key); + } + } + assert_eq!(keys.len(), runs.len(), "every series appears exactly once"); + assert!( + chunks_per_series.values().copied().max().unwrap() > 1, + "the fixture must emit multiple chunks for one series, got {chunks_per_series:?}" + ); + assert_eq!(keys.len(), chunks_per_series.len()); + for (key, times) in &expected_times { + let observed = complete + .iter() + .filter(|chunk| chunk.primary_key.as_slice() == key.as_slice()) + .flat_map(|chunk| chunk.time.as_buffer().iter().copied()) + .collect::>(); + assert_eq!( + times, &observed, + "sample positions must increase per series" + ); + } + for (index, chunk) in complete.iter().enumerate() { + let next_is_same_series = complete + .get(index + 1) + .is_some_and(|next| next.primary_key.as_slice() == chunk.primary_key.as_slice()); + assert_eq!( + !next_is_same_series, chunk.is_last, + "is_last must mark the final chunk of a series" + ); + let times = chunk.time.as_buffer(); + for (sample, time) in times.iter().enumerate() { + let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(sample) else { + panic!("raw fields are converted to float samples"); + }; + assert_eq!((*time + 1) as f64, value); + } + } +} + +/// Creates the sparse-encoded flat region shared by the two-phase raw scan tests. +/// +/// Returns the region metadata and the row schema accepted by the sparse write path. +async fn create_two_phase_sparse_region( + engine: &crate::engine::MitoEngine, + region_id: RegionId, +) -> ( + Arc, + Vec, +) { + let metadata = Arc::new(sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + )); + let mut create = CreateRequestBuilder::new().build(); + create.column_metadatas = metadata.column_metadatas.clone(); + create.primary_key = metadata.primary_key.clone(); + create + .options + .insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string()); + create + .options + .insert("memtable.type".to_string(), "bulk".to_string()); + create + .options + .insert("sst_format".to_string(), "flat".to_string()); + let full_schema = test_util::rows_schema(&create); + let mut key_schema = full_schema[0].clone(); + key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string(); + key_schema.datatype = ColumnDataType::Binary.into(); + key_schema.semantic_type = SemanticType::Tag.into(); + let row_schema = vec![key_schema, full_schema[5].clone(), full_schema[4].clone()]; + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + (metadata, row_schema) +} + +/// Writes `(primary key, timestamp, field_0)` rows through the sparse write path. +async fn put_sparse_rows( + engine: &crate::engine::MitoEngine, + region_id: RegionId, + schema: &[api::v1::ColumnSchema], + rows: Vec<(Vec, i64, u64)>, +) { + let rows = rows + .into_iter() + .map(|(key, time, value)| { + row(vec![ + ValueData::BinaryValue(key), + ValueData::TimestampMillisecondValue(time), + ValueData::U64Value(value), + ]) + }) + .collect(); + engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema: schema.to_vec(), + rows, + }, + hint: Some(WriteHint { + primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(), + }), + skip_wal: false, + partition_expr_version: None, + }), + ) + .await + .unwrap(); +} + +/// Binds every non-internal tag column of `metadata` as the raw label source. +fn primary_key_label_source( + metadata: &store_api::metadata::RegionMetadataRef, +) -> store_api::region_engine::RawLabelSource { + use store_api::region_engine::{BoundTag, RawLabelSource}; + + RawLabelSource::PrimaryKey { + metric_name: Arc::from("fixture_metric"), + physical_metadata: Arc::clone(metadata), + logical_tags: metadata + .column_metadatas + .iter() + .filter(|column| { + column.semantic_type == SemanticType::Tag + && !store_api::storage::consts::is_internal_column(&column.column_schema.name) + && !store_api::metric_engine_consts::is_metric_engine_internal_column( + &column.column_schema.name, + ) + }) + .map(|column| BoundTag { + column_id: column.column_id, + name: Arc::from(column.column_schema.name.as_str()), + }) + .collect::>() + .into(), + } +} + +/// Concatenates the raw chunks of every reader assignment of one scan, in partition order. +struct ChainedRawSeriesStream { + schema: Arc, + label_source: store_api::region_engine::RawLabelSource, + ordering: datatypes::series::SeriesOrdering, + chunks: std::vec::IntoIter, +} + +impl ChainedRawSeriesStream { + fn new( + schema: Arc, + label_source: store_api::region_engine::RawLabelSource, + ordering: datatypes::series::SeriesOrdering, + chunks: Vec, + ) -> Self { + Self { + schema, + label_source, + ordering, + chunks: chunks.into_iter(), + } + } +} + +impl futures::Stream for ChainedRawSeriesStream { + type Item = Result; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(self.chunks.next().map(Ok)) + } +} + +impl store_api::region_engine::RawSeriesStream for ChainedRawSeriesStream { + fn schema(&self) -> &Arc { + &self.schema + } + + fn label_source(&self) -> &store_api::region_engine::RawLabelSource { + &self.label_source + } + + fn ordering(&self) -> datatypes::series::SeriesOrdering { + self.ordering + } +} + #[tokio::test] async fn test_mito_raw_series_int64_predicate_uses_original_precision() { use datatypes::series::samples::SampleRef; From 38f728ee3fa97e4405a1a4466022f7e63fe04b43 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:42:34 +0800 Subject: [PATCH 03/10] test(mito2): cover a second assignment reaching the same partition The cross-assignment test wrote four candidate series, gave each of two output partitions one assignment, and concatenated the two streams. It proved that two disjoint non-empty assignments stay contiguous once joined, but production only sends a second round to the *same* receiver when one collection round holds `CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD` (1,000,000) candidates, so that boundary was never crossed. The new test lowers the threshold through a `#[cfg(test)]` override instead of writing a million series, then writes 501 series -- one candidate batch plus a trailing remainder -- into a single output partition and asserts on that partition's one stream: two or more assignment rounds were sent, every series appears exactly once in key order with no recurrence, timestamps increase within a key, `is_last` is correct at the boundary, and every value matches. The stream then goes through `pack_raw_series`/`unpack_raw_series` so `SequenceValidator` runs on it as well. Dropping a later round leaves a validator-clean stream, so the data assertions are what catch it. The layout assertions now check the composition rather than non-emptiness: the scan input reports two SST sources whose row counts are the two flushed write rounds and one memtable whose rows are the unflushed round. Compaction is disabled in both tests so a background merge cannot move that composition. The older test is renamed to say what it covers: two disjoint partitions, one assignment each, concatenated. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/mito2/src/engine/scan_test.rs | 369 +++++++++++++++++++++++++++++- src/mito2/src/read/series_scan.rs | 48 +++- 2 files changed, 408 insertions(+), 9 deletions(-) diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 6fe07d63ecd..4a720ef73f2 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -5932,7 +5932,7 @@ async fn test_two_phase_raw_partition_out_of_range_keeps_scanner_usable() { } #[tokio::test] -async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { +async fn test_two_phase_raw_stream_stays_contiguous_across_disjoint_partition_assignments() { use common_query::series_frame::{pack_raw_series, unpack_raw_series}; use datatypes::series::SeriesOrdering; use datatypes::series::raw::RawSeriesChunk; @@ -5943,6 +5943,10 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { let engine = env .create_engine(MitoConfig { experimental_series_scan_v2: true, + // Automatic compaction could merge the two flushed SSTs before the scan pins its + // input and make the source-composition assertions below racy. + schedule_compaction_after_edit: false, + min_compaction_interval: Duration::from_secs(60 * 60), ..Default::default() }) .await; @@ -5963,9 +5967,11 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { .map(|(tag, tsid)| new_sparse_primary_key(&[tag, "x"], &metadata, 10, *tsid)) .collect::>(); - // Three write rounds put every series into two SST ranges plus one memtable range, and the - // large rounds make a series span more than one read batch, so one series is emitted as - // multiple chunks instead of exactly one. + // Three write rounds put every series into two SST sources (the first two rounds are flushed) + // plus one memtable source (the last round stays in memory), and the large rounds make a + // series span more than one read batch, so one series is emitted as multiple chunks instead + // of exactly one. The scan input assertions below check that composition instead of only + // checking that something was read. const LARGE: i64 = 20_000; const SMALL: i64 = 3; let rounds: [&[(usize, i64, i64)]; 3] = [ @@ -5992,6 +5998,7 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { .extend(first..first + count); } } + let mut round_rows = Vec::with_capacity(rounds.len()); for (round, spec) in rounds.iter().enumerate() { let rows = spec .iter() @@ -6003,6 +6010,7 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { }) }) .collect::>(); + round_rows.push(rows.len()); put_sparse_rows(&engine, region_id, &row_schema, rows).await; if round + 1 < rounds.len() { test_util::flush_region(&engine, region_id, None).await; @@ -6014,8 +6022,50 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { preserve_pk_dictionary_encoding: true, ..Default::default() }; - let mut scanner = engine.handle_query(region_id, request).await.unwrap(); + let selected = engine.scanner(region_id, request).await.unwrap(); + let Scanner::Series(mut scanner) = selected else { + panic!("sparse PerSeries request must use SeriesScan"); + }; + assert_eq!("two_phase", scanner.mode()); assert_eq!(SeriesOrdering::Contiguous, scanner.raw_series_ordering()); + // Composition of the pinned scan input: the two flushes pin two SST sources and the third + // write round stays in one memtable source. Each source reports the rows its write round + // wrote, so this asserts the layout instead of only asserting that something was read. + { + let input = scanner.input(); + let mut file_rows = input + .files + .iter() + .map(|file| file.num_rows()) + .collect::>(); + file_rows.sort_unstable(); + let mut expected_file_rows = round_rows[..2].to_vec(); + expected_file_rows.sort_unstable(); + assert_eq!( + expected_file_rows, file_rows, + "each flushed write round must be one SST source" + ); + assert_eq!(2, input.num_files()); + assert_eq!( + 1, + input.num_memtables(), + "the last round is one memtable range" + ); + assert_eq!( + round_rows[2], + input + .memtables + .iter() + .map(|memtable| memtable.stats().num_rows) + .sum::(), + "the unflushed round must be the memtable's contribution" + ); + assert_eq!( + round_rows.iter().sum::(), + input.total_rows(), + "the sources must add up to every written row" + ); + } let source = primary_key_label_source(&scanner.metadata()); let ranges = scanner .properties() @@ -6083,8 +6133,9 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { per_partition.push(chunks); } - // The complete raw series stream of the multi-assignment scan: every assignment's chunks in - // partition order. + // The complete raw series stream of the two-partition scan: each partition's one assignment, + // concatenated in partition order. `test_two_phase_raw_same_partition_multi_round_assignment_ + // stays_contiguous` covers two assignments handed to the same partition. let complete = per_partition .into_iter() .flatten() @@ -6136,7 +6187,7 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { if runs.last() != Some(&key) { assert!( !runs.contains(&key), - "a series' chunks must stay contiguous across assignments" + "a series' chunks must stay contiguous across the concatenated assignments" ); runs.push(key); } @@ -6176,6 +6227,308 @@ async fn test_two_phase_raw_stream_stays_contiguous_across_assignments() { } } +/// Lowers the candidate-series assignment threshold and restores it when dropped. +/// +/// The override is process-global, so it is restored from `Drop` to keep a failing assertion or a +/// panic from leaking a weakened threshold into later tests of the same binary. `cargo nextest` +/// (the documented runner for this crate) additionally runs every test in its own process. +struct AssignmentThresholdScope; + +impl AssignmentThresholdScope { + fn lower_to(threshold: usize) -> Self { + crate::read::series_scan::set_candidate_series_assignment_threshold(threshold); + Self + } +} + +impl Drop for AssignmentThresholdScope { + fn drop(&mut self) { + crate::read::series_scan::set_candidate_series_assignment_threshold(0); + } +} + +/// One partition receiving two candidate assignments must still emit one contiguous stream. +/// +/// Without the threshold override a second assignment reaches the same partition only when a +/// single collection round holds `CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD` (1,000,000) candidate +/// series, so this test lowers the threshold instead of writing a million series. +#[tokio::test] +async fn test_two_phase_raw_same_partition_multi_round_assignment_stays_contiguous() { + use common_query::series_frame::{pack_raw_series, unpack_raw_series}; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::SampleRef; + use store_api::region_engine::QueryScanContext; + + // The candidate distributor starts a new assignment as soon as the collected series reach the + // threshold, and the candidate stream hands series over in globally sorted batches of at most + // `METRIC_SERIES_ID_BATCH_SIZE` (500) entries, yielding a trailing batch for the remainder. + // With the threshold lowered to 1 every one of those batches becomes one assignment round, so + // 501 series produce exactly two non-empty rounds: the first 500 sorted series, then the last + // one. Both rounds are addressed to the single output partition, i.e. to one receiver. + const CANDIDATE_BATCH: usize = 500; + const SERIES: usize = CANDIDATE_BATCH + 1; + let _scope = AssignmentThresholdScope::lower_to(1); + + let mut env = TestEnv::with_prefix("test_two_phase_raw_same_partition_multi_round").await; + let engine = env + .create_engine(MitoConfig { + experimental_series_scan_v2: true, + // The source-composition assertions below pin the flushed SST until the scan opens. + schedule_compaction_after_edit: false, + min_compaction_interval: Duration::from_secs(60 * 60), + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await; + + let tags = (0..SERIES) + .map(|index| format!("s{index}")) + .collect::>(); + let keys = tags + .iter() + .enumerate() + .map(|(index, tag)| { + new_sparse_primary_key(&[tag.as_str(), "x"], &metadata, 10, index as u64) + }) + .collect::>(); + // The round split below relies on the candidate stream ordering series by primary key, which + // is the ascending TSID order for this fixture. + let mut sorted_keys = keys.clone(); + sorted_keys.sort(); + assert_eq!(keys, sorted_keys, "primary keys must sort in TSID order"); + + // One flushed SST source plus one memtable source. The wide series spans more than one read + // batch, so a series is emitted as several chunks and the round boundary sits next to chunks + // that must stay grouped. + const WIDE: i64 = 20_000; + const SMALL: i64 = 3; + const SECOND_ROUND_FIRST: i64 = 100_000; + let mut expected_times = HashMap::, Vec>::new(); + expected_times.insert( + keys[0].clone(), + (0..WIDE) + .chain(SECOND_ROUND_FIRST..SECOND_ROUND_FIRST + 3) + .collect(), + ); + for key in &keys[1..] { + expected_times.insert( + key.clone(), + (0..SMALL) + .chain(SECOND_ROUND_FIRST..SECOND_ROUND_FIRST + 3) + .collect(), + ); + } + + let first_round = std::iter::once((keys[0].clone(), 0_i64, WIDE)) + .chain(keys[1..].iter().map(|key| (key.clone(), 0_i64, SMALL))) + .flat_map(|(key, first, count)| { + (0..count).map(move |offset| { + let time = first + offset; + (key.clone(), time, (time + 1) as u64) + }) + }) + .collect::>(); + let second_round = keys + .iter() + .flat_map(|key| { + (0..SMALL).map(move |offset| { + let time = SECOND_ROUND_FIRST + offset; + (key.clone(), time, (time + 1) as u64) + }) + }) + .collect::>(); + let (sst_rows, memtable_rows) = (first_round.len(), second_round.len()); + put_sparse_rows(&engine, region_id, &row_schema, first_round).await; + test_util::flush_region(&engine, region_id, None).await; + put_sparse_rows(&engine, region_id, &row_schema, second_round).await; + + let request = ScanRequest { + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let selected = engine.scanner(region_id, request).await.unwrap(); + let Scanner::Series(mut scanner) = selected else { + panic!("sparse PerSeries request must use SeriesScan"); + }; + assert_eq!("two_phase", scanner.mode()); + assert_eq!(SeriesOrdering::Contiguous, scanner.raw_series_ordering()); + // The fixture must really be one SST source plus one memtable source, or the two rounds below + // would be explained by something else. + { + let input = scanner.input(); + assert_eq!(1, input.num_files()); + assert_eq!( + vec![sst_rows], + input + .files + .iter() + .map(|file| file.num_rows()) + .collect::>() + ); + assert_eq!(1, input.num_memtables()); + assert_eq!( + memtable_rows, + input + .memtables + .iter() + .map(|memtable| memtable.stats().num_rows) + .sum::() + ); + } + + let source = primary_key_label_source(&scanner.metadata()); + let ranges = scanner + .properties() + .partitions + .clone() + .into_iter() + .flatten() + .collect::>(); + assert!(!ranges.is_empty(), "region scan needs an input range"); + // One output partition means every series the distributor assigns belongs to this receiver, + // so both rounds are delivered to partition 0. + scanner + .prepare(PrepareRequest { + ranges: Some(vec![ranges]), + target_partitions: Some(1), + ..Default::default() + }) + .unwrap(); + assert_eq!(1, scanner.properties().num_partitions()); + + let metrics = ExecutionPlanMetricsSet::default(); + let ctx = QueryScanContext::default(); + let stream = scanner + .scan_series_partition(&ctx, &metrics, 0, &source) + .unwrap() + .expect("two-phase raw scan is supported"); + assert_eq!(SeriesOrdering::Contiguous, stream.ordering()); + let schema = Arc::clone(stream.schema()); + let chunks = stream.try_collect::>().await.unwrap(); + // Two collection rounds really happened; the fixture never reaches the production threshold. + let rounds = crate::read::series_scan::candidate_assignment_rounds(); + assert!( + rounds >= 2, + "the partition must consume more than one assignment round, got {rounds}" + ); + assert!( + !chunks.is_empty(), + "partition 0 must own reader assignments" + ); + + // Partition 0's single stream carries every series exactly once, in ascending key order, so + // the stream crosses the round boundary: series 0..500 come from the first assignment and + // series 500 (the last of the globally sorted candidate stream) from the second one. + let mut runs = Vec::>::new(); + let mut chunks_per_series = HashMap::, usize>::new(); + for chunk in &chunks { + let key = chunk.primary_key.to_vec(); + *chunks_per_series.entry(key.clone()).or_default() += 1; + if runs.last() != Some(&key) { + assert!( + !runs.contains(&key), + "a series must not resume after another series across a round boundary" + ); + runs.push(key); + } + } + assert_eq!(keys, runs, "every series appears exactly once in key order"); + assert!( + chunks_per_series.values().copied().max().unwrap() > 1, + "the fixture must emit multiple chunks for one series, got {chunks_per_series:?}" + ); + // The round boundary: the first run belongs to the first assignment, the last run to the + // second assignment, and both are chunks of the same partition stream. + assert_eq!( + &keys[0], + runs.first().unwrap(), + "first round data is streamed" + ); + assert_eq!( + &keys[SERIES - 1], + runs.last().unwrap(), + "second round data is streamed" + ); + let last_round_chunks = chunks + .iter() + .filter(|chunk| chunk.primary_key.as_slice() == keys[SERIES - 1].as_slice()) + .count(); + assert!( + last_round_chunks > 0, + "the series of the second assignment must be streamed" + ); + + let stream_rows = chunks.iter().map(|chunk| chunk.time.len()).sum::(); + assert_eq!( + expected_times.values().map(Vec::len).sum::(), + stream_rows, + "the stream must carry every written row of both rounds" + ); + for (key, times) in &expected_times { + let observed = chunks + .iter() + .filter(|chunk| chunk.primary_key.as_slice() == key.as_slice()) + .flat_map(|chunk| chunk.time.as_buffer().iter().copied()) + .collect::>(); + assert_eq!(times, &observed, "timestamps must increase per series"); + assert!( + observed.windows(2).all(|window| window[0] < window[1]), + "timestamps must strictly increase within a key" + ); + } + for (index, chunk) in chunks.iter().enumerate() { + let next_is_same_series = chunks + .get(index + 1) + .is_some_and(|next| next.primary_key.as_slice() == chunk.primary_key.as_slice()); + assert_eq!( + !next_is_same_series, chunk.is_last, + "is_last must mark the final chunk of a series, including at the round boundary" + ); + let times = chunk.time.as_buffer(); + for (sample, time) in times.iter().enumerate() { + let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(sample) else { + panic!("raw fields are converted to float samples"); + }; + assert_eq!((*time + 1) as f64, value); + } + } + + // Route the same partition stream through the frame codec so its `SequenceValidator` checks + // the chunks this reader produced, including the chunks the second assignment added. + let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new( + Arc::clone(&schema), + source.clone(), + SeriesOrdering::Contiguous, + chunks.clone(), + ))) + .unwrap(); + let unpacked = unpack_raw_series( + packed, + Arc::clone(&schema), + source, + SeriesOrdering::Contiguous, + ) + .unwrap(); + let validated = unpacked.try_collect::>().await.unwrap(); + assert_eq!( + stream_rows, + validated + .iter() + .map(|chunk| chunk.time.len()) + .sum::(), + "packing and unpacking must preserve the multi-round stream" + ); + let mut schema_fields = schema + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>(); + schema_fields.dedup(); + assert_eq!(vec!["field_0"], schema_fields); +} + /// Creates the sparse-encoded flat region shared by the two-phase raw scan tests. /// /// Returns the region metadata and the row schema accepted by the sparse write path. diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index 8b4ad2acf20..971ff93a742 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -81,6 +81,49 @@ const SEND_TIMEOUT: Duration = Duration::from_micros(100); /// Maximum number of candidate series retained before distributing assignments. const CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD: usize = 1_000_000; +/// Test-only override of [`CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD`], where `0` means "use the +/// production constant". +/// +/// The production build compiles this static, the setter below and the private accessor out, so +/// the shipped threshold is always the constant above. +#[cfg(test)] +static CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE: AtomicUsize = AtomicUsize::new(0); + +/// Test-only number of candidate assignment rounds sent since the override was last set. +/// +/// A round is one `send_assignments` call, so a partition that received more than one assignment +/// sees `>= 2` rounds here. Increments are compiled out of production builds. +#[cfg(test)] +static CANDIDATE_ASSIGNMENT_ROUNDS: AtomicUsize = AtomicUsize::new(0); + +/// Returns the candidate-series assignment threshold, honouring the test-only override. +fn candidate_series_assignment_threshold() -> usize { + #[cfg(test)] + { + let threshold = CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.load(Ordering::Relaxed); + if threshold > 0 { + return threshold; + } + } + CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD +} + +/// Test-only: overrides the candidate-series assignment threshold and resets the round counter. +/// +/// Pass `0` to restore the production threshold. Tests must reset the override before they +/// return; a scope guard in `engine::scan_test` does that even on panic. +#[cfg(test)] +pub(crate) fn set_candidate_series_assignment_threshold(threshold: usize) { + CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.store(threshold, Ordering::Relaxed); + CANDIDATE_ASSIGNMENT_ROUNDS.store(0, Ordering::Relaxed); +} + +/// Test-only: returns the number of assignment rounds sent since the override was last set. +#[cfg(test)] +pub(crate) fn candidate_assignment_rounds() -> usize { + CANDIDATE_ASSIGNMENT_ROUNDS.load(Ordering::Relaxed) +} + /// Legacy data receivers for output partitions. type LegacyReceiverList = Vec>>>; @@ -1143,7 +1186,7 @@ impl SeriesCandidateDistributor { return Ok(()); } collector.push(batch); - if collector.len() >= CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD { + if collector.len() >= candidate_series_assignment_threshold() { chunked = true; self.send_assignments(collector.finish(false), &partition_pruner); if !self.should_fetch_candidates() { @@ -1167,6 +1210,9 @@ impl SeriesCandidateDistributor { assignments: Vec, partition_pruner: &Arc, ) { + // One round of candidate collection; a partition that receives two assignments sees two. + #[cfg(test)] + CANDIDATE_ASSIGNMENT_ROUNDS.fetch_add(1, Ordering::Relaxed); for (partition, assigned_series) in assignments.into_iter().enumerate() { if assigned_series.series().is_empty() { continue; From e1dba11eea857c2b1b9825753262fece81fffcfa Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:46:23 +0800 Subject: [PATCH 04/10] test(mito2): check the ordering the producer declares, and drop the promql dev-dep MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three end-to-end sites unpacked every frame as `Contiguous` while the producer declared `KeyThenTime`, and `SequenceValidator` only checks key order under the ordering it is given. A producer that declared key-then-time and emitted keys out of order passed all three. Each site now reads the ordering the frame declares, asserts it is `KeyThenTime` — so a future producer that quietly downgrades its declaration fails instead of skipping the check — and unpacks under it. Reversing two series' key order in the fixture now fails the test; passing `Contiguous` for the same frames still passes, which is what the old code did. The two-phase test asserted key order for an ordering that declares only `Contiguous`: a reader that stayed contiguous and stopped sorting keys is within contract and failed the test for it. It now asserts one run per key and that the two assignments hold the first and last key, which is what `Contiguous` plus the assignment composition actually promise. `promql` leaves mito2's dev-dependencies. The storage contract needs only `pack`/`unpack_raw_series` from `common-query`, which mito2 already depends on; the cross-region merge composition moves to promql, where it is a stream-level test rather than a two-region fixture: `merges_two_unpacked_frames_through_the_frame_codec`. The merge rejection that the two-phase test used to exercise is already covered by `rejects_unsupported_ordering_and_empty_input_without_polling`, which the remaining test now cites instead of duplicating. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- Cargo.lock | 1 - src/mito2/Cargo.toml | 1 - src/mito2/src/engine/scan_test.rs | 637 +++++---------------------- src/promql/src/source/merge/tests.rs | 62 +++ 4 files changed, 164 insertions(+), 537 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 43d65a03bd8..ea2a530d6b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8742,7 +8742,6 @@ dependencies = [ "partition", "pin-project", "prometheus 0.14.0", - "promql", "prost 0.14.1", "puffin", "rand 0.9.4", diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index 151694c40d1..02c134e964c 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -101,7 +101,6 @@ dotenv.workspace = true log-store = { workspace = true, features = ["testing"] } mito-codec = { workspace = true, features = ["testing"] } object-store = { workspace = true, features = ["services-memory"] } -promql.workspace = true rskafka.workspace = true rstest.workspace = true rstest_reuse.workspace = true diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 4a720ef73f2..c0b155f7311 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -4772,7 +4772,6 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { use datatypes::series::samples::SampleRef; use datatypes::value::Value as DatumValue; use mito_codec::row_converter::build_primary_key_codec; - use promql::source::materialize_raw_labels; use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; use store_api::region_request::RegionDeleteRequest; use table::predicate::Predicate; @@ -5093,7 +5092,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { assert_eq!(raw_visible, visible); // Exercise the production table physical consumer over a fresh real Mito scanner. - use common_query::series_frame::unpack_raw_series; + use common_query::series_frame::{raw_series_frame_ordering, unpack_raw_series}; use datafusion::execution::TaskContext; use datafusion::physical_plan::ExecutionPlan; use table::table::scan::RegionScanExec; @@ -5125,20 +5124,18 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { let native_frames = native_plan .execute(0, Arc::new(TaskContext::default())) .unwrap(); - let unpacked = unpack_raw_series( - native_frames, - native_schema, - native_source, - SeriesOrdering::Contiguous, - ) - .unwrap(); + // Unpack under the frame's own declaration. A legacy producer declares `KeyThenTime`, and + // only that declaration makes the decoder check that keys increase. + let frame_ordering = raw_series_frame_ordering(native_frames.schema().as_ref()).unwrap(); + assert_eq!( + SeriesOrdering::KeyThenTime, + frame_ordering, + "the legacy producer must declare key-then-time frames" + ); + let unpacked = + unpack_raw_series(native_frames, native_schema, native_source, frame_ordering).unwrap(); let native_schema = unpacked.schema().clone(); - let materialized = materialize_raw_labels(unpacked).unwrap(); - assert!(matches!( - materialized.label_source(), - RawLabelSource::Explicit - )); - let mut native = materialized.try_collect::>().await.unwrap(); + let mut native = unpacked.try_collect::>().await.unwrap(); assert_eq!( vec!["field_1", "field_0"], native_schema @@ -5150,18 +5147,17 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { let mut native_visible = native .drain(..) .flat_map(|chunk| { - let metric = chunk.metric.as_ref().expect("materialized complete metric"); - assert_eq!(Some("fixture_metric"), metric.name()); - let labels = metric - .tags() - .iter() - .map(|label| (label.name.as_ref(), label.value.as_ref())) - .collect::>(); - assert_eq!(1, labels.len()); - let tag = labels["tag_0"].to_string(); - assert!(tag == "A" || tag == "B"); - let times = chunk.time.as_buffer(); let key = chunk.primary_key.to_vec(); + // The frame binding is the raw primary key, so decode it back to the fixture tag to + // keep the raw rows comparable with the legacy path. + let tag = if key == expected_keys[0] { + "A" + } else if key == expected_keys[1] { + "B" + } else { + panic!("unexpected raw primary key {key:?}") + }; + let times = chunk.time.as_buffer(); let is_last = chunk.is_last; let mut rows = Vec::with_capacity(times.len()); for (i, time) in times.iter().enumerate() { @@ -5175,7 +5171,7 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { }; rows.push(( key.clone(), - tag.clone(), + tag.to_string(), *time, f1, f0, @@ -5230,478 +5226,22 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { ); } +/// A `TwoPhase` scan declares [`SeriesOrdering::Contiguous`] on the scanner, on every partition +/// stream, and therefore in every frame it packs; the frame adapter validates that declaration. +/// +/// The ordered merge that rejects a non-`KeyThenTime` input is covered by +/// `promql::source::merge::tests::rejects_unsupported_ordering_and_empty_input_without_polling`. #[tokio::test] -async fn test_mito_regional_raw_merge_preserves_global_key_order_and_labels() { - use api::v1::{Row, Value}; - use common_query::series_frame::{pack_raw_series, unpack_raw_series}; - use datatypes::arrow::array::Array; - use datatypes::series::SeriesOrdering; - use datatypes::series::samples::{SampleRef, SeriesSchema}; - use datatypes::value::Value as DatumValue; - use mito_codec::row_converter::build_primary_key_codec; - use promql::source::{materialize_raw_labels, merge_ordered_raw_series}; - use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; - use store_api::region_request::RegionDeleteRequest; - - let mut env = TestEnv::with_prefix("test_mito_regional_raw_merge").await; - let engine = env.create_engine(MitoConfig::default()).await; - let regions = [RegionId::new(1, 1), RegionId::new(1, 2)]; - let mut request = CreateRequestBuilder::new().field_num(3).build(); - request - .options - .insert("memtable.type".into(), "bulk".into()); - let schema = test_util::rows_schema(&request); - for region in regions { - engine - .handle_request(region, RegionRequest::Create(request.clone())) - .await - .unwrap(); - } - let make_row = |tag: &str, f0: Option, f1: f64, gate: f64, time: i64| Row { - values: vec![ - Some(ValueData::StringValue(tag.into())), - f0.map(ValueData::F64Value), - Some(ValueData::F64Value(f1)), - Some(ValueData::F64Value(gate)), - Some(ValueData::TimestampMillisecondValue(time)), - ] - .into_iter() - .map(|value_data| Value { value_data }) - .collect(), +async fn test_two_phase_native_raw_stream_declares_contiguous_frames() { + use common_query::series_frame::{ + pack_raw_series, raw_series_frame_ordering, unpack_raw_series, }; - for (region, rows) in [ - ( - regions[0], - vec![ - make_row("A", Some(10.0), 1.0, 1.0, 10), - make_row("A", None, 3.0, 1.0, 30), - make_row("B", Some(-0.0), 5.0, 1.0, 10), - ], - ), - ( - regions[1], - vec![ - make_row("A", Some(20.0), 2.0, 1.0, 20), - make_row("A", Some(40.0), 4.0, 1.0, 40), - make_row("C", Some(60.0), 6.0, 1.0, 10), - ], - ), - ] { - test_util::put_rows( - &engine, - region, - Rows { - schema: schema.clone(), - rows, - }, - ) - .await; - } - test_util::flush_region(&engine, regions[0], None).await; - test_util::flush_region(&engine, regions[1], None).await; - test_util::put_rows( - &engine, - regions[0], - Rows { - schema: schema.clone(), - rows: vec![ - make_row("A", Some(11.0), 11.0, 1.0, 10), - make_row("A", Some(50.0), 5.0, 0.0, 50), - make_row("B", Some(60.0), 6.0, 1.0, 60), - ], - }, - ) - .await; - engine - .handle_request( - regions[0], - RegionRequest::Delete(RegionDeleteRequest { - rows: Rows { - schema: test_util::delete_rows_schema( - &CreateRequestBuilder::new().field_num(3).build(), - ), - rows: vec![row(vec![ - ValueData::StringValue("B".into()), - ValueData::TimestampMillisecondValue(60), - ])], - }, - hint: None, - partition_expr_version: None, - }), - ) - .await - .unwrap(); - let request = ScanRequest { - projection: Some(vec![2, 1, 4]), - filters: vec![col("field_2").gt(lit(0.0_f64))], - distribution: Some(TimeSeriesDistribution::PerSeries), - preserve_pk_dictionary_encoding: true, - ..Default::default() - }; - let mut streams = Vec::new(); - let mut metadata_for_codec = None; - let mut expected_schema: Option> = None; - let metrics = ExecutionPlanMetricsSet::default(); - for region in regions { - let selected = engine.scanner(region, request.clone()).await.unwrap(); - let mut scanner: Box = match selected { - Scanner::Series(series) => { - assert_eq!("legacy", series.mode()); - Box::new(series) - } - _ => panic!("PerSeries request must select a series scanner"), - }; - assert_eq!(SeriesOrdering::KeyThenTime, scanner.raw_series_ordering()); - let metadata = scanner.metadata(); - metadata_for_codec.get_or_insert_with(|| metadata.clone()); - let source = RawLabelSource::PrimaryKey { - metric_name: Arc::from("fixture_metric"), - physical_metadata: metadata.clone(), - logical_tags: metadata - .column_metadatas - .iter() - .filter(|column| { - column.semantic_type == SemanticType::Tag - && !store_api::storage::consts::is_internal_column( - &column.column_schema.name, - ) - && !store_api::metric_engine_consts::is_metric_engine_internal_column( - &column.column_schema.name, - ) - }) - .map(|column| BoundTag { - column_id: column.column_id, - name: Arc::from(column.column_schema.name.as_str()), - }) - .collect::>() - .into(), - }; - let ranges = scanner - .properties() - .partitions - .clone() - .into_iter() - .flatten() - .collect::>(); - assert!(!ranges.is_empty(), "region scan needs an input range"); - let partition_count = 2; - let mut partitions = vec![Vec::new(); partition_count]; - for (index, range) in ranges.into_iter().enumerate() { - partitions[index % partition_count].push(range); - } - scanner - .prepare(PrepareRequest { - ranges: Some(partitions), - target_partitions: Some(partition_count), - ..Default::default() - }) - .unwrap(); - let partition_count = scanner.properties().num_partitions(); - assert!( - partition_count > 1, - "prepare must use multiple supplied native range partitions" - ); - for partition in 0..partition_count { - let stream = scanner - .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) - .unwrap() - .expect("native raw input"); - assert_eq!(scanner.raw_series_ordering(), stream.ordering()); - assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering()); - assert_eq!( - vec!["field_1", "field_0"], - stream - .schema() - .fields - .iter() - .map(|field| field.name.as_ref()) - .collect::>() - ); - if let Some(schema) = &expected_schema { - assert_eq!( - schema - .fields - .iter() - .map(|field| field.name.as_ref()) - .collect::>(), - stream - .schema() - .fields - .iter() - .map(|field| field.name.as_ref()) - .collect::>() - ); - } else { - expected_schema = Some(Arc::clone(stream.schema())); - } - streams.push(stream); - } - // Each scanner owns the same schema and explicitly bound source. - } - let merged = merge_ordered_raw_series(streams).unwrap(); - let merged_schema = Arc::clone(merged.schema()); - let binding = merged.label_source().clone(); - let ordering = merged.ordering(); - assert_eq!(SeriesOrdering::KeyThenTime, ordering); - let packed = pack_raw_series(merged).unwrap(); - let unpacked = unpack_raw_series(packed, merged_schema, binding, ordering).unwrap(); - let mut materialized = materialize_raw_labels(unpacked).unwrap(); - let mut actual = Vec::new(); - while let Some(chunk) = materialized.try_next().await.unwrap() { - let metric = chunk.metric.as_ref().unwrap(); - assert_eq!(Some("fixture_metric"), metric.name()); - let tag = metric.get("tag_0").unwrap().to_string(); - for index in 0..chunk.time.len() { - let SampleRef::Float(f1) = chunk.fields.get(0).unwrap().sample(index) else { - panic!("field_1 float") - }; - let f0 = match chunk.fields.get(1).unwrap().sample(index) { - SampleRef::Float(value) => Some(value.to_bits()), - SampleRef::Missing => None, - _ => panic!("unexpected field_0 sample type"), - }; - actual.push(( - chunk.primary_key.to_vec(), - tag.clone(), - chunk.time.timestamp(index).unwrap(), - f1.to_bits(), - f0, - chunk.is_last && index + 1 == chunk.time.len(), - )); - } - } - assert!( - actual - .windows(2) - .all(|pair| pair[0].0 < pair[1].0 || (pair[0].0 == pair[1].0 && pair[0].2 < pair[1].2)), - "merged stream must be ordered by full read key then time" - ); - let metadata = metadata_for_codec.unwrap(); - let codec = build_primary_key_codec(&metadata); - let mut expected = Vec::new(); - for (tag, time, f1, f0) in [ - ("A", 10, 11.0_f64, Some(11.0_f64)), - ("A", 20, 2.0, Some(20.0)), - ("A", 30, 3.0, None), - ("A", 40, 4.0, Some(40.0)), - ("B", 10, 5.0, Some(-0.0_f64)), - ("C", 10, 6.0, Some(60.0)), - ] { - let mut key = Vec::new(); - codec - .encode_values( - &[(metadata.primary_key[0], DatumValue::String(tag.into()))], - &mut key, - ) - .unwrap(); - expected.push((key, tag, time, f1.to_bits(), f0.map(f64::to_bits))); - } - let duplicate_key = expected[0].0.clone(); - assert_eq!( - expected - .iter() - .map(|(key, _, _, _, _)| key.clone()) - .collect::>(), - actual.iter().map(|row| row.0.clone()).collect::>() - ); - let visible = actual - .iter() - .map(|(_, tag, time, f1, f0, _)| (tag.as_str(), *time, *f1, *f0)) - .collect::>(); - assert_eq!( - expected - .iter() - .map(|(_, tag, time, f1, f0)| (*tag, *time, *f1, *f0)) - .collect::>(), - visible - ); - let mut legacy_batches = Vec::new(); - for region in regions { - let mut legacy_request = request.clone(); - legacy_request.projection = Some(vec![0, 1, 2, 3, 4]); - legacy_request.filters.clear(); - legacy_request.preserve_pk_dictionary_encoding = false; - let legacy = engine.handle_query(region, legacy_request).await.unwrap(); - for partition in 0..legacy.properties().num_partitions() { - legacy_batches.extend( - legacy - .scan_partition(&QueryScanContext::default(), &metrics, partition) - .unwrap() - .try_collect::>() - .await - .unwrap(), - ); - } - } - let mut legacy_visible = Vec::new(); - for batch in &legacy_batches { - let batch = batch.df_record_batch(); - let tags = batch - .column_by_name("tag_0") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let f0 = batch - .column_by_name("field_0") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let f1 = batch - .column_by_name("field_1") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let times = batch - .column_by_name("ts") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let gate = batch - .column_by_name("field_2") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - for row in 0..batch.num_rows() { - if gate.value(row) > 0.0 { - legacy_visible.push(( - tags.value(row).to_string(), - times.value(row), - f1.value(row).to_bits(), - if f0.is_null(row) { - None - } else { - Some(f0.value(row).to_bits()) - }, - )); - } - } - } - legacy_visible.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1))); - let mut raw_visible = actual - .iter() - .map(|(_, tag, time, f1, f0, _)| (tag.clone(), *time, *f1, *f0)) - .collect::>(); - raw_visible.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1))); - assert_eq!( - legacy_visible, raw_visible, - "raw candidates after field_2 predicate must match legacy scan" - ); - test_util::put_rows( - &engine, - regions[1], - Rows { - schema: schema.clone(), - rows: vec![make_row("A", Some(99.0), 99.0, 1.0, 30)], - }, - ) - .await; - let mut duplicate_inputs = Vec::new(); - for region in regions { - let scanner = engine.handle_query(region, request.clone()).await.unwrap(); - let metadata = scanner.metadata(); - let source = RawLabelSource::PrimaryKey { - metric_name: Arc::from("fixture_metric"), - physical_metadata: metadata.clone(), - logical_tags: metadata - .column_metadatas - .iter() - .filter(|column| { - column.semantic_type == SemanticType::Tag - && !store_api::storage::consts::is_internal_column( - &column.column_schema.name, - ) - && !store_api::metric_engine_consts::is_metric_engine_internal_column( - &column.column_schema.name, - ) - }) - .map(|column| BoundTag { - column_id: column.column_id, - name: Arc::from(column.column_schema.name.as_str()), - }) - .collect::>() - .into(), - }; - let mut scanner = scanner; - let ranges = scanner - .properties() - .partitions - .clone() - .into_iter() - .flatten() - .collect::>(); - let partition_count = 2; - let mut partitions = vec![Vec::new(); partition_count]; - for (index, range) in ranges.into_iter().enumerate() { - partitions[index % partition_count].push(range); - } - scanner - .prepare(PrepareRequest { - ranges: Some(partitions), - target_partitions: Some(partition_count), - ..Default::default() - }) - .unwrap(); - for partition in 0..scanner.properties().num_partitions() { - duplicate_inputs.push( - scanner - .scan_series_partition( - &QueryScanContext::default(), - &metrics, - partition, - &source, - ) - .unwrap() - .unwrap(), - ); - } - } - let mut duplicate_merge = merge_ordered_raw_series(duplicate_inputs).unwrap(); - let mut affected_key_last = Vec::new(); - let duplicate_error = loop { - match duplicate_merge.try_next().await { - Ok(Some(chunk)) => { - if chunk.primary_key.as_slice() == duplicate_key.as_slice() { - affected_key_last.push(chunk.is_last); - } - } - Ok(None) => panic!("same full key/timestamp across regions must fail"), - Err(error) => break error.to_string(), - } - }; - assert!( - duplicate_error.contains("timestamp") || duplicate_error.contains("time"), - "unexpected duplicate timestamp error: {duplicate_error}" - ); - assert!(!affected_key_last.is_empty()); - assert!(affected_key_last.iter().all(|is_last| !is_last)); - assert!( - duplicate_merge.try_next().await.unwrap().is_none(), - "merge error must fuse stream" - ); - for tag in ["A", "B", "C"] { - let key_rows = actual.iter().filter(|row| row.1 == tag).collect::>(); - assert_eq!( - 1, - key_rows.iter().filter(|row| row.5).count(), - "global finality for {tag}" - ); - assert!(key_rows.last().unwrap().5); - assert!(key_rows[..key_rows.len() - 1].iter().all(|row| !row.5)); - } -} - -#[tokio::test] -async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { use datatypes::series::SeriesOrdering; + use datatypes::series::samples::SeriesSchema; use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource}; use store_api::region_request::RegionPutRequest; - let mut env = TestEnv::with_prefix("test_two_phase_native_raw_merge_rejection").await; + let mut env = TestEnv::with_prefix("test_two_phase_native_raw_contiguous_frames").await; let engine = env .create_engine(MitoConfig { experimental_series_scan_v2: true, @@ -5806,23 +5346,47 @@ async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { }) .unwrap(); let metrics = ExecutionPlanMetricsSet::default(); - let mut streams = Vec::new(); + let mut schema: Option> = None; + let mut chunks = Vec::new(); for partition in 0..ranges.len() { let stream = scanner .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) .unwrap() .unwrap(); + // The storage-side contract: every partition stream reports the scanner's declaration. assert_eq!(scanner.raw_series_ordering(), stream.ordering()); assert_eq!(SeriesOrdering::Contiguous, stream.ordering()); - streams.push(stream); + schema.get_or_insert_with(|| Arc::clone(stream.schema())); + chunks.extend(stream.try_collect::>().await.unwrap()); } - let error = match promql::source::merge_ordered_raw_series(streams) { - Ok(_) => panic!("Contiguous two-phase input cannot satisfy ordered merge ordering"), - Err(error) => error, - }; - assert!( - error.to_string().contains("ordering") || error.to_string().contains("ordered"), - "expected ordering rejection, got: {error}" + assert_eq!( + 2, + chunks.iter().map(|chunk| chunk.time.len()).sum::() + ); + + // The frames the adapter receives carry that declaration, and the adapter validates it + // through `pack`/`unpack_raw_series` without ever seeing a sorted key guarantee. + let schema = schema.expect("the scan must emit at least one partition stream"); + let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new( + Arc::clone(&schema), + source.clone(), + SeriesOrdering::Contiguous, + chunks, + ))) + .unwrap(); + let ordering = raw_series_frame_ordering(packed.schema().as_ref()).unwrap(); + assert_eq!(SeriesOrdering::Contiguous, ordering); + let validated = unpack_raw_series(packed, schema, source, ordering) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + 2, + validated + .iter() + .map(|chunk| chunk.time.len()) + .sum::() ); } @@ -6418,9 +5982,10 @@ async fn test_two_phase_raw_same_partition_multi_round_assignment_stays_contiguo "partition 0 must own reader assignments" ); - // Partition 0's single stream carries every series exactly once, in ascending key order, so - // the stream crosses the round boundary: series 0..500 come from the first assignment and - // series 500 (the last of the globally sorted candidate stream) from the second one. + // Partition 0's single stream carries every series in one contiguous run each. `TwoPhase` + // declares only `Contiguous`, so the runs are not contracted to be sorted; the assignment + // composition is: the first assignment holds the first 500 candidate series (which includes + // `keys[0]`) and the trailing assignment holds the last candidate series. let mut runs = Vec::>::new(); let mut chunks_per_series = HashMap::, usize>::new(); for chunk in &chunks { @@ -6434,22 +5999,21 @@ async fn test_two_phase_raw_same_partition_multi_round_assignment_stays_contiguo runs.push(key); } } - assert_eq!(keys, runs, "every series appears exactly once in key order"); + assert_eq!(keys.len(), runs.len(), "every series appears in one run"); assert!( chunks_per_series.values().copied().max().unwrap() > 1, "the fixture must emit multiple chunks for one series, got {chunks_per_series:?}" ); // The round boundary: the first run belongs to the first assignment, the last run to the // second assignment, and both are chunks of the same partition stream. - assert_eq!( - &keys[0], - runs.first().unwrap(), - "first round data is streamed" + let (first_assignment, second_assignment) = runs.split_at(SERIES - 1); + assert!( + first_assignment.contains(&keys[0]), + "the first assignment must stream the first key" ); - assert_eq!( - &keys[SERIES - 1], - runs.last().unwrap(), - "second round data is streamed" + assert!( + second_assignment.contains(&keys[SERIES - 1]), + "the second assignment must stream the last key" ); let last_round_chunks = chunks .iter() @@ -6794,7 +6358,7 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() { assert_eq!(vec![(2, 20.0)], output_values); // Validate the typed integer gate through RegionScanExec's actual physical consumer. - use common_query::series_frame::unpack_raw_series; + use common_query::series_frame::{raw_series_frame_ordering, unpack_raw_series}; use datafusion::execution::TaskContext; use datafusion::physical_plan::ExecutionPlan; use datatypes::series::SeriesOrdering; @@ -6830,16 +6394,18 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() { let frames = native_plan .execute(0, Arc::new(TaskContext::default())) .unwrap(); - let chunks = unpack_raw_series( - frames, - native_schema, - native_source, - SeriesOrdering::Contiguous, - ) - .unwrap() - .try_collect::>() - .await - .unwrap(); + // Unpack under the frame's own declaration so the decoder checks the legacy key order. + let ordering = raw_series_frame_ordering(frames.schema().as_ref()).unwrap(); + assert_eq!( + SeriesOrdering::KeyThenTime, + ordering, + "the legacy producer must declare key-then-time frames" + ); + let chunks = unpack_raw_series(frames, native_schema, native_source, ordering) + .unwrap() + .try_collect::>() + .await + .unwrap(); let native_rows = chunks .iter() .flat_map(|chunk| { @@ -6887,16 +6453,17 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() { let empty_frames = empty_plan .execute(0, Arc::new(TaskContext::default())) .unwrap(); - let empty_chunks = unpack_raw_series( - empty_frames, - empty_schema, - empty_source, - SeriesOrdering::Contiguous, - ) - .unwrap() - .try_collect::>() - .await - .unwrap(); + let empty_ordering = raw_series_frame_ordering(empty_frames.schema().as_ref()).unwrap(); + assert_eq!( + SeriesOrdering::KeyThenTime, + empty_ordering, + "a statically empty legacy scan still declares key-then-time frames" + ); + let empty_chunks = unpack_raw_series(empty_frames, empty_schema, empty_source, empty_ordering) + .unwrap() + .try_collect::>() + .await + .unwrap(); assert!(empty_chunks.is_empty()); } diff --git a/src/promql/src/source/merge/tests.rs b/src/promql/src/source/merge/tests.rs index 4ad5d17cbb7..853da99e823 100644 --- a/src/promql/src/source/merge/tests.rs +++ b/src/promql/src/source/merge/tests.rs @@ -23,6 +23,7 @@ use std::task::{Context, Poll, Waker}; use api::v1::SemanticType; use common_error::ext::{BoxedError, ErrorExt, PlainError}; use common_error::status_code::StatusCode; +use common_query::series_frame::{pack_raw_series, raw_series_frame_ordering, unpack_raw_series}; use datatypes::arrow::array::Float64Array; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; use datatypes::data_type::ConcreteDataType; @@ -431,6 +432,67 @@ async fn merges_full_encoded_keys_and_interleaved_chunks_with_global_finality() assert!(series[2].3.last().unwrap()); } +/// Two inputs that each went through the frame codec merge like plain streams: unpacking keeps +/// the declared ordering, and the merge restores global key order and per-key finality across +/// the unpacked frames. +#[tokio::test] +async fn merges_two_unpacked_frames_through_the_frame_codec() { + let rack_a_sensor_1 = read_key("rack-a", "sensor-1"); + let rack_b_sensor_1 = read_key("rack-b", "sensor-1"); + let framed = |labels: RawLabelSource, chunks: Vec| { + let (stream, _, _) = stream( + labels, + SeriesOrdering::KeyThenTime, + chunks.into_iter().map(ready), + ); + let schema = Arc::clone(stream.schema()); + let binding = stream.label_source().clone(); + let packed = pack_raw_series(stream).unwrap(); + let ordering = raw_series_frame_ordering(packed.schema().as_ref()).unwrap(); + assert_eq!(SeriesOrdering::KeyThenTime, ordering); + unpack_raw_series(packed, schema, binding, ordering).unwrap() + }; + let left = framed( + label_source(1), + vec![ + chunk(rack_a_sensor_1.clone(), &[10, 30], &[1.0, 3.0], true), + chunk(rack_b_sensor_1.clone(), &[5], &[5.0], true), + ], + ); + let right = framed( + label_source(2), + vec![chunk(rack_a_sensor_1.clone(), &[20, 40], &[2.0, 4.0], true)], + ); + + let mut merged = merge_ordered_raw_series(vec![left, right]).unwrap(); + assert_eq!(SeriesOrdering::KeyThenTime, merged.ordering()); + let mut series = Vec::<(Buffer, Vec, Vec)>::new(); + while let Some(item) = merged.next().await { + let item = item.unwrap(); + if series + .last() + .is_none_or(|current| current.0 != item.primary_key) + { + series.push((item.primary_key.clone(), Vec::new(), Vec::new())); + } + let current = series.last_mut().unwrap(); + current.1.extend(item.time.as_buffer().to_vec()); + current.2.push(item.is_last); + } + assert_eq!(2, series.len()); + assert_eq!(rack_a_sensor_1, series[0].0); + assert_eq!(vec![10, 20, 30, 40], series[0].1); + assert!(*series[0].2.last().unwrap()); + assert!( + series[0].2[..series[0].2.len() - 1] + .iter() + .all(|last| !last) + ); + assert_eq!(rack_b_sensor_1, series[1].0); + assert_eq!(vec![5], series[1].1); + assert!(*series[1].2.last().unwrap()); +} + #[tokio::test] async fn rejects_equal_timestamp_from_separate_heads() { let key = read_key("rack-a", "sensor-1"); From 420255ed3950a0a0801ec8551816582e9c00af54 Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Wed, 21 Oct 2026 11:21:36 +0800 Subject: [PATCH 05/10] feat(promql): add limitk, limit_ratio and binary fill modifiers to native kernels (#9805) Signed-off-by: Dennis Zhuang --- Cargo.lock | 1 + Cargo.toml | 1 + src/promql/Cargo.toml | 1 + src/promql/src/grid_series.rs | 11 + src/promql/src/native/display.rs | 20 +- src/promql/src/native/display/tests.rs | 20 +- src/promql/src/native/metrics.rs | 1 + src/promql/src/native/plan/tests.rs | 3 +- src/promql/src/select.rs | 180 +- src/promql/src/select/limit_cases.txt | 1372 +++++++++++++ src/promql/src/select/tests.rs | 204 +- src/promql/src/vector_match.rs | 246 ++- src/promql/src/vector_match/fill_cases.txt | 2021 ++++++++++++++++++++ src/promql/src/vector_match/tests.rs | 100 +- 14 files changed, 4052 insertions(+), 129 deletions(-) create mode 100644 src/promql/src/select/limit_cases.txt create mode 100644 src/promql/src/vector_match/fill_cases.txt diff --git a/Cargo.lock b/Cargo.lock index ea2a530d6b5..a42a20af081 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11377,6 +11377,7 @@ dependencies = [ "snafu 0.8.6", "store-api", "tokio", + "twox-hash", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 702498ee5e5..c870b88c0b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -278,6 +278,7 @@ tracing = "0.1" tracing-appender = "0.2" tracing-opentelemetry = "0.33.0" tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "fmt"] } +twox-hash = { version = "2.1", default-features = false, features = ["xxhash64"] } typetag = "0.2" uddsketch-rs = "0.1.0" uuid = { version = "1.17", features = ["serde", "v4", "v7", "fast-rng"] } diff --git a/src/promql/Cargo.toml b/src/promql/Cargo.toml index ad682f4b2a2..a3d8f5c4e71 100644 --- a/src/promql/Cargo.toml +++ b/src/promql/Cargo.toml @@ -28,6 +28,7 @@ prost.workspace = true regex.workspace = true snafu.workspace = true store-api.workspace = true +twox-hash.workspace = true [dev-dependencies] api.workspace = true diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index b5634b259e9..ce24cae6af4 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -88,6 +88,17 @@ pub(crate) enum GridSample { const _: () = assert!(std::mem::size_of::>() == 16); +/// `sample` as an owned value; `None` when missing. +pub(crate) fn owned(sample: SampleRef<'_>) -> Result> { + Ok(match sample { + SampleRef::Missing => None, + SampleRef::Float(value) => Some(GridSample::Float(value)), + SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new( + FloatHistogram::try_from_view(&view)?, + ))), + }) +} + impl GridSeriesBuilder { /// Creates a builder for series of `schema`, which must have an evaluation grid. pub fn try_new(schema: Arc) -> Result { diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 7e0e82c2b5e..86d40946cc1 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -32,7 +32,7 @@ use crate::native::plan::{ NativeType, }; use crate::range_eval::RangeFunction; -use crate::vector_match::{BinaryOp, Cardinality, MatchingLabels}; +use crate::vector_match::{BinaryOp, Cardinality, FillValues, MatchingLabels}; /// The header line of every tree. const HEADER: &str = "NativeTree"; @@ -121,7 +121,7 @@ fn describe(node: &NativeNode) -> String { } ), NativeExpr::Binary { matching, .. } => format!( - "{}{} {} {}", + "{}{} {} {}{}", binary_op(matching.op), if matching.return_bool { " bool" } else { "" }, match &matching.labels { @@ -132,11 +132,25 @@ fn describe(node: &NativeNode) -> String { Cardinality::OneToOne => "one-to-one".to_string(), Cardinality::ManyToOne(labels) => format!("many-to-one [{}]", label_list(labels)), Cardinality::OneToMany(labels) => format!("one-to-many [{}]", label_list(labels)), - } + }, + fill(matching.fill) ), } } +fn fill(values: FillValues) -> String { + let side = |name: &str, value: Option| { + value + .map(|value| format!(" {name} {value}")) + .unwrap_or_default() + }; + format!( + "{}{}", + side("fill_left", values.lhs), + side("fill_right", values.rhs) + ) +} + /// A window: what it runs, over which range, and where it lands. fn window(op: &BoundWindow) -> String { format!( diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 8166bad3c98..316f6a39a4e 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -24,7 +24,7 @@ use super::super::plan::{ }; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) @@ -324,11 +324,12 @@ fn an_aggregate_and_a_binary_name_their_binding() { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }, }, output: evaluated(out), }; - let tree = NativeTree::try_new(binary).unwrap(); + let tree = NativeTree::try_new(binary.clone()).unwrap(); assert_eq!( tree.to_string(), shown(&[ @@ -339,6 +340,21 @@ fn an_aggregate_and_a_binary_name_their_binding() { " input Input raw samples", ]) ); + + // Fill values change the result, so a set one is part of the binding shown. + let mut filled = binary; + let NativeExpr::Binary { matching, .. } = &mut filled.expr else { + unreachable!() + }; + matching.fill.rhs = Some(0.5); + assert_eq!( + NativeTree::try_new(filled) + .unwrap() + .to_string() + .lines() + .nth(1), + Some(" root Binary + ignoring [] one-to-one fill_right 0.5") + ); } /// A `without` grouping reads as `without [...]`, not as `by [...]`. diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index bcae9ddcdd0..6e36153fe2e 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -452,6 +452,7 @@ mod tests { return_bool: false, labels: crate::vector_match::MatchingLabels::Ignoring(Vec::new()), cardinality: crate::vector_match::Cardinality::OneToOne, + fill: crate::vector_match::FillValues::default(), }, }, output: { diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 85be7426a58..1c42c3b32af 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -24,7 +24,7 @@ use super::{ }; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) @@ -218,6 +218,7 @@ fn add() -> BinaryMatching { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), } } diff --git a/src/promql/src/select.rs b/src/promql/src/select.rs index cc869b91a93..c65a7955c36 100644 --- a/src/promql/src/select.rs +++ b/src/promql/src/select.rs @@ -13,9 +13,9 @@ // limitations under the License. //! Operators that depend on the whole set of evaluated series at each grid point: `topk`, -//! `bottomk`, `scalar`, `absent` and the instant-result sorts. +//! `bottomk`, `limitk`, `limit_ratio`, `scalar`, `absent` and the instant-result sorts. //! -//! Semantics follow Prometheus (`aggregationK`, `funcScalar`, `funcAbsent`, +//! Semantics follow Prometheus (`aggregationK`, `HashRatioSampler`, `funcScalar`, `funcAbsent`, //! `createLabelsForAbsentFunction`, `funcSort*`). A scalar is a grid series without labels that //! has a value at every point, so `vector(s)` is `s` itself and has no kernel. @@ -29,7 +29,7 @@ use datatypes::series::time::union_positions; use datatypes::series::{Label, MetricName}; use crate::go_sort; -use crate::grid_series::{GridSeriesBuilder, external}; +use crate::grid_series::{GridSeriesBuilder, external, owned}; #[cfg(test)] mod tests; @@ -73,22 +73,9 @@ pub fn topk( // Validates the series against the schema and its grid; the walk below visits the carried // positions, not the whole grid. grid_points(schema, series)?; - // Prometheus returns nothing for k below 1, rejects NaN and values out of int64, then - // truncates k and caps it at the number of input series. - if k < 1.0 { + let Some(k) = k_param(k, series.len())? else { return Ok(Vec::new()); - } - if k.is_nan() { - return Err(DataFusionError::Execution("Parameter value is NaN".into())); - } - // Prometheus' `maxInt64`, the largest float64 below 2^63. - if k >= 9_223_372_036_854_774_784.0 { - return Err(DataFusionError::Execution(format!( - "Scalar value {k} overflows int64" - ))); - } - let k = k.trunc().min(series.len() as f64) as usize; - + }; let mut order: Vec = (0..series.len()).collect(); order.sort_by(|&a, &b| compare_labels(&series[a].metric, &series[b].metric)); let mut groups: HashMap> = HashMap::new(); @@ -149,6 +136,144 @@ pub fn topk( Ok(result) } +/// `limitk(k, ...)` with a constant `k`. +/// +/// At every point each group keeps the first `k` series in input order that hold a sample there, +/// float or histogram, with their labels and values. Prometheus takes them in the order its +/// storage returns series: label order once a query reads several queriers (the head and a +/// block), creation order when the TSDB head alone answers it. A caller that wants Prometheus' +/// result over persisted data passes the series in label order. +pub fn limitk( + k: f64, + grouping: &Grouping, + schema: &SeriesSchema, + series: &[Series], +) -> Result> { + single_field(schema, "limitk")?; + grid_points(schema, series)?; + let Some(k) = k_param(k, series.len())? else { + return Ok(Vec::new()); + }; + let mut groups: HashMap> = HashMap::new(); + for (index, item) in series.iter().enumerate() { + groups + .entry(group_key(&item.metric, grouping)) + .or_default() + .push(index); + } + let mut selected: Vec> = vec![Vec::new(); series.len()]; + for members in groups.values() { + let mut cursors: Vec> = members + .iter() + .map(|&member| series[member].fields.as_slice()[0].cursor()) + .collect(); + for point in union_positions(members.iter().map(|&member| &series[member].time)) { + let mut taken = 0; + for (slot, &member) in members.iter().enumerate() { + if taken == k { + break; + } + let Some(row) = series[member].time.row_of(point) else { + continue; + }; + if !matches!( + cursors[slot] + .at(row) + .expect("the axis and the fields are aligned"), + SampleRef::Missing + ) { + selected[member].push((point, row)); + taken += 1; + } + } + } + } + + let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?; + let mut result = Vec::new(); + for (index, points) in selected.into_iter().enumerate() { + if points.is_empty() { + continue; + } + builder.begin_series(); + // A series belongs to one group, whose points are visited in order. + let mut cursor = series[index].fields.as_slice()[0].cursor(); + for (point, row) in points { + let sample = cursor.at(row).expect("the axis and the fields are aligned"); + builder.push_samples(point, &[owned(sample)?])?; + } + result.extend(builder.finish(series[index].metric.clone())?); + } + Ok(result) +} + +/// `limit_ratio(r, ...)` with a constant `r`. +/// +/// Keeps whole series: Prometheus derives an offset in `[0, 1)` from the hash of a series' labels +/// and keeps the series when the offset is below `r`, or, for a negative `r`, at least `1 + r`. +/// Which series are kept does not depend on the grouping, so it is not a parameter. The hash is +/// the one of Prometheus' default `stringlabels` build; the other label builds hash differently. +pub fn limit_ratio(ratio: f64, schema: &SeriesSchema, series: &[Series]) -> Result> { + grid_points(schema, series)?; + if ratio.is_nan() { + return Err(DataFusionError::Execution("Ratio value is NaN".into())); + } + let ratio = ratio.clamp(-1.0, 1.0); + let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?; + let mut result = Vec::new(); + let mut row = Vec::with_capacity(schema.fields.len()); + for item in series { + let offset = sample_offset(&item.metric); + let kept = if ratio >= 0.0 { + offset < ratio + } else { + offset >= 1.0 + ratio + }; + if !kept { + continue; + } + // Rebuilt rather than cloned: an input may carry rows without a value, a result may not. + builder.begin_series(); + let mut cursors: Vec> = + item.fields.iter().map(|field| field.cursor()).collect(); + for (point, index) in item.time.positions() { + row.clear(); + for cursor in &mut cursors { + row.push(owned( + cursor + .at(index) + .expect("the axis and the fields are aligned"), + )?); + } + builder.push_samples(point, &row)?; + } + result.extend(builder.finish(item.metric.clone())?); + } + Ok(result) +} + +/// Prometheus `HashRatioSampler.SampleOffset`: the xxHash64 of the labels as `stringlabels` +/// encodes them, each name and value prefixed by its length, over `u64::MAX`. +fn sample_offset(metric: &MetricName) -> f64 { + let mut data = Vec::new(); + for (name, value) in labels_with_name(metric) { + // Prometheus label sets hold no empty value. + if value.is_empty() { + continue; + } + for text in [&name, &value] { + let len = text.len(); + if len < 255 { + data.push(len as u8); + } else { + data.extend([255, len as u8, (len >> 8) as u8, (len >> 16) as u8]); + } + data.extend_from_slice(text.as_bytes()); + } + } + twox_hash::XxHash64::oneshot(0, &data) as f64 / u64::MAX as f64 +} + /// `scalar(v)`: the value of the only series present at each point, NaN otherwise. pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result { single_field(schema, "scalar")?; @@ -361,6 +486,25 @@ fn rank(a: f64, b: f64, top: bool) -> Ordering { } } +/// The `k` of `topk`, `bottomk` and `limitk` as Prometheus reads it: nothing for `k` below 1, an +/// error for NaN or a value out of int64, otherwise `k` truncated and capped at the number of +/// input series. +fn k_param(k: f64, series: usize) -> Result> { + if k < 1.0 { + return Ok(None); + } + if k.is_nan() { + return Err(DataFusionError::Execution("Parameter value is NaN".into())); + } + // Prometheus' `maxInt64`, the largest float64 below 2^63. + if k >= 9_223_372_036_854_774_784.0 { + return Err(DataFusionError::Execution(format!( + "Scalar value {k} overflows int64" + ))); + } + Ok(Some(k.trunc().min(series as f64) as usize)) +} + /// Label pairs identifying a group; empty values are absent, as in Prometheus. type GroupKey = Vec<(Arc, Arc)>; diff --git a/src/promql/src/select/limit_cases.txt b/src/promql/src/select/limit_cases.txt new file mode 100644 index 00000000000..a9ab4a27208 --- /dev/null +++ b/src/promql/src/select/limit_cases.txt @@ -0,0 +1,1372 @@ +# Generated by promql-compat cmd/narthex-golden-vector built for amd64 (Prometheus v3.15.0 +# engine, seed 1, 120 cases per kind, -experimental limit). Each case lists its operation, the grid, the +# input series and either the result series or the error. Points are `grid index:hex bits`. +case limit limit_ratio NaN by __name__,host,job,zone +grid 100000 10000 6 +series __name__=a,host=h2,job=y ; 1:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 5:c079dc0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4078980000000000 2:406ad00000000000 3:c08b8e0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 4:c0795c0000000000 5:7ff8000000000001 +error Ratio value is NaN +end +case limit limit_ratio 0.9 by __name__,job,zone +grid 100000 10000 1 +series __name__=a,host=h1,job=y ; 0:408ab00000000000 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=y ; 0:4072120000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h1,job=y ; 0:c08d650000000000 +result __name__=a,host=h1,job=y ; 0:408ab00000000000 +result __name__=a,host=h2,job=y ; 0:4072120000000000 +result __name__=b,host=h1,job=y ; 0:c08d650000000000 +end +case limit limit_ratio -0.5 without __name__,host +grid 100000 10000 6 +series __name__=a,host=h2,job=y,zone=z1 ; 4:407fa60000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 5:fff0000000000000 +series __name__=a,host=h2,job=x ; 1:c0888a0000000000 3:407dfa0000000000 4:c089040000000000 5:c085460000000000 +series __name__=a,host=h1,job=x ; 0:4073480000000000 1:7e37e43c8800759c +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=y ; 2:407ad60000000000 +series __name__=b,host=h1,job=x ; 0:c068f40000000000 1:bff4000000000000 3:c0740c0000000000 4:403a200000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:7ff8000000000001 4:c08e530000000000 5:4072a60000000000 +result __name__=a,host=h2,job=x ; 1:c0888a0000000000 3:407dfa0000000000 4:c089040000000000 5:c085460000000000 +result __name__=b,host=h2,job=y ; 2:407ad60000000000 +end +case limit limit_ratio 0 by job,zone +grid 100000 10000 12 +series __name__=a,host=h2,job=x ; 1:c0631c0000000000 3:c08c910000000000 4:fff0000000000000 5:c077260000000000 6:c088fd0000000000 7:c07db40000000000 8:c0729c0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:c072a80000000000 5:4075700000000000 6:40833f0000000000 7:408c540000000000 8:4084b40000000000 9:c07c500000000000 +series __name__=a,host=h2,job=y ; 1:4051e80000000000 2:4063a40000000000 4:7ff0000000000000 6:c066a40000000000 9:c0886b0000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 6:407f680000000000 7:c08e6b0000000000 8:c08c900000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 10:407b8a0000000000 +series __name__=b,host=h2,job=y ; 0:406e800000000000 1:408bc00000000000 2:4052800000000000 4:4012000000000000 5:407e820000000000 +series __name__=b,host=h2,job=x ; +end +case limit limitk 0 without host +grid 100000 10000 9 +series __name__=a,host=h1,job=y,zone=z1 ; 5:c06a840000000000 6:fff0000000000000 7:7ff8000000000001 8:c074900000000000 +series __name__=a,host=h1,job=x ; 2:c08dde0000000000 3:c080f70000000000 5:c05b700000000000 7:7ff8000000000001 8:4080a70000000000 +series __name__=a,host=h2,job=y ; 5:c085a80000000000 8:c0616c0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 2:c087ad0000000000 3:c088cb0000000000 4:7e37e43c8800759c 5:c0893a0000000000 +series __name__=b,host=h1,job=x ; 6:c07bb20000000000 +end +case limit limit_ratio 1.5 by __name__,host,zone +grid 100000 10000 1 +series __name__=a,host=h2,job=y,zone=z1 ; 0:408db20000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:7ff8000000000001 +series __name__=a,host=h1,job=x ; 0:c089610000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:c052300000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 0:c075de0000000000 +result __name__=a,host=h1,job=x ; 0:c089610000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:7ff8000000000001 +result __name__=a,host=h2,job=y,zone=z1 ; 0:408db20000000000 +result __name__=b,host=h1,job=x,zone=z2 ; 0:c075de0000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 0:c052300000000000 +end +case limit limitk -1 without __name__,host,job,zone +grid 100000 10000 10 +series __name__=a,host=h2,job=y,zone=z1 ; 0:c07e160000000000 2:c085d60000000000 3:406b840000000000 4:7ff0000000000000 5:c085140000000000 +series __name__=a,host=h2,job=x ; 9:4089a80000000000 +series __name__=a,host=h1,job=y ; 5:408dda0000000000 +series __name__=a,host=h1,job=x ; 3:c0872d0000000000 4:4083600000000000 +series __name__=b,host=h2,job=y ; 7:4054500000000000 +series __name__=b,host=h1,job=y ; 7:4072080000000000 8:4073880000000000 +end +case limit limitk 0 without host +grid 100000 10000 7 +series __name__=a,host=h1,job=x ; 3:c07b340000000000 4:406ba00000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 4:4056f00000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 4:c08ac20000000000 +series __name__=a,host=h1,job=y ; 6:c050300000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:c047100000000000 2:c07cee0000000000 4:c08aab0000000000 5:c08cab0000000000 +series __name__=b,host=h1,job=y ; 0:c081500000000000 1:c080240000000000 2:c07ee00000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 5:fff0000000000000 6:c0878c0000000000 +end +case limit limitk 0 none - +grid 100000 10000 5 +series __name__=a,host=h1,job=y ; 0:c075a00000000000 +series __name__=b,host=h1,job=y ; 2:4077a00000000000 +end +case limit limitk 1 by job +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; 0:402ac00000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 2:408f390000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:408c220000000000 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x ; 1:c069080000000000 2:4071920000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:4072a60000000000 1:408eae0000000000 2:c089030000000000 +series __name__=b,host=h2,job=x ; 2:407d1a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:4080690000000000 2:408bb80000000000 +series __name__=b,host=h1,job=y ; 1:c08f1e0000000000 2:c086590000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:7ff0000000000000 1:4081dd0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 0:408ece0000000000 1:4056880000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 2:408f390000000000 +result __name__=a,host=h2,job=x ; 2:4071920000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 1:408c220000000000 +result __name__=a,host=h2,job=y ; 0:402ac00000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 1:408eae0000000000 +result __name__=b,host=h2,job=x,zone=z2 ; 0:408ece0000000000 +end +case limit limit_ratio 0.5 none - +grid 100000 10000 7 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=y,zone=z1 ; 0:408d360000000000 1:4089930000000000 2:c083d70000000000 3:4078200000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 6:c08df90000000000 +series __name__=b,host=h2,job=y ; 5:4084890000000000 6:c08cc40000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 0:408d360000000000 1:4089930000000000 2:c083d70000000000 3:4078200000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 6:c08df90000000000 +end +case limit limitk 1.5 by host,job +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:4081210000000000 +series __name__=a,host=h2,job=x ; 0:4081dd0000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=x ; 0:c083b90000000000 +result __name__=a,host=h1,job=x ; 0:4081210000000000 +result __name__=a,host=h2,job=x ; 0:4081dd0000000000 +end +case limit limitk 1.5 without __name__,zone +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 6:4081d10000000000 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; 4:40793e0000000000 6:4087570000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c065fc0000000000 +series __name__=b,host=h1,job=x ; 6:40846d0000000000 7:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z1 ; +result __name__=a,host=h1,job=x ; 6:4081d10000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 4:40793e0000000000 6:4087570000000000 +result __name__=b,host=h1,job=x ; 7:7ff8000000000001 +result __name__=b,host=h2,job=x,zone=z1 ; 0:c065fc0000000000 +end +case limit limit_ratio 0.9 none - +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; 10:4073de0000000000 +series __name__=b,host=h2,job=y ; 7:406cc40000000000 +series __name__=b,host=h1,job=x ; 7:c06f500000000000 8:c08c310000000000 +result __name__=a,host=h2,job=y ; 10:4073de0000000000 +result __name__=b,host=h1,job=x ; 7:c06f500000000000 8:c08c310000000000 +result __name__=b,host=h2,job=y ; 7:406cc40000000000 +end +case limit limit_ratio 1 without zone +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 0:7e37e43c8800759c +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x ; 1:407e2a0000000000 +series __name__=b,host=h2,job=x ; 0:7ff0000000000000 1:408da70000000000 +series __name__=b,host=h1,job=y ; 0:c088c60000000000 +series __name__=b,host=h2,job=y ; 1:4081880000000000 +result __name__=a,host=h2,job=x ; 1:407e2a0000000000 +result __name__=a,host=h2,job=y ; 0:7e37e43c8800759c +result __name__=b,host=h1,job=y ; 0:c088c60000000000 +result __name__=b,host=h2,job=x ; 0:7ff0000000000000 1:408da70000000000 +result __name__=b,host=h2,job=y ; 1:4081880000000000 +end +case limit limitk 0 without host,job,zone +grid 100000 10000 10 +series __name__=a,host=h2,job=x,zone=z1 ; 4:c087520000000000 5:4064540000000000 6:40879c0000000000 7:0 8:4082580000000000 +series __name__=a,host=h1,job=y ; 8:c088640000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c052f80000000000 1:c0709c0000000000 3:c08e060000000000 4:4079680000000000 5:c061200000000000 6:c077520000000000 7:40822a0000000000 9:4079ea0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:c071ec0000000000 +series __name__=b,host=h2,job=x ; 0:c08de50000000000 1:c08d6e0000000000 3:c08d530000000000 +end +case limit limit_ratio -0.5 by host +grid 100000 10000 12 +series __name__=a,host=h1,job=y ; 3:7ff8000000000001 4:c089990000000000 6:c066800000000000 +series __name__=a,host=h2,job=y ; 1:7ff0000000000000 3:407d4e0000000000 4:c07cfa0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 6:c086c20000000000 +series __name__=a,host=h1,job=x ; 8:4081ca0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 4:4085720000000000 5:c08a4a0000000000 +result __name__=a,host=h1,job=y ; 3:7ff8000000000001 4:c089990000000000 6:c066800000000000 +result __name__=a,host=h2,job=y ; 1:7ff0000000000000 3:407d4e0000000000 4:c07cfa0000000000 +end +case limit limitk -1 none - +grid 100000 10000 9 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4089b40000000000 2:c07a7c0000000000 4:c041400000000000 5:4086be0000000000 7:4084730000000000 8:c06be80000000000 +series __name__=a,host=h1,job=y ; 0:0 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=y,zone=z2 ; 3:4084c10000000000 4:c072220000000000 5:c06cb00000000000 6:7ff8000000000001 7:4055200000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 3:7ff8000000000001 4:c04c300000000000 6:c0820b0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; +end +case limit limitk 3 none - +grid 100000 10000 6 +series __name__=a,host=h2,job=x,zone=z1 ; 3:408b9d0000000000 4:fff0000000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:40837b0000000000 2:40680c0000000000 4:404f600000000000 +series __name__=b,host=h2,job=x ; 2:4087400000000000 3:c083360000000000 4:c07fd40000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 3:408b9d0000000000 4:fff0000000000000 +result __name__=b,host=h2,job=x ; 2:4087400000000000 3:c083360000000000 4:c07fd40000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 1:40837b0000000000 2:40680c0000000000 4:404f600000000000 +end +case limit limit_ratio 0.5 without __name__ +grid 100000 10000 4 +series __name__=a,host=h1,job=x ; 2:407fae0000000000 +series __name__=b,host=h1,job=x ; 0:c072d40000000000 +result __name__=a,host=h1,job=x ; 2:407fae0000000000 +result __name__=b,host=h1,job=x ; 0:c072d40000000000 +end +case limit limit_ratio -0.5 without __name__,job +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 0:408d630000000000 +series __name__=b,host=h2,job=y ; 1:7ff0000000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 1:4071840000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:0 +result __name__=a,host=h2,job=y ; 0:408d630000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 1:0 +result __name__=b,host=h2,job=y ; 1:7ff0000000000000 +end +case limit limit_ratio 0.3 none - +grid 100000 10000 4 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x ; 3:7e37e43c8800759c +series __name__=a,host=h1,job=x ; 2:c083650000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:4081e50000000000 +series __name__=b,host=h1,job=x ; 0:40852b0000000000 1:4058780000000000 +series __name__=b,host=h2,job=x ; 3:7ff8000000000001 +series __name__=b,host=h2,job=x,zone=z2 ; 3:c0810c0000000000 +result __name__=b,host=h1,job=x ; 0:40852b0000000000 1:4058780000000000 +result __name__=b,host=h2,job=x ; 3:7ff8000000000001 +end +case limit limitk 1.5 none - +grid 100000 10000 10 +series __name__=a,host=h1,job=x,zone=z1 ; 7:7ff8000000000001 9:c076960000000000 +series __name__=a,host=h2,job=x ; 4:7ff0000000000000 5:407aaa0000000000 +series __name__=a,host=h2,job=y ; 6:c088eb0000000000 +series __name__=b,host=h2,job=x ; 4:c075060000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 8:405dd80000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 7:7ff8000000000001 9:c076960000000000 +result __name__=a,host=h2,job=x ; 4:7ff0000000000000 5:407aaa0000000000 +result __name__=a,host=h2,job=y ; 6:c088eb0000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 8:405dd80000000000 +end +case limit limit_ratio 1.5 none - +grid 100000 10000 9 +series __name__=a,host=h2,job=y ; 4:c073ae0000000000 +series __name__=a,host=h2,job=x ; 6:fff0000000000000 7:c087ff0000000000 +series __name__=a,host=h1,job=x ; 3:4062fc0000000000 4:7ff8000000000001 5:c08bc10000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 7:c08a6e0000000000 8:408a5d0000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=x ; 7:7e37e43c8800759c +result __name__=a,host=h1,job=x ; 3:4062fc0000000000 4:7ff8000000000001 5:c08bc10000000000 +result __name__=a,host=h2,job=x ; 6:fff0000000000000 7:c087ff0000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 7:c08a6e0000000000 8:408a5d0000000000 +result __name__=a,host=h2,job=y ; 4:c073ae0000000000 +result __name__=b,host=h1,job=x ; 7:7e37e43c8800759c +end +case limit limit_ratio -0.5 none - +grid 100000 10000 11 +series __name__=a,host=h2,job=x ; 0:40802b0000000000 1:c087bb0000000000 3:c079d00000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 9:408e5e0000000000 10:4087c30000000000 +series __name__=b,host=h2,job=x ; 5:4076820000000000 6:4051700000000000 7:7ff8000000000001 +result __name__=a,host=h2,job=x ; 0:40802b0000000000 1:c087bb0000000000 3:c079d00000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 9:408e5e0000000000 10:4087c30000000000 +end +case limit limitk 2 without - +grid 100000 10000 2 +series __name__=a,host=h1,job=x ; 1:c081900000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +series __name__=b,host=h1,job=x ; 1:c084590000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 1:c0825e0000000000 +series __name__=b,host=h1,job=y ; 1:c0773a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4084d70000000000 +result __name__=a,host=h1,job=x ; 1:c081900000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +result __name__=b,host=h1,job=x ; 1:c084590000000000 +result __name__=b,host=h1,job=x,zone=z2 ; 1:c0825e0000000000 +result __name__=b,host=h1,job=y ; 1:c0773a0000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:4084d70000000000 +end +case limit limit_ratio 1.5 by job +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; 0:c077d80000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c077a40000000000 +series __name__=a,host=h1,job=x ; 0:405d880000000000 +series __name__=b,host=h2,job=y ; 0:c0883e0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 0:c086890000000000 +result __name__=a,host=h1,job=x ; 0:405d880000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 0:c077a40000000000 +result __name__=a,host=h2,job=y ; 0:c077d80000000000 +result __name__=b,host=h1,job=x,zone=z2 ; 0:c086890000000000 +result __name__=b,host=h2,job=y ; 0:c0883e0000000000 +end +case limit limit_ratio 0 none - +grid 100000 10000 3 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z2 ; 1:4076880000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:c081500000000000 +series __name__=b,host=h2,job=x ; +end +case limit limit_ratio 0 without job +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 7:c07e260000000000 +series __name__=a,host=h1,job=y ; 2:c080820000000000 3:0 4:c082c60000000000 5:405e980000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 4:c08e6a0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:40735e0000000000 +series __name__=b,host=h2,job=y ; 5:c06e2c0000000000 6:7ff0000000000000 +series __name__=b,host=h1,job=y ; 4:7ff8000000000001 +end +case limit limit_ratio NaN without host,job,zone +grid 100000 10000 11 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h2,job=x ; 0:4089af0000000000 1:c088900000000000 2:405aa80000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:4078d20000000000 7:4084890000000000 8:40683c0000000000 9:4087510000000000 10:c086f20000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c063240000000000 2:7e37e43c8800759c 3:4063c80000000000 4:4072c60000000000 +series __name__=b,host=h2,job=x ; 10:4083e60000000000 +error Ratio value is NaN +end +case limit limit_ratio NaN without host,job,zone +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; 8:4084880000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 6:c06fb80000000000 7:c07ba40000000000 +series __name__=b,host=h2,job=y ; 7:7ff8000000000001 8:40853c0000000000 10:c0821e0000000000 +error Ratio value is NaN +end +case limit limit_ratio -1 without job +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 3:7ff8000000000001 4:407cfa0000000000 5:407b9e0000000000 +series __name__=a,host=h2,job=x ; 6:0 +series __name__=a,host=h2,job=y,zone=z1 ; 2:40837e0000000000 +series __name__=a,host=h2,job=y ; 2:c082630000000000 3:c06bb80000000000 4:4082e10000000000 +series __name__=b,host=h2,job=y,zone=z1 ; +series __name__=b,host=h2,job=x ; 1:c0899f0000000000 3:40853d0000000000 4:4089390000000000 5:408e4a0000000000 6:7e37e43c8800759c +result __name__=a,host=h1,job=y,zone=z1 ; 3:7ff8000000000001 4:407cfa0000000000 5:407b9e0000000000 +result __name__=a,host=h2,job=x ; 6:0 +result __name__=a,host=h2,job=y ; 2:c082630000000000 3:c06bb80000000000 4:4082e10000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 2:40837e0000000000 +result __name__=b,host=h2,job=x ; 1:c0899f0000000000 3:40853d0000000000 4:4089390000000000 5:408e4a0000000000 6:7e37e43c8800759c +end +case limit limitk NaN by __name__,host,job,zone +grid 100000 10000 1 +series __name__=a,host=h1,job=y ; 0:407a180000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c085b70000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:4076400000000000 +series __name__=b,host=h1,job=y ; 0:4073d40000000000 +series __name__=b,host=h2,job=y ; +error Parameter value is NaN +end +case limit limit_ratio -0.3 by host +grid 100000 10000 6 +series __name__=a,host=h1,job=y,zone=z1 ; 0:7ff8000000000001 1:c088480000000000 2:4081130000000000 +series __name__=a,host=h2,job=y ; 0:4082da0000000000 1:4089250000000000 2:c08f260000000000 3:4081ba0000000000 4:c086560000000000 5:40868c0000000000 +series __name__=b,host=h2,job=y ; 3:c0858b0000000000 4:c085d50000000000 +series __name__=b,host=h1,job=y ; 4:c0870e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:4084e20000000000 2:c084150000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 1:4084e20000000000 2:c084150000000000 +end +case limit limit_ratio 0 none - +grid 100000 10000 9 +series __name__=a,host=h2,job=y,zone=z1 ; 8:4060000000000000 +series __name__=a,host=h1,job=x ; 6:c066380000000000 7:7ff8000000000001 +series __name__=a,host=h2,job=x ; 3:c067700000000000 4:fff0000000000000 6:408a7c0000000000 7:407d960000000000 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=x,zone=z1 ; 3:407d940000000000 4:7ff8000000000001 +series __name__=b,host=h2,job=y,zone=z1 ; +series __name__=b,host=h1,job=x,zone=z1 ; 2:c056080000000000 3:408e490000000000 4:c042c00000000000 5:c053a80000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 6:c086520000000000 7:400a000000000000 8:c086fd0000000000 +series __name__=b,host=h1,job=x ; 8:c06ff40000000000 +end +case limit limitk 0 none - +grid 100000 10000 8 +series __name__=a,host=h2,job=x ; 6:4076cc0000000000 7:c066800000000000 +series __name__=b,host=h2,job=x ; 1:c0842b0000000000 2:c08df50000000000 3:4088430000000000 5:c08b9a0000000000 6:c0789e0000000000 +end +case limit limit_ratio 0.9 by __name__ +grid 100000 10000 8 +series __name__=a,host=h2,job=x ; 5:0 +series __name__=a,host=h2,job=y,zone=z1 ; 2:c063f00000000000 3:4077140000000000 4:4049d00000000000 5:c080600000000000 +series __name__=b,host=h2,job=x ; 1:4089270000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:c055e00000000000 3:c067d40000000000 +result __name__=a,host=h2,job=x ; 5:0 +result __name__=a,host=h2,job=y,zone=z1 ; 2:c063f00000000000 3:4077140000000000 4:4049d00000000000 5:c080600000000000 +result __name__=b,host=h2,job=x ; 1:4089270000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 1:c055e00000000000 3:c067d40000000000 +end +case limit limitk 3 none - +grid 100000 10000 8 +series __name__=a,host=h2,job=y,zone=z1 ; 7:408a630000000000 +series __name__=a,host=h2,job=y ; 5:c072620000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h1,job=y ; 0:4042000000000000 +series __name__=b,host=h1,job=x ; 1:408d840000000000 2:c082d80000000000 3:7ff8000000000001 +series __name__=b,host=h2,job=x ; 4:c07db20000000000 6:407a220000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:407aba0000000000 3:c06ef40000000000 4:c083b40000000000 5:405c680000000000 6:c087080000000000 +result __name__=a,host=h1,job=y ; 0:4042000000000000 +result __name__=a,host=h2,job=y ; 5:c072620000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 7:408a630000000000 +result __name__=b,host=h1,job=x ; 1:408d840000000000 2:c082d80000000000 3:7ff8000000000001 +result __name__=b,host=h2,job=x ; 4:c07db20000000000 6:407a220000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 2:407aba0000000000 3:c06ef40000000000 4:c083b40000000000 5:405c680000000000 6:c087080000000000 +end +case limit limitk 3 none - +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 1:c062f40000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h2,job=x,zone=z1 ; 0:c082e80000000000 1:c064680000000000 +series __name__=a,host=h2,job=x ; 0:c074e60000000000 +series __name__=a,host=h1,job=y ; 1:c0851b0000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h2,job=x,zone=z1 ; 0:c072ae0000000000 +series __name__=b,host=h2,job=y ; 1:c080e90000000000 +result __name__=a,host=h1,job=y ; 1:c0851b0000000000 +result __name__=a,host=h2,job=x ; 0:c074e60000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:c082e80000000000 1:c064680000000000 +result __name__=a,host=h2,job=y ; 1:c062f40000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:c072ae0000000000 +end +case limit limit_ratio -0.5 by host +grid 100000 10000 7 +series __name__=a,host=h2,job=x,zone=z1 ; 2:406aa00000000000 +series __name__=a,host=h1,job=y ; 3:4066a00000000000 4:c086b20000000000 5:407e0c0000000000 +series __name__=b,host=h1,job=y ; 0:407aac0000000000 1:c077080000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 6:c065600000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:4051380000000000 +series __name__=b,host=h1,job=y,zone=z2 ; +result __name__=a,host=h1,job=y ; 3:4066a00000000000 4:c086b20000000000 5:407e0c0000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 2:406aa00000000000 +end +case limit limitk 2 none - +grid 100000 10000 9 +series __name__=a,host=h2,job=x ; 4:c08e180000000000 5:7e37e43c8800759c +series __name__=a,host=h1,job=x ; 6:c0830b0000000000 7:4089e80000000000 +series __name__=a,host=h2,job=y ; 0:4083010000000000 1:c066640000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 6:40862c0000000000 +series __name__=a,host=h1,job=y ; 3:4077840000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 6:406be00000000000 +series __name__=b,host=h1,job=y ; 7:4055a80000000000 +series __name__=b,host=h2,job=y ; 2:c073aa0000000000 3:c077f00000000000 4:4083630000000000 +result __name__=a,host=h1,job=x ; 6:c0830b0000000000 7:4089e80000000000 +result __name__=a,host=h1,job=y ; 3:4077840000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 6:40862c0000000000 +result __name__=a,host=h2,job=x ; 4:c08e180000000000 5:7e37e43c8800759c +result __name__=a,host=h2,job=y ; 0:4083010000000000 1:c066640000000000 +result __name__=b,host=h1,job=y ; 7:4055a80000000000 +result __name__=b,host=h2,job=y ; 2:c073aa0000000000 3:c077f00000000000 4:4083630000000000 +end +case limit limitk 1.5 without __name__ +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; 0:7ff8000000000001 +series __name__=b,host=h1,job=x ; 0:c08a990000000000 +series __name__=b,host=h2,job=y ; 0:c06b000000000000 +result __name__=a,host=h2,job=y ; 0:7ff8000000000001 +result __name__=b,host=h1,job=x ; 0:c08a990000000000 +end +case limit limitk -1 by __name__,host +grid 100000 10000 4 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x ; 1:c07ea20000000000 2:0 3:c086e10000000000 +series __name__=a,host=h1,job=x ; 2:7ff8000000000001 3:405e680000000000 +series __name__=a,host=h2,job=y ; 3:403cc00000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c052d00000000000 2:4087d80000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=x ; 1:407f180000000000 2:408b490000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:4088240000000000 1:4084e00000000000 2:c07a960000000000 3:c069a00000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4044100000000000 1:c065880000000000 2:407e0e0000000000 +series __name__=b,host=h1,job=x ; 3:c052d80000000000 +end +case limit limit_ratio 1 by host,job +grid 100000 10000 2 +series __name__=a,host=h1,job=x ; 1:407dc40000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 1:7ff8000000000001 +series __name__=b,host=h1,job=x ; 0:c087820000000000 +series __name__=b,host=h2,job=y ; 0:0 +series __name__=b,host=h1,job=y,zone=z1 ; 1:c075940000000000 +series __name__=b,host=h1,job=y ; 1:c058f00000000000 +result __name__=a,host=h1,job=x ; 1:407dc40000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 1:7ff8000000000001 +result __name__=b,host=h1,job=x ; 0:c087820000000000 +result __name__=b,host=h1,job=y ; 1:c058f00000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 1:c075940000000000 +result __name__=b,host=h2,job=y ; 0:0 +end +case limit limit_ratio -1 without - +grid 100000 10000 9 +series __name__=a,host=h1,job=y ; 8:40873f0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 3:c081420000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +result __name__=a,host=h1,job=x,zone=z1 ; 3:c081420000000000 +result __name__=a,host=h1,job=y ; 8:40873f0000000000 +end +case limit limitk NaN none - +grid 100000 10000 3 +series __name__=a,host=h1,job=y,zone=z1 ; 1:c08b070000000000 +series __name__=a,host=h2,job=y ; 2:7ff0000000000000 +series __name__=a,host=h1,job=x ; 2:c082330000000000 +series __name__=a,host=h1,job=y ; 1:c08b810000000000 +series __name__=b,host=h2,job=y ; 1:7e37e43c8800759c 2:fff0000000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:7ff8000000000001 2:4063080000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:4075660000000000 +error Parameter value is NaN +end +case limit limitk 10 none - +grid 100000 10000 9 +series __name__=a,host=h2,job=y ; 7:405b400000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 6:405dd00000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c077a60000000000 1:c08b2b0000000000 3:4089970000000000 +series __name__=b,host=h1,job=y ; 1:40833e0000000000 +series __name__=b,host=h2,job=y ; 4:407e480000000000 5:40752a0000000000 6:c020800000000000 7:c07bd60000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 8:c08f0f0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 6:405dd00000000000 +result __name__=a,host=h2,job=y ; 7:405b400000000000 +result __name__=b,host=h1,job=y ; 1:40833e0000000000 +result __name__=b,host=h1,job=y,zone=z2 ; 8:c08f0f0000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:c077a60000000000 1:c08b2b0000000000 3:4089970000000000 +result __name__=b,host=h2,job=y ; 4:407e480000000000 5:40752a0000000000 6:c020800000000000 7:c07bd60000000000 +end +case limit limit_ratio -1 without host,zone +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; 5:c075400000000000 6:c072600000000000 7:c05a900000000000 9:4089c90000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 7:406bd00000000000 +series __name__=b,host=h1,job=x ; 6:7e37e43c8800759c +result __name__=a,host=h1,job=x ; 5:c075400000000000 6:c072600000000000 7:c05a900000000000 9:4089c90000000000 +result __name__=b,host=h1,job=x ; 6:7e37e43c8800759c +result __name__=b,host=h2,job=x,zone=z1 ; 7:406bd00000000000 +end +case limit limit_ratio -0.5 by __name__ +grid 100000 10000 7 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c08e130000000000 1:c064700000000000 2:4087fc0000000000 +series __name__=a,host=h2,job=x ; 6:4086a20000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 3:7ff8000000000001 4:408a320000000000 +series __name__=a,host=h1,job=x ; 5:c047100000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 3:c07aee0000000000 4:c082470000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 5:c029000000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:c050f00000000000 1:405ca80000000000 +series __name__=b,host=h2,job=x ; 6:c087b20000000000 +result __name__=a,host=h2,job=x ; 6:4086a20000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:c08e130000000000 1:c064700000000000 2:4087fc0000000000 +end +case limit limit_ratio 0.3 none - +grid 100000 10000 1 +series __name__=a,host=h2,job=x ; 0:c089820000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c081140000000000 +series __name__=b,host=h1,job=y ; 0:7ff0000000000000 +series __name__=b,host=h2,job=x ; 0:c0721a0000000000 +result __name__=b,host=h2,job=x ; 0:c0721a0000000000 +end +case limit limit_ratio -1 none - +grid 100000 10000 3 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h1,job=y ; 1:7ff0000000000000 +series __name__=a,host=h1,job=x ; 1:c072800000000000 +series __name__=a,host=h2,job=y ; 2:7ff8000000000001 +series __name__=b,host=h2,job=y ; 1:c089740000000000 +series __name__=b,host=h1,job=x ; 0:c074c40000000000 1:c064b40000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:4082940000000000 +result __name__=a,host=h1,job=x ; 1:c072800000000000 +result __name__=a,host=h1,job=y ; 1:7ff0000000000000 +result __name__=a,host=h2,job=y ; 2:7ff8000000000001 +result __name__=b,host=h1,job=x ; 0:c074c40000000000 1:c064b40000000000 +result __name__=b,host=h2,job=y ; 1:c089740000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 2:4082940000000000 +end +case limit limitk 1.5 by host,zone +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 4:c0752c0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:0 +series __name__=a,host=h1,job=x ; 3:c07b360000000000 +series __name__=b,host=h1,job=x ; 4:7e37e43c8800759c +series __name__=b,host=h2,job=y ; 5:c062340000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 5:7ff0000000000000 +result __name__=a,host=h1,job=x ; 3:c07b360000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 0:0 +result __name__=a,host=h2,job=x ; 4:c0752c0000000000 +result __name__=b,host=h1,job=x ; 4:7e37e43c8800759c +result __name__=b,host=h2,job=y ; 5:c062340000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 5:7ff0000000000000 +end +case limit limit_ratio -1.5 none - +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=y ; 1:4084200000000000 2:c086690000000000 3:c070ec0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 2:0 +series __name__=b,host=h2,job=y,zone=z1 ; 3:404c700000000000 +series __name__=b,host=h2,job=x ; 0:4089990000000000 1:c08e120000000000 2:407da40000000000 +series __name__=b,host=h1,job=y ; 1:c064e00000000000 2:c07e260000000000 3:4060600000000000 +result __name__=a,host=h2,job=y ; 1:4084200000000000 2:c086690000000000 3:c070ec0000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 2:0 +result __name__=b,host=h1,job=y ; 1:c064e00000000000 2:c07e260000000000 3:4060600000000000 +result __name__=b,host=h2,job=x ; 0:4089990000000000 1:c08e120000000000 2:407da40000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 3:404c700000000000 +end +case limit limit_ratio 1 without host,zone +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; 10:c08d430000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c044500000000000 2:7ff0000000000000 3:4071940000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:c063c80000000000 1:c08b5f0000000000 3:c086c20000000000 4:c071e40000000000 5:c089450000000000 6:4084b40000000000 8:c0889c0000000000 9:c08e350000000000 10:c0751e0000000000 +series __name__=a,host=h2,job=x ; 3:c080850000000000 4:c08c210000000000 5:c087fc0000000000 6:408d490000000000 8:c046f00000000000 +series __name__=b,host=h1,job=y ; 6:c07a260000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 5:4073500000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 1:c044500000000000 2:7ff0000000000000 3:4071940000000000 +result __name__=a,host=h2,job=x ; 3:c080850000000000 4:c08c210000000000 5:c087fc0000000000 6:408d490000000000 8:c046f00000000000 +result __name__=a,host=h2,job=y ; 10:c08d430000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 0:c063c80000000000 1:c08b5f0000000000 3:c086c20000000000 4:c071e40000000000 5:c089450000000000 6:4084b40000000000 8:c0889c0000000000 9:c08e350000000000 10:c0751e0000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 5:4073500000000000 +result __name__=b,host=h1,job=y ; 6:c07a260000000000 +end +case limit limitk 1 none - +grid 100000 10000 4 +series __name__=a,host=h1,job=y,zone=z1 ; 3:4083510000000000 +series __name__=a,host=h1,job=y ; 1:4072ca0000000000 +series __name__=a,host=h2,job=y ; 3:c0852b0000000000 +series __name__=b,host=h2,job=y ; 0:0 1:fff0000000000000 2:7ff8000000000001 +series __name__=b,host=h1,job=y,zone=z1 ; 2:c08e8d0000000000 3:7ff8000000000001 +series __name__=b,host=h1,job=y ; 2:c07d680000000000 3:c0863f0000000000 +result __name__=a,host=h1,job=y ; 1:4072ca0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 3:4083510000000000 +result __name__=b,host=h2,job=y ; 0:0 2:7ff8000000000001 +end +case limit limit_ratio 0 by __name__,host,zone +grid 100000 10000 9 +series __name__=a,host=h2,job=x ; 4:c08cd80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 2:c063540000000000 3:40754e0000000000 4:4086db0000000000 5:c05ba80000000000 6:c052200000000000 7:4084fd0000000000 8:c059800000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:4071460000000000 2:4081220000000000 +series __name__=b,host=h2,job=x ; 2:4081560000000000 3:c07a380000000000 4:406b740000000000 5:407e520000000000 6:c08de10000000000 7:407b460000000000 +end +case limit limitk 1 without job +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 6:c04d200000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 6:c086770000000000 7:4082900000000000 +series __name__=a,host=h2,job=y ; 1:4061080000000000 2:7ff8000000000001 3:c08c200000000000 4:4082a60000000000 +series __name__=a,host=h1,job=y ; 5:c08a560000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 3:0 5:c07a8c0000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=y,zone=z1 ; 3:4071b60000000000 4:c046d00000000000 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h1,job=y,zone=z2 ; 6:c077980000000000 7:c0778a0000000000 +result __name__=a,host=h1,job=x ; 6:c04d200000000000 +result __name__=a,host=h1,job=y ; 5:c08a560000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 3:0 5:c07a8c0000000000 +result __name__=a,host=h2,job=y ; 1:4061080000000000 2:7ff8000000000001 3:c08c200000000000 4:4082a60000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 6:c086770000000000 7:4082900000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 4:c046d00000000000 +result __name__=b,host=h1,job=y,zone=z2 ; 6:c077980000000000 7:c0778a0000000000 +end +case limit limit_ratio 0.5 by host,job,zone +grid 100000 10000 4 +series __name__=a,host=h2,job=y ; 2:c075e40000000000 +series __name__=a,host=h1,job=y ; 2:4082130000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:408ac60000000000 1:4042d00000000000 2:c08daf0000000000 3:40736c0000000000 +series __name__=a,host=h2,job=x ; 1:7ff8000000000001 2:4085af0000000000 3:c074820000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:407d660000000000 1:40837d0000000000 +series __name__=b,host=h2,job=y ; 3:4084f00000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 0:408ac60000000000 1:4042d00000000000 2:c08daf0000000000 3:40736c0000000000 +end +case limit limit_ratio 0.3 without host +grid 100000 10000 11 +series __name__=a,host=h2,job=y,zone=z1 ; 10:4077ba0000000000 +series __name__=a,host=h1,job=y ; 0:408cce0000000000 1:408bd00000000000 3:4084330000000000 5:407ff00000000000 6:c0770a0000000000 7:fff0000000000000 8:7ff0000000000000 9:406ec40000000000 +series __name__=a,host=h2,job=x ; 4:7ff8000000000001 5:c06e840000000000 6:c088c20000000000 7:40813f0000000000 +series __name__=b,host=h1,job=x ; 2:4088940000000000 3:4040500000000000 4:c06d680000000000 5:408dd70000000000 6:c0894b0000000000 7:7e37e43c8800759c 9:4075060000000000 10:4086f40000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 9:40881f0000000000 10:4076bc0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 10:c085570000000000 +result __name__=b,host=h1,job=x ; 2:4088940000000000 3:4040500000000000 4:c06d680000000000 5:408dd70000000000 6:c0894b0000000000 7:7e37e43c8800759c 9:4075060000000000 10:4086f40000000000 +result __name__=b,host=h2,job=y,zone=z2 ; 9:40881f0000000000 10:4076bc0000000000 +end +case limit limit_ratio 1.5 none - +grid 100000 10000 8 +series __name__=a,host=h1,job=x,zone=z1 ; 3:4065f80000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 5:c08bd20000000000 6:408c3d0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:c08bb40000000000 7:408ccd0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:c08cea0000000000 5:c08d320000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:c08df70000000000 5:7ff8000000000001 6:c089d20000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c06d300000000000 3:40864f0000000000 5:407b0e0000000000 7:4089760000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 3:4065f80000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 4:c08bb40000000000 7:408ccd0000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 5:c08bd20000000000 6:408c3d0000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 4:c08cea0000000000 5:c08d320000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 3:c08df70000000000 5:7ff8000000000001 6:c089d20000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 2:c06d300000000000 3:40864f0000000000 5:407b0e0000000000 7:4089760000000000 +end +case limit limit_ratio 0.3 without - +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 3:c0864b0000000000 4:c06a080000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:4081db0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 5:4078fc0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c016000000000000 4:c06d140000000000 5:406bd40000000000 +series __name__=b,host=h2,job=x ; 0:7ff0000000000000 1:c083350000000000 2:c07be60000000000 3:408b590000000000 4:c083f50000000000 5:c088240000000000 +result __name__=b,host=h2,job=x ; 0:7ff0000000000000 1:c083350000000000 2:c07be60000000000 3:408b590000000000 4:c083f50000000000 5:c088240000000000 +end +case limit limitk NaN without __name__,job,zone +grid 100000 10000 5 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 3:40754e0000000000 +error Parameter value is NaN +end +case limit limitk 0 none - +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; 7:c04b400000000000 8:4085340000000000 9:c0742c0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 10:c08bc70000000000 +series __name__=a,host=h1,job=y ; 3:c088ea0000000000 4:4076660000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 10:7ff8000000000001 +series __name__=a,host=h2,job=x ; 0:406b0c0000000000 1:4087650000000000 +series __name__=b,host=h2,job=y ; 1:40805c0000000000 2:c085350000000000 3:c08ab20000000000 +series __name__=b,host=h1,job=x ; 2:40750a0000000000 3:7e37e43c8800759c 5:c06d440000000000 7:c036600000000000 8:4060e80000000000 9:c0845c0000000000 +series __name__=b,host=h2,job=x ; 7:c0812f0000000000 8:40846e0000000000 9:c080930000000000 +series __name__=b,host=h1,job=y ; 2:c079b40000000000 +end +case limit limit_ratio -1 by host +grid 100000 10000 6 +series __name__=a,host=h2,job=y ; 4:407c360000000000 +series __name__=a,host=h2,job=x ; 0:c081410000000000 1:c068180000000000 +series __name__=a,host=h1,job=y ; 2:4061d80000000000 3:4078c20000000000 +series __name__=b,host=h2,job=y ; 1:c089f60000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 1:c053d00000000000 2:4072180000000000 3:4072040000000000 +series __name__=b,host=h1,job=y ; 2:c082ac0000000000 3:c05e780000000000 +result __name__=a,host=h1,job=y ; 2:4061d80000000000 3:4078c20000000000 +result __name__=a,host=h2,job=x ; 0:c081410000000000 1:c068180000000000 +result __name__=a,host=h2,job=y ; 4:407c360000000000 +result __name__=b,host=h1,job=y ; 2:c082ac0000000000 3:c05e780000000000 +result __name__=b,host=h2,job=y ; 1:c089f60000000000 +result __name__=b,host=h2,job=y,zone=z2 ; 1:c053d00000000000 2:4072180000000000 3:4072040000000000 +end +case limit limitk 2 without host,job +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 3:c0879b0000000000 4:c07b4a0000000000 5:4085d90000000000 +series __name__=b,host=h2,job=y ; 4:7ff8000000000001 5:c063a80000000000 +result __name__=a,host=h2,job=y ; 3:c0879b0000000000 4:c07b4a0000000000 5:4085d90000000000 +result __name__=b,host=h2,job=y ; 4:7ff8000000000001 5:c063a80000000000 +end +case limit limit_ratio 0.9 none - +grid 100000 10000 3 +series __name__=a,host=h2,job=x,zone=z1 ; 1:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h1,job=x ; 2:4083010000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:7e37e43c8800759c 1:4085e60000000000 2:4074e00000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 1:c060ec0000000000 +series __name__=b,host=h1,job=x ; 1:408d5f0000000000 2:7ff8000000000001 +result __name__=a,host=h1,job=x ; 2:4083010000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 1:7ff8000000000001 +result __name__=b,host=h1,job=x ; 1:408d5f0000000000 2:7ff8000000000001 +result __name__=b,host=h1,job=y,zone=z1 ; 0:7e37e43c8800759c 1:4085e60000000000 2:4074e00000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 1:c060ec0000000000 +end +case limit limit_ratio 0.5 by host +grid 100000 10000 11 +series __name__=a,host=h1,job=x ; 8:0 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h2,job=y,zone=z1 ; 8:c072360000000000 9:4084ff0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 8:7ff8000000000001 10:c086d20000000000 +series __name__=b,host=h2,job=x ; 8:7ff0000000000000 9:c08a000000000000 10:c077c80000000000 +result __name__=a,host=h1,job=x ; 8:0 +result __name__=b,host=h1,job=x,zone=z1 ; 8:7ff8000000000001 10:c086d20000000000 +result __name__=b,host=h2,job=x ; 8:7ff0000000000000 9:c08a000000000000 10:c077c80000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 8:c072360000000000 9:4084ff0000000000 +end +case limit limit_ratio 0.5 without __name__ +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; 2:c07bd20000000000 3:c0692c0000000000 +series __name__=a,host=h1,job=y ; 3:4084de0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:407c320000000000 2:408e5a0000000000 3:c07be00000000000 +series __name__=a,host=h1,job=x ; 2:c0807f0000000000 3:4052480000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:c062280000000000 1:4081f80000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 3:408bdb0000000000 +result __name__=a,host=h1,job=x ; 2:c0807f0000000000 3:4052480000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 1:407c320000000000 2:408e5a0000000000 3:c07be00000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 0:c062280000000000 1:4081f80000000000 +end +case limit limitk 3 by __name__ +grid 100000 10000 2 +series __name__=a,host=h1,job=y,zone=z1 ; 1:7e37e43c8800759c +series __name__=b,host=h1,job=y,zone=z1 ; 1:c0816c0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 1:7e37e43c8800759c +result __name__=b,host=h1,job=y,zone=z1 ; 1:c0816c0000000000 +end +case limit limit_ratio -1.5 by host +grid 100000 10000 6 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x ; 4:c0862b0000000000 +series __name__=b,host=h1,job=x ; 2:7ff0000000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:4081a30000000000 +series __name__=b,host=h1,job=y ; 2:c080030000000000 +result __name__=a,host=h2,job=x ; 4:c0862b0000000000 +result __name__=b,host=h1,job=x ; 2:7ff0000000000000 +result __name__=b,host=h1,job=y ; 2:c080030000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 0:4081a30000000000 +end +case limit limitk 3 none - +grid 100000 10000 11 +series __name__=a,host=h2,job=x,zone=z1 ; 7:c070be0000000000 8:4079560000000000 9:7e37e43c8800759c +series __name__=a,host=h1,job=x ; 5:c089950000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4075ce0000000000 2:408a680000000000 4:4043800000000000 5:c068ec0000000000 6:4044200000000000 7:fff0000000000000 8:407e900000000000 +series __name__=b,host=h1,job=x ; 7:c06a280000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:407ed20000000000 3:c07a5e0000000000 4:7ff0000000000000 6:c08e910000000000 +result __name__=a,host=h1,job=x ; 5:c089950000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 1:4075ce0000000000 2:408a680000000000 4:4043800000000000 5:c068ec0000000000 6:4044200000000000 7:fff0000000000000 8:407e900000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 7:c070be0000000000 8:4079560000000000 9:7e37e43c8800759c +result __name__=b,host=h1,job=x ; 7:c06a280000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 1:407ed20000000000 3:c07a5e0000000000 4:7ff0000000000000 6:c08e910000000000 +end +case limit limitk 2 none - +grid 100000 10000 4 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; 0:4068d80000000000 2:c06c540000000000 3:c08f070000000000 +series __name__=a,host=h2,job=x ; 0:407e180000000000 +series __name__=a,host=h1,job=y ; 0:c086600000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:408a2d0000000000 2:4064d00000000000 3:c087510000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 3:4064f00000000000 +result __name__=a,host=h2,job=x ; 0:407e180000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:4068d80000000000 2:c06c540000000000 3:c08f070000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 1:408a2d0000000000 2:4064d00000000000 3:c087510000000000 +end +case limit limitk -1 by __name__,zone +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 4:4051e00000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:408bf60000000000 1:407acc0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 5:4076c80000000000 +series __name__=b,host=h2,job=y ; 3:c063f00000000000 4:c07aa20000000000 +end +case limit limitk 3 without host,zone +grid 100000 10000 3 +series __name__=a,host=h1,job=y ; 0:4079fc0000000000 1:4087970000000000 2:407aaa0000000000 +series __name__=a,host=h1,job=x ; 2:4050c00000000000 +series __name__=b,host=h1,job=y ; 1:40888f0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:7ff8000000000001 2:c089030000000000 +result __name__=a,host=h1,job=x ; 2:4050c00000000000 +result __name__=a,host=h1,job=y ; 0:4079fc0000000000 1:4087970000000000 2:407aaa0000000000 +result __name__=b,host=h1,job=y ; 1:40888f0000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 1:7ff8000000000001 2:c089030000000000 +end +case limit limitk 10 none - +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; 3:406f140000000000 4:40723e0000000000 5:c05c300000000000 6:4085570000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:4074080000000000 1:c075020000000000 2:c08def0000000000 4:0 5:7ff8000000000001 6:4068d00000000000 +series __name__=a,host=h2,job=y ; 9:c084020000000000 +series __name__=b,host=h2,job=y ; 6:40718c0000000000 7:c08efe0000000000 +series __name__=b,host=h1,job=x ; 3:c08df70000000000 4:404a500000000000 5:c08ed00000000000 6:4083640000000000 +result __name__=a,host=h1,job=x ; 3:406f140000000000 4:40723e0000000000 5:c05c300000000000 6:4085570000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:4074080000000000 1:c075020000000000 2:c08def0000000000 4:0 5:7ff8000000000001 6:4068d00000000000 +result __name__=a,host=h2,job=y ; 9:c084020000000000 +result __name__=b,host=h1,job=x ; 3:c08df70000000000 4:404a500000000000 5:c08ed00000000000 6:4083640000000000 +result __name__=b,host=h2,job=y ; 6:40718c0000000000 7:c08efe0000000000 +end +case limit limitk 10 without host +grid 100000 10000 1 +series __name__=a,host=h1,job=y ; 0:40858b0000000000 +series __name__=a,host=h1,job=x ; 0:0 +series __name__=a,host=h2,job=x ; 0:c080310000000000 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; 0:7e37e43c8800759c +series __name__=a,host=h2,job=y,zone=z1 ; 0:4083970000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:4085320000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4085340000000000 +result __name__=a,host=h1,job=x ; 0:0 +result __name__=a,host=h1,job=y ; 0:40858b0000000000 +result __name__=a,host=h2,job=x ; 0:c080310000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:7e37e43c8800759c +result __name__=a,host=h2,job=y,zone=z1 ; 0:4083970000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:4085340000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 0:4085320000000000 +end +case limit limitk 3 by __name__,job +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c075a20000000000 1:c082bc0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 4:c0878f0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 0:c075a20000000000 1:c082bc0000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 4:c0878f0000000000 +end +case limit limitk 2 by __name__,zone +grid 100000 10000 11 +series __name__=a,host=h1,job=y,zone=z1 ; 5:40830d0000000000 6:407bfa0000000000 7:4085050000000000 +series __name__=a,host=h2,job=x ; 1:405fb00000000000 3:4083340000000000 5:c089590000000000 6:4081250000000000 7:7ff8000000000001 +series __name__=a,host=h1,job=x ; 2:4033400000000000 3:c074020000000000 4:4070220000000000 5:c085a90000000000 6:c08ccc0000000000 8:4029c00000000000 +series __name__=a,host=h1,job=y ; 8:c061c80000000000 9:4087c30000000000 10:4079940000000000 +series __name__=a,host=h2,job=y ; 9:c080c00000000000 10:7ff0000000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 3:c07e520000000000 4:40771c0000000000 5:c072e00000000000 6:40891a0000000000 7:c073300000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c066780000000000 4:c08c940000000000 5:c080ca0000000000 6:40844f0000000000 7:4079d80000000000 +result __name__=a,host=h1,job=x ; 2:4033400000000000 3:c074020000000000 4:4070220000000000 5:c085a90000000000 6:c08ccc0000000000 8:4029c00000000000 +result __name__=a,host=h1,job=y ; 8:c061c80000000000 9:4087c30000000000 10:4079940000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 5:40830d0000000000 6:407bfa0000000000 7:4085050000000000 +result __name__=a,host=h2,job=x ; 1:405fb00000000000 3:4083340000000000 5:c089590000000000 6:4081250000000000 7:7ff8000000000001 +result __name__=a,host=h2,job=y ; 9:c080c00000000000 10:7ff0000000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 3:c07e520000000000 4:40771c0000000000 5:c072e00000000000 6:40891a0000000000 7:c073300000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 2:c066780000000000 4:c08c940000000000 5:c080ca0000000000 6:40844f0000000000 7:4079d80000000000 +end +case limit limit_ratio NaN none - +grid 100000 10000 8 +series __name__=a,host=h1,job=x,zone=z1 ; 4:c027400000000000 5:c075cc0000000000 +series __name__=a,host=h1,job=x ; 5:c08a8f0000000000 6:4089760000000000 7:c08d7c0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 3:407f020000000000 4:0 6:c08d7d0000000000 +series __name__=a,host=h2,job=x ; 5:7ff0000000000000 6:408a740000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=x ; 5:4073ce0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 6:40859b0000000000 +error Ratio value is NaN +end +case limit limitk 3 by __name__,host +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; 2:4082250000000000 3:4084e80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=y ; 1:7e37e43c8800759c 2:4086f20000000000 3:c076c20000000000 4:4087440000000000 +series __name__=a,host=h1,job=x ; 3:c07de20000000000 4:c076540000000000 +series __name__=b,host=h1,job=y ; 4:4077240000000000 +series __name__=b,host=h2,job=y ; 0:40746c0000000000 1:0 2:4076260000000000 3:c0824e0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:c042200000000000 1:4069ac0000000000 2:408d5a0000000000 3:c0746e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:c067c80000000000 +series __name__=b,host=h1,job=x ; 4:7ff8000000000001 +result __name__=a,host=h1,job=x ; 3:c07de20000000000 4:c076540000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 2:4082250000000000 3:4084e80000000000 +result __name__=a,host=h2,job=y ; 1:7e37e43c8800759c 2:4086f20000000000 3:c076c20000000000 4:4087440000000000 +result __name__=b,host=h1,job=x ; 4:7ff8000000000001 +result __name__=b,host=h1,job=y ; 4:4077240000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 0:c067c80000000000 +result __name__=b,host=h1,job=y,zone=z2 ; 0:c042200000000000 1:4069ac0000000000 2:408d5a0000000000 3:c0746e0000000000 +result __name__=b,host=h2,job=y ; 0:40746c0000000000 1:0 2:4076260000000000 3:c0824e0000000000 +end +case limit limitk 1 without host +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 6:0 +series __name__=a,host=h2,job=y ; 5:c086680000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:c087a30000000000 +series __name__=b,host=h2,job=x ; 2:7ff8000000000001 3:c080290000000000 4:c0890f0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 4:c065440000000000 +result __name__=a,host=h2,job=x ; 6:0 +result __name__=a,host=h2,job=x,zone=z1 ; 6:c087a30000000000 +result __name__=a,host=h2,job=y ; 5:c086680000000000 +result __name__=b,host=h2,job=x ; 2:7ff8000000000001 3:c080290000000000 4:c0890f0000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 4:c065440000000000 +end +case limit limitk 0 without - +grid 100000 10000 3 +series __name__=a,host=h2,job=x ; 1:c061f80000000000 2:c07ada0000000000 +series __name__=a,host=h2,job=y ; 1:c048a00000000000 2:c06b2c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=x,zone=z1 ; 0:4063140000000000 +series __name__=b,host=h2,job=x ; 1:408d090000000000 2:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 0:408e0f0000000000 1:c081700000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4076ac0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:407bda0000000000 2:c070240000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 2:407e180000000000 +end +case limit limitk NaN by __name__,job +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; 3:7ff8000000000001 +series __name__=a,host=h1,job=x ; 2:c08d430000000000 3:c06a4c0000000000 4:7ff8000000000001 +series __name__=b,host=h1,job=x ; 3:fff0000000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h2,job=x ; 0:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z2 ; 1:407d200000000000 2:c08ea90000000000 +error Parameter value is NaN +end +case limit limit_ratio 1.5 without __name__,host,zone +grid 100000 10000 5 +series __name__=a,host=h2,job=y,zone=z1 ; 4:4065840000000000 +series __name__=a,host=h1,job=x ; 2:c060180000000000 3:7ff0000000000000 +series __name__=a,host=h1,job=y ; 0:4081400000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 3:406d3c0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:4078ba0000000000 +result __name__=a,host=h1,job=x ; 2:c060180000000000 3:7ff0000000000000 +result __name__=a,host=h1,job=y ; 0:4081400000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 4:4065840000000000 +result __name__=b,host=h1,job=x,zone=z2 ; 3:406d3c0000000000 +result __name__=b,host=h2,job=y,zone=z1 ; 2:4078ba0000000000 +end +case limit limitk 0 none - +grid 100000 10000 10 +series __name__=a,host=h1,job=x,zone=z1 ; 2:c05dd00000000000 5:0 7:4080880000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:c080550000000000 +series __name__=b,host=h2,job=y ; 5:40888d0000000000 6:4078de0000000000 7:4084d60000000000 8:4071940000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 2:404cf00000000000 +series __name__=b,host=h1,job=y ; 7:407e3c0000000000 8:40834f0000000000 +end +case limit limit_ratio -0.5 by host +grid 100000 10000 9 +series __name__=a,host=h1,job=y,zone=z1 ; 5:40824d0000000000 6:4080070000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 7:fff0000000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h2,job=x ; 1:40839f0000000000 2:406d2c0000000000 3:408b070000000000 4:c045400000000000 5:7e37e43c8800759c 6:c074620000000000 +series __name__=b,host=h1,job=y ; 1:405f580000000000 2:c070e20000000000 +series __name__=b,host=h2,job=x ; 4:c0800e0000000000 5:4084af0000000000 6:408f0a0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 5:c0801e0000000000 +result __name__=a,host=h2,job=x ; 1:40839f0000000000 2:406d2c0000000000 3:408b070000000000 4:c045400000000000 5:7e37e43c8800759c 6:c074620000000000 +end +case limit limitk 1.5 without - +grid 100000 10000 9 +series __name__=a,host=h1,job=x,zone=z1 ; 6:c084e10000000000 7:40700e0000000000 8:c08e210000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 7:c076fc0000000000 8:c057680000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 6:c084e10000000000 7:40700e0000000000 8:c08e210000000000 +end +case limit limit_ratio -1.5 without __name__,job +grid 100000 10000 11 +series __name__=a,host=h2,job=x ; 9:408d0c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c054980000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=x,zone=z1 ; 2:4051500000000000 3:7e37e43c8800759c 4:407f160000000000 5:c063700000000000 8:c08efb0000000000 9:4062640000000000 10:7ff8000000000001 +result __name__=a,host=h2,job=x ; 9:408d0c0000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 1:c054980000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 2:4051500000000000 3:7e37e43c8800759c 4:407f160000000000 5:c063700000000000 8:c08efb0000000000 9:4062640000000000 10:7ff8000000000001 +end +case limit limit_ratio NaN without host +grid 100000 10000 3 +series __name__=a,host=h2,job=x ; 2:4061c00000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h2,job=y ; +series __name__=b,host=h1,job=x ; 2:4030800000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 0:0 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c075fa0000000000 +error Ratio value is NaN +end +case limit limitk 3 none - +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:c049000000000000 +series __name__=a,host=h1,job=y ; 0:c08e380000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:0 +series __name__=a,host=h2,job=y ; 0:c05c080000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:c0759e0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4058200000000000 +series __name__=b,host=h2,job=y,zone=z1 ; +series __name__=b,host=h1,job=y,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +series __name__=b,host=h1,job=x,zone=z2 ; +result __name__=a,host=h1,job=x ; 0:c049000000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 0:0 +result __name__=a,host=h1,job=y ; 0:c08e380000000000 +end +case limit limit_ratio -0.3 by host,zone +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; 3:c08e960000000000 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h1,job=x ; 1:0 +series __name__=a,host=h2,job=y ; 1:c07e320000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 2:c06a800000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c080d50000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 2:40699c0000000000 +series __name__=b,host=h2,job=y ; 3:c066640000000000 +series __name__=b,host=h1,job=x ; 1:c07e960000000000 3:c08ad70000000000 +result __name__=a,host=h2,job=x ; 3:c08e960000000000 +end +case limit limit_ratio 0.3 by job +grid 100000 10000 1 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:4085180000000000 +series __name__=b,host=h2,job=x,zone=z1 ; +result __name__=b,host=h2,job=y,zone=z1 ; 0:4085180000000000 +end +case limit limit_ratio 0.5 without job,zone +grid 100000 10000 3 +series __name__=a,host=h1,job=x ; 0:406a480000000000 1:c0897d0000000000 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h1,job=y ; +series __name__=b,host=h1,job=x,zone=z1 ; 0:c0619c0000000000 +series __name__=b,host=h2,job=y ; 0:4051100000000000 1:c078da0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:c081c70000000000 +series __name__=b,host=h2,job=x ; 1:4078f60000000000 2:0 +result __name__=a,host=h1,job=x ; 0:406a480000000000 1:c0897d0000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 0:c0619c0000000000 +result __name__=b,host=h2,job=x ; 1:4078f60000000000 2:0 +end +case limit limitk 0 none - +grid 100000 10000 12 +series __name__=a,host=h1,job=y ; 8:7ff0000000000000 +series __name__=a,host=h2,job=y ; 5:7e37e43c8800759c +series __name__=b,host=h2,job=y,zone=z1 ; 10:4066a00000000000 11:4083ce0000000000 +end +case limit limit_ratio -1 without __name__,zone +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; 0:7e37e43c8800759c +series __name__=a,host=h2,job=x ; 0:c08b560000000000 +series __name__=b,host=h1,job=y ; 0:4063c40000000000 +series __name__=b,host=h2,job=y ; 0:c08a2d0000000000 +series __name__=b,host=h2,job=x ; 0:0 +result __name__=a,host=h2,job=x ; 0:c08b560000000000 +result __name__=a,host=h2,job=y ; 0:7e37e43c8800759c +result __name__=b,host=h1,job=y ; 0:4063c40000000000 +result __name__=b,host=h2,job=x ; 0:0 +result __name__=b,host=h2,job=y ; 0:c08a2d0000000000 +end +case limit limitk 1 without - +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 5:c08dfc0000000000 +series __name__=a,host=h1,job=x ; 0:404b100000000000 1:c08b410000000000 4:c0663c0000000000 +series __name__=b,host=h2,job=x ; 1:c072c60000000000 2:4085340000000000 3:c07ff20000000000 +series __name__=b,host=h1,job=x ; 4:408aab0000000000 5:4087870000000000 +result __name__=a,host=h1,job=x ; 0:404b100000000000 1:c08b410000000000 4:c0663c0000000000 +result __name__=a,host=h2,job=x ; 5:c08dfc0000000000 +result __name__=b,host=h1,job=x ; 5:4087870000000000 +result __name__=b,host=h2,job=x ; 1:c072c60000000000 2:4085340000000000 3:c07ff20000000000 +end +case limit limitk 0 none - +grid 100000 10000 6 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h1,job=y,zone=z1 ; 4:7ff0000000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 4:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 5:4085c70000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 2:4084e10000000000 +end +case limit limitk NaN none - +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 1:4084a00000000000 +series __name__=a,host=h2,job=x ; 1:c061540000000000 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=a,host=h1,job=y,zone=z1 ; 0:c0804c0000000000 +series __name__=b,host=h1,job=y ; 1:c084760000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:c08be50000000000 +error Parameter value is NaN +end +case limit limitk 1 none - +grid 100000 10000 1 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=a,host=h2,job=x ; 0:7ff8000000000001 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h1,job=y ; 0:c082570000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:c0752e0000000000 +series __name__=b,host=h2,job=x ; 0:4089460000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 0:fff0000000000000 +result __name__=a,host=h2,job=x ; 0:7ff8000000000001 +end +case limit limit_ratio 1.5 none - +grid 100000 10000 11 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=y ; +series __name__=a,host=h1,job=y ; 3:4087b10000000000 4:c08f300000000000 5:c081f90000000000 6:405c500000000000 7:c08aee0000000000 +series __name__=b,host=h1,job=y ; 3:c08e540000000000 4:4067f80000000000 5:0 +series __name__=b,host=h2,job=y,zone=z2 ; 0:7ff8000000000001 1:c085370000000000 3:40750a0000000000 4:c0617c0000000000 5:c076f20000000000 6:406f040000000000 7:7ff8000000000001 9:4055280000000000 10:406b7c0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 10:c085830000000000 +result __name__=a,host=h1,job=y ; 3:4087b10000000000 4:c08f300000000000 5:c081f90000000000 6:405c500000000000 7:c08aee0000000000 +result __name__=b,host=h1,job=y ; 3:c08e540000000000 4:4067f80000000000 5:0 +result __name__=b,host=h2,job=x,zone=z1 ; 10:c085830000000000 +result __name__=b,host=h2,job=y,zone=z2 ; 0:7ff8000000000001 1:c085370000000000 3:40750a0000000000 4:c0617c0000000000 5:c076f20000000000 6:406f040000000000 7:7ff8000000000001 9:4055280000000000 10:406b7c0000000000 +end +case limit limit_ratio 0.3 by __name__,job +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h2,job=y ; 2:4089a70000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 2:40723c0000000000 3:c086f30000000000 4:4077d20000000000 +series __name__=a,host=h1,job=x ; 1:c0804b0000000000 2:0 +series __name__=b,host=h2,job=x ; 3:c082f40000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 4:4086160000000000 +series __name__=b,host=h1,job=x ; 3:7ff0000000000000 4:c070440000000000 +result __name__=b,host=h1,job=x ; 3:7ff0000000000000 4:c070440000000000 +result __name__=b,host=h2,job=x ; 3:c082f40000000000 +end +case limit limit_ratio -1.5 none - +grid 100000 10000 10 +series __name__=a,host=h2,job=x,zone=z1 ; 4:4052480000000000 5:c0896e0000000000 6:4068900000000000 7:c083a50000000000 +series __name__=b,host=h2,job=x ; 0:4083640000000000 1:c08a6b0000000000 2:405a480000000000 3:c08c510000000000 4:c085420000000000 5:4072a40000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4075800000000000 1:c06c7c0000000000 2:4089d70000000000 3:fff0000000000000 4:c070f60000000000 +series __name__=b,host=h2,job=y ; 1:4085a30000000000 2:4087760000000000 3:7e37e43c8800759c +result __name__=a,host=h2,job=x,zone=z1 ; 4:4052480000000000 5:c0896e0000000000 6:4068900000000000 7:c083a50000000000 +result __name__=b,host=h2,job=x ; 0:4083640000000000 1:c08a6b0000000000 2:405a480000000000 3:c08c510000000000 4:c085420000000000 5:4072a40000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:4075800000000000 1:c06c7c0000000000 2:4089d70000000000 3:fff0000000000000 4:c070f60000000000 +result __name__=b,host=h2,job=y ; 1:4085a30000000000 2:4087760000000000 3:7e37e43c8800759c +end +case limit limit_ratio 0.9 by job +grid 100000 10000 12 +series __name__=a,host=h1,job=y ; 5:c069ec0000000000 6:7ff0000000000000 7:c041900000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 11:c07a720000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:40727c0000000000 3:406a940000000000 +series __name__=b,host=h1,job=y ; 4:40713e0000000000 5:c072660000000000 6:7e37e43c8800759c 7:7ff8000000000001 8:c072040000000000 +result __name__=a,host=h1,job=y ; 5:c069ec0000000000 6:7ff0000000000000 7:c041900000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 11:c07a720000000000 +result __name__=b,host=h1,job=y ; 4:40713e0000000000 5:c072660000000000 6:7e37e43c8800759c 7:7ff8000000000001 8:c072040000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 1:40727c0000000000 3:406a940000000000 +end +case limit limitk -1 none - +grid 100000 10000 5 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4088e80000000000 2:40876c0000000000 3:c0878e0000000000 4:408b6e0000000000 +series __name__=a,host=h1,job=y ; 3:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 1:407a980000000000 2:c04a900000000000 +series __name__=b,host=h1,job=y ; 2:405e280000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +end +case limit limitk 0 without __name__,zone +grid 100000 10000 8 +series __name__=a,host=h2,job=x,zone=z1 ; 3:c087530000000000 4:408cad0000000000 +series __name__=a,host=h2,job=x ; 1:4035600000000000 2:40889f0000000000 3:4071880000000000 4:c0829f0000000000 5:406ae80000000000 +series __name__=a,host=h2,job=y ; 2:407f3c0000000000 3:c089c30000000000 4:c04e000000000000 5:7e37e43c8800759c 6:406f600000000000 7:c07d7e0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:4084450000000000 1:407f080000000000 +series __name__=b,host=h1,job=x ; 5:405e680000000000 6:4076a80000000000 7:fff0000000000000 +series __name__=b,host=h2,job=y ; 2:c021c00000000000 4:c084650000000000 5:c051c00000000000 6:c07c180000000000 7:4050c80000000000 +end +case limit limit_ratio 0.5 by host,zone +grid 100000 10000 12 +series __name__=a,host=h2,job=y,zone=z1 ; 7:4087260000000000 10:407c720000000000 +series __name__=a,host=h2,job=x ; 10:40797e0000000000 +series __name__=b,host=h2,job=y ; 11:c07f420000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 7:4087260000000000 10:407c720000000000 +end +case limit limit_ratio 0.9 none - +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h1,job=x ; 6:c08dd70000000000 7:40753a0000000000 8:405d100000000000 9:4069f00000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 1:c087a90000000000 2:c069640000000000 3:c087800000000000 4:408b400000000000 5:407d920000000000 6:c083600000000000 7:c07d3a0000000000 8:c081c90000000000 9:406c940000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 6:4087230000000000 7:c060d40000000000 8:408b6a0000000000 9:40842a0000000000 +result __name__=b,host=h1,job=x ; 6:c08dd70000000000 7:40753a0000000000 8:405d100000000000 9:4069f00000000000 +result __name__=b,host=h1,job=x,zone=z2 ; 1:c087a90000000000 2:c069640000000000 3:c087800000000000 4:408b400000000000 5:407d920000000000 6:c083600000000000 7:c07d3a0000000000 8:c081c90000000000 9:406c940000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 6:4087230000000000 7:c060d40000000000 8:408b6a0000000000 9:40842a0000000000 +end +case limit limitk -1 without job +grid 100000 10000 5 +series __name__=a,host=h1,job=x ; 3:c07e780000000000 4:c07fc80000000000 +series __name__=a,host=h2,job=x ; 1:c052000000000000 +series __name__=a,host=h1,job=y ; 1:c06e580000000000 2:408f0f0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c07d7e0000000000 2:4063a40000000000 +series __name__=b,host=h1,job=x ; 3:c08bb80000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +end +case limit limit_ratio -0.5 without __name__,zone +grid 100000 10000 8 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c08abd0000000000 4:c08a940000000000 +series __name__=a,host=h1,job=y ; 0:4087470000000000 2:4088490000000000 3:4076f40000000000 +series __name__=b,host=h1,job=y ; 5:4087230000000000 +series __name__=b,host=h2,job=x ; 2:0 4:4045300000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 3:7ff0000000000000 5:408b780000000000 7:c085310000000000 +result __name__=a,host=h1,job=y ; 0:4087470000000000 2:4088490000000000 3:4076f40000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 3:7ff0000000000000 5:408b780000000000 7:c085310000000000 +end +case limit limitk 10 none - +grid 100000 10000 9 +series __name__=a,host=h1,job=x ; 3:c07f000000000000 4:c087f90000000000 5:407d620000000000 6:405f680000000000 7:4082420000000000 +series __name__=a,host=h2,job=x ; 1:406a880000000000 2:40872e0000000000 3:c071880000000000 4:40768c0000000000 +series __name__=a,host=h1,job=y ; 7:c03a800000000000 8:c0851c0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 7:4025800000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 8:c063d00000000000 +series __name__=b,host=h1,job=x ; 6:c073c20000000000 7:c06aec0000000000 8:c080330000000000 +result __name__=a,host=h1,job=x ; 3:c07f000000000000 4:c087f90000000000 5:407d620000000000 6:405f680000000000 7:4082420000000000 +result __name__=a,host=h1,job=y ; 7:c03a800000000000 8:c0851c0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 7:4025800000000000 +result __name__=a,host=h2,job=x ; 1:406a880000000000 2:40872e0000000000 3:c071880000000000 4:40768c0000000000 +result __name__=b,host=h1,job=x ; 6:c073c20000000000 7:c06aec0000000000 8:c080330000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 8:c063d00000000000 +end +case limit limit_ratio 0 without host +grid 100000 10000 10 +series __name__=a,host=h2,job=x,zone=z1 ; 8:40820b0000000000 +series __name__=a,host=h2,job=x ; 2:c082b20000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h2,job=x,zone=z1 ; 4:c068080000000000 5:4089be0000000000 +series __name__=b,host=h2,job=y ; 1:407c9e0000000000 2:408a140000000000 3:40848b0000000000 +series __name__=b,host=h2,job=x ; 9:40754e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 5:4071720000000000 6:c085190000000000 7:c084510000000000 8:c082160000000000 +end +case limit limitk 10 none - +grid 100000 10000 6 +series __name__=a,host=h1,job=x,zone=z1 ; 3:40854d0000000000 4:4080900000000000 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h1,job=x ; 1:c067280000000000 2:4066d00000000000 +series __name__=b,host=h2,job=y ; 3:0 +series __name__=b,host=h1,job=x ; 0:c07fc80000000000 +result __name__=a,host=h1,job=x ; 1:c067280000000000 2:4066d00000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 3:40854d0000000000 4:4080900000000000 +result __name__=b,host=h1,job=x ; 0:c07fc80000000000 +result __name__=b,host=h2,job=y ; 3:0 +end +case limit limit_ratio -0.3 none - +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 7:0 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h2,job=x ; 3:408f0b0000000000 +series __name__=b,host=h1,job=y ; 2:c08dc40000000000 +series __name__=b,host=h2,job=x ; 3:4076540000000000 4:c088df0000000000 5:c059a80000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 4:c08cd70000000000 5:4089ad0000000000 +result __name__=a,host=h2,job=x ; 3:408f0b0000000000 +end +case limit limit_ratio -1 without host,job,zone +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 5:c08ae60000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c055700000000000 2:0 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h1,job=x ; 2:fff0000000000000 +series __name__=a,host=h2,job=y ; 3:40736a0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +result __name__=a,host=h1,job=x ; 2:fff0000000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 1:c055700000000000 2:0 +result __name__=a,host=h2,job=x ; 5:c08ae60000000000 +result __name__=a,host=h2,job=y ; 3:40736a0000000000 +end +case limit limit_ratio 1.5 without zone +grid 100000 10000 4 +series __name__=a,host=h2,job=y ; 3:c0857a0000000000 +series __name__=a,host=h1,job=x ; 2:c084060000000000 +series __name__=a,host=h2,job=x ; 3:40854f0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:4076840000000000 2:c06f540000000000 3:0 +series __name__=b,host=h1,job=x ; 0:c08dcc0000000000 1:c07f840000000000 2:404d400000000000 +series __name__=b,host=h2,job=x ; 2:c054900000000000 3:7ff0000000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:4086660000000000 2:c08e020000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=y,zone=z1 ; 3:c083a30000000000 +result __name__=a,host=h1,job=x ; 2:c084060000000000 +result __name__=a,host=h2,job=x ; 3:40854f0000000000 +result __name__=a,host=h2,job=y ; 3:c0857a0000000000 +result __name__=b,host=h1,job=x ; 0:c08dcc0000000000 1:c07f840000000000 2:404d400000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 1:4086660000000000 2:c08e020000000000 +result __name__=b,host=h2,job=x ; 2:c054900000000000 3:7ff0000000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 1:4076840000000000 2:c06f540000000000 3:0 +result __name__=b,host=h2,job=y,zone=z1 ; 3:c083a30000000000 +end +case limit limit_ratio NaN without __name__,job +grid 100000 10000 10 +series __name__=a,host=h1,job=y ; 2:4079280000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 3:c085cc0000000000 4:c08ef40000000000 5:c05d800000000000 6:c08f260000000000 7:c06bfc0000000000 +series __name__=a,host=h2,job=y ; 1:407fec0000000000 2:c069a00000000000 +series __name__=b,host=h2,job=x ; 4:4075d60000000000 5:4070080000000000 +series __name__=b,host=h1,job=x ; 3:c07a480000000000 5:7ff8000000000001 +series __name__=b,host=h1,job=y,zone=z1 ; 1:7e37e43c8800759c 2:c05ab00000000000 3:c0798c0000000000 4:c072160000000000 5:40835a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 5:c060d40000000000 6:c085260000000000 7:c071820000000000 +series __name__=b,host=h2,job=y ; 6:4086fa0000000000 7:c063bc0000000000 8:406ab40000000000 9:c086160000000000 +error Ratio value is NaN +end +case limit limit_ratio -1 without __name__,zone +grid 100000 10000 10 +series __name__=a,host=h1,job=y,zone=z1 ; 1:c08a660000000000 2:c082d60000000000 4:c051500000000000 5:406d040000000000 6:7ff8000000000001 7:c0612c0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 3:0 5:408b220000000000 6:c07e5e0000000000 +series __name__=b,host=h1,job=y ; 1:7e37e43c8800759c 2:4081920000000000 4:407ed40000000000 5:4067000000000000 7:c086ea0000000000 8:c084630000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:7ff8000000000001 2:c0856a0000000000 3:c0759e0000000000 4:c074200000000000 5:7ff8000000000001 6:7ff8000000000001 7:c084a10000000000 8:c088830000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 1:c08a660000000000 2:c082d60000000000 4:c051500000000000 5:406d040000000000 6:7ff8000000000001 7:c0612c0000000000 +result __name__=b,host=h1,job=y ; 1:7e37e43c8800759c 2:4081920000000000 4:407ed40000000000 5:4067000000000000 7:c086ea0000000000 8:c084630000000000 +result __name__=b,host=h1,job=y,zone=z1 ; 3:0 5:408b220000000000 6:c07e5e0000000000 +result __name__=b,host=h1,job=y,zone=z2 ; 0:7ff8000000000001 2:c0856a0000000000 3:c0759e0000000000 4:c074200000000000 5:7ff8000000000001 6:7ff8000000000001 7:c084a10000000000 8:c088830000000000 +end +case limit limit_ratio 1.5 by __name__,job +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:407f8a0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:7ff8000000000001 +series __name__=a,host=h1,job=y ; 0:7ff0000000000000 +series __name__=a,host=h2,job=y ; 0:fff0000000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c072320000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +series __name__=b,host=h2,job=y ; 0:c067b80000000000 +result __name__=a,host=h1,job=x ; 0:407f8a0000000000 +result __name__=a,host=h1,job=y ; 0:7ff0000000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:7ff8000000000001 +result __name__=a,host=h2,job=y ; 0:fff0000000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 0:c072320000000000 +result __name__=b,host=h2,job=y ; 0:c067b80000000000 +end +case limit limitk 1 none - +grid 100000 10000 12 +series __name__=a,host=h2,job=y,zone=z1 ; 0:403a200000000000 1:408af00000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 8:c066740000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 6:c0633c0000000000 7:40758a0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:408e220000000000 +series __name__=b,host=h2,job=y ; 0:408ce30000000000 1:c07f5e0000000000 2:c076880000000000 3:7ff0000000000000 4:c08a240000000000 5:fff0000000000000 7:4081450000000000 8:4061400000000000 9:407cec0000000000 +series __name__=b,host=h2,job=x ; 1:c073280000000000 2:4072240000000000 4:c05bc00000000000 5:408ab60000000000 6:40810e0000000000 9:c08cfc0000000000 10:40749e0000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 8:c066740000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 0:403a200000000000 1:408af00000000000 +result __name__=b,host=h2,job=x ; 10:40749e0000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 6:c0633c0000000000 7:40758a0000000000 +result __name__=b,host=h2,job=y ; 2:c076880000000000 3:7ff0000000000000 4:c08a240000000000 5:fff0000000000000 9:407cec0000000000 +end +case limit limitk 1 none - +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 0:7ff8000000000001 1:4088b50000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:408e740000000000 3:407a740000000000 4:7ff8000000000001 5:408f0d0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 4:7e37e43c8800759c +series __name__=a,host=h1,job=x ; 5:c0815e0000000000 6:40700a0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:c081b20000000000 +series __name__=b,host=h1,job=x ; 1:40724c0000000000 +result __name__=a,host=h1,job=x ; 6:40700a0000000000 +result __name__=a,host=h2,job=x ; 0:7ff8000000000001 1:4088b50000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 3:407a740000000000 4:7ff8000000000001 5:408f0d0000000000 +end diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index 568ed4c4b5c..0cc2763bf64 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -24,14 +24,16 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use super::{ - Grouping, LabelMatcher, MatchOp, SortOrder, absent, absent_labels, natural_less, scalar, - sort_instant, topk, + Grouping, LabelMatcher, MatchOp, SortOrder, absent, absent_labels, limit_ratio, limitk, + natural_less, sample_offset, scalar, sort_instant, topk, }; use crate::golden::fold_pieces; use crate::grid_series::reference::{ - Dense, Labels, Points, assert_pieces_eq, assert_result_eq, piece_ranges, run_ranges, - sparse_series, + Dense, Labels, OwnedHistogram, Points, assert_pieces_eq, assert_result_eq, piece_ranges, + run_ranges, sparse_series, }; +use crate::grid_series::{GridSample, GridSeriesBuilder}; +use crate::histogram_eval::float_histogram::FloatHistogram; fn schema(points: u64, fields: usize) -> SeriesSchema { SeriesSchema { @@ -117,42 +119,20 @@ fn names(list: &str) -> Vec> { /// header of `prometheus_cases.txt`. #[test] fn select_operators_match_prometheus() { - let text = include_str!("prometheus_cases.txt"); - let mut checked = 0; - for case in text.split("end\n").filter(|case| case.contains("case ")) { - let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect(); - let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect(); - let points: usize = lines[1].split_whitespace().nth(3).unwrap().parse().unwrap(); - let schema = schema(points as u64, 1); - let mut inputs = Vec::new(); - let mut expected: BTreeMap = BTreeMap::new(); - for line in &lines[2..] { - let (kind, rest) = line.split_once(' ').unwrap(); - let (labels, values) = rest.split_once(" ;").unwrap(); - match kind { - "series" => inputs.push((metric(labels), dense(points, values))), - "result" => { - expected.insert(labels.to_string(), dense(points, values)); - } - other => panic!("unexpected line {other} in {case}"), - } - } - let series: Vec = inputs - .iter() - .filter_map(|(metric, dense)| build(&schema, metric.clone(), dense)) - .collect(); - - let actual: Vec = match spec[0] { + let checked = check_cases( + include_str!("prometheus_cases.txt"), + |spec, schema, series| match spec[0] { "topk" => { - let grouping = match spec[3] { - "without" => Grouping::Without(names(spec[4])), - "by" => Grouping::By(names(spec[4])), - _ => Grouping::By(Vec::new()), - }; let k: f64 = spec[2].parse().unwrap(); - topk(k, spec[1] == "topk", &grouping, &schema, &series).unwrap() + topk( + k, + spec[1] == "topk", + &grouping(spec[3], spec[4]), + schema, + series, + ) } - "scalar" => vec![scalar(&schema, &series).unwrap()], + "scalar" => Ok(vec![scalar(schema, series).unwrap()]), "absent" => { let matchers: Vec = spec .get(1) @@ -189,12 +169,156 @@ fn select_operators_match_prometheus() { }) .cloned() .collect(); - absent(&schema, &selected, absent_labels(&matchers).unwrap()) + Ok(absent(schema, &selected, absent_labels(&matchers).unwrap()) .unwrap() .into_iter() - .collect() + .collect()) } other => panic!("unknown case {other}"), + }, + ); + assert!(checked > 200, "{checked} result series checked"); +} + +/// `limitk` and `limit_ratio` evaluated by the Prometheus v3.15.0 engine; see the header of +/// `limit_cases.txt`. +#[test] +fn limit_operators_match_prometheus() { + let checked = check_cases(include_str!("limit_cases.txt"), |spec, schema, series| { + let param: f64 = spec[2].parse().unwrap(); + match spec[1] { + "limitk" => limitk(param, &grouping(spec[3], spec[4]), schema, series), + _ => limit_ratio(param, schema, series), + } + }); + assert!(checked > 200, "{checked} result series checked"); +} + +/// The labels of the fixtures are short; these need the long length prefix of `stringlabels`. +/// Prometheus' offsets were computed with promql-compat `cmd/narthex-golden-labelhash`. +#[test] +fn sample_offset_hashes_labels_like_prometheus() { + let cases = [ + ("__name__=a,job=x".to_string(), 0x3fe1c2f8b3f15aa8), + ( + format!("__name__=a,long={}", "v".repeat(300)), + 0x3fca51ed01e04434, + ), + ( + format!( + "__name__=a,{}={},zone={}", + "n".repeat(254), + "v".repeat(255), + "z".repeat(70000) + ), + 0x3fc3bf72b8300ba3, + ), + // A Prometheus label set has no empty value, so an empty label is no label. + ("__name__=a,empty=,job=x".to_string(), 0x3fe1c2f8b3f15aa8), + ]; + for (labels, offset) in cases { + assert_eq!(sample_offset(&metric(&labels)).to_bits(), offset); + } +} + +/// `limitk` and `limit_ratio` select series, so histogram samples pass through, and +/// `limit_ratio` keeps every field of the series it keeps. +#[test] +fn limit_operators_keep_histogram_samples() { + let histogram = + OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"); + let sample = || { + GridSample::Histogram(Box::new( + FloatHistogram::try_from_view(&histogram.view()).unwrap(), + )) + }; + let kinds = |series: &Series, field: usize| -> Vec<(usize, &str)> { + let samples = &series.fields.as_slice()[field]; + series + .time + .positions() + .map(|(point, row)| { + let kind = match samples.sample(row) { + SampleRef::Missing => "missing", + SampleRef::Float(_) => "float", + SampleRef::Histogram(_) => "histogram", + }; + (point, kind) + }) + .collect() + }; + + let two_fields = schema(3, 2); + let mut builder = GridSeriesBuilder::try_new(Arc::new(two_fields.clone())).unwrap(); + builder + .push_samples(0, &[Some(GridSample::Float(1.0)), Some(sample())]) + .unwrap(); + builder.push_samples(2, &[None, Some(sample())]).unwrap(); + let series = builder.finish(metric("__name__=a")).unwrap().unwrap(); + let kept = limit_ratio(1.0, &two_fields, std::slice::from_ref(&series)).unwrap(); + assert_eq!(kept.len(), 1); + assert_eq!(kinds(&kept[0], 0), [(0, "float"), (2, "missing")]); + assert_eq!(kinds(&kept[0], 1), [(0, "histogram"), (2, "histogram")]); + + let one_field = schema(3, 1); + let mut builder = GridSeriesBuilder::try_new(Arc::new(one_field.clone())).unwrap(); + builder.push_samples(1, &[Some(sample())]).unwrap(); + let series = builder.finish(metric("__name__=a")).unwrap().unwrap(); + let kept = limitk(1.0, &Grouping::By(Vec::new()), &one_field, &[series]).unwrap(); + assert_eq!(kept.len(), 1); + assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]); +} + +fn grouping(kind: &str, labels: &str) -> Grouping { + match kind { + "without" => Grouping::Without(names(labels)), + "by" => Grouping::By(names(labels)), + _ => Grouping::By(Vec::new()), + } +} + +/// Evaluates each case of a fixture with `eval` and returns how many result series matched; a +/// case with an `error` line must fail with that message. +fn check_cases( + text: &str, + eval: impl Fn(&[&str], &SeriesSchema, &[Series]) -> Result, DataFusionError>, +) -> usize { + let mut checked = 0; + for case in text.split("end\n").filter(|case| case.contains("case ")) { + let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect(); + let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect(); + let points: usize = lines[1].split_whitespace().nth(3).unwrap().parse().unwrap(); + let schema = schema(points as u64, 1); + let mut inputs = Vec::new(); + let mut expected: BTreeMap = BTreeMap::new(); + let mut error = None; + for line in &lines[2..] { + if let Some(message) = line.strip_prefix("error ") { + error = Some(message); + continue; + } + let (kind, rest) = line.split_once(' ').unwrap(); + let (labels, values) = rest.split_once(" ;").unwrap(); + match kind { + "series" => inputs.push((metric(labels), dense(points, values))), + "result" => { + expected.insert(labels.to_string(), dense(points, values)); + } + other => panic!("unexpected line {other} in {case}"), + } + } + let series: Vec = inputs + .iter() + .filter_map(|(metric, dense)| build(&schema, metric.clone(), dense)) + .collect(); + + let actual = match (eval(&spec, &schema, &series), error) { + (Ok(actual), None) => actual, + (Err(actual), Some(expected)) => { + assert_eq!(actual.message(), expected, "{case}"); + continue; + } + (actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"), }; // A result arrives as one series over the runs of valued positions; the fixtures pin the @@ -213,7 +337,7 @@ fn select_operators_match_prometheus() { checked += 1; } } - assert!(checked > 200, "{checked} result series checked"); + checked } /// The fixture's label rendering: `name=value` pairs in name order, `-` when empty. diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index 5e49080fb87..eab40a3f64e 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -25,12 +25,12 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; -use datatypes::series::MetricName; use datatypes::series::histogram::{CounterResetHint, HistogramView}; use datatypes::series::samples::{RowCursor, SampleRef, Series, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridRunPair, TimeAxis}; +use datatypes::series::{Label, MetricName}; -use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS}; +use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external, owned}; use crate::histogram_eval::float_histogram::FloatHistogram; #[cfg(test)] @@ -110,8 +110,30 @@ pub struct BinaryMatching { pub return_bool: bool, pub labels: MatchingLabels, pub cardinality: Cardinality, + pub fill: FillValues, } +/// The values of `fill`, `fill_left` and `fill_right`, which stand in for a sample that has no +/// match on the other side. +/// +/// Prometheus applies them after it swaps the operands of `group_right`, so there `fill_left` +/// stands in for a missing right-hand sample and `fill_right` for a missing left-hand one. +#[derive(Clone, Copy, Debug, Default)] +pub struct FillValues { + pub lhs: Option, + pub rhs: Option, +} + +// Compared by bits: a NaN fill equals itself, and `fill(-0)` differs from `fill(0)` (`1 / fill`). +impl PartialEq for FillValues { + fn eq(&self, other: &Self) -> bool { + let bits = |value: Option| value.map(f64::to_bits); + bits(self.lhs) == bits(other.lhs) && bits(self.rhs) == bits(other.rhs) + } +} + +impl Eq for FillValues {} + /// A PromQL set operator between two instant vectors. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SetOp { @@ -135,7 +157,8 @@ pub fn binary_output_schema(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result (rhs, lhs, &include[..], true), }; let points = grid.timestamps().len(); - // Prometheus short-circuits a point where either side is empty, before any check. - let both_present: Vec = lhs + let fill = matching.fill; + // Prometheus short-circuits a point where either side is empty, before any check; with a fill + // value only a point where both are empty. + let filling = fill.lhs.is_some() || fill.rhs.is_some(); + let evaluated: Vec = lhs .presence(points) .into_iter() .zip(rhs.presence(points)) - .map(|(lhs, rhs)| lhs && rhs) + .map(|(lhs, rhs)| if filling { lhs || rhs } else { lhs && rhs }) .collect(); let one_groups = group(one, &matching.labels); let mut one_duplicate: Option<(usize, &GroupKey)> = None; for (key, members) in &one_groups { - if let Some(point) = overlap(one, members, |point| both_present[point]) + if let Some(point) = overlap(one, members, |point| evaluated[point]) && one_duplicate.is_none_or(|(first, _)| point < first) { one_duplicate = Some((point, key)); @@ -193,23 +219,23 @@ fn binary_field( } let drop_name = !matching.op.is_comparison() || matching.return_bool; - let mut results = Results::default(); - let group_keys: Vec<&GroupKey> = one_groups.keys().collect(); - let group_ids: HashMap<&GroupKey, usize> = group_keys - .iter() - .enumerate() - .map(|(id, key)| (*key, id)) - .collect(); - // One-to-one: a match group may be matched once per point; Prometheus counts a filtered - // comparison as a match too, but not an operation that failed. - let mut matched: HashSet<(usize, usize)> = HashSet::new(); - let mut implicit_many_to_one: Option<(usize, &GroupKey)> = None; + let mut pairs = Pairs { + matching, + one_is_left, + results: Results::default(), + group_keys: Vec::new(), + group_ids: HashMap::new(), + matched: (matching.cardinality == Cardinality::OneToOne || fill.lhs.is_some()) + .then(HashSet::new), + implicit_many_to_one: None, + }; for (many_index, many_series) in many.series.iter().enumerate() { let key = group_key(&many_series.metric, &matching.labels); - let Some(candidates) = one_groups.get(&key) else { + let candidates = one_groups.get(&key).map_or(&[][..], Vec::as_slice); + if candidates.is_empty() && fill.rhs.is_none() { continue; - }; - let group_id = group_ids[&key]; + } + let group = pairs.group_id(&key); for &one_index in candidates { let metric = result_metric( &many_series.metric, @@ -237,36 +263,65 @@ fn binary_field( .at(pair.other_row + offset) .expect("a row never goes back"), ); - if matches!(many_value, SampleRef::Missing) - || matches!(one_value, SampleRef::Missing) - { - continue; - } - let (lhs_value, rhs_value) = if one_is_left { - (one_value, many_value) - } else { - (many_value, one_value) - }; - let Some((result, keep)) = elem_binop(matching.op, lhs_value, rhs_value)? - else { - continue; - }; - if matching.cardinality == Cardinality::OneToOne - && !matched.insert((group_id, point)) - && implicit_many_to_one.is_none_or(|(first, _)| point < first) - { - implicit_many_to_one = Some((point, group_keys[group_id])); - } - let value = if matching.return_bool { - Some(GridSample::Float(if keep { 1.0 } else { 0.0 })) - } else { - keep.then_some(result) - }; - results.insert(&metric, group_id, point, value); + pairs.apply(group, &metric, point, many_value, one_value)?; + } + } + } + if let Some(value) = fill.rhs { + let metric = result_metric( + &many_series.metric, + &metric_of(&key)?, + matching, + include, + drop_name, + )?; + let mut cursor = many.cursor(many_index); + let mut candidate_cursors: Vec> = + candidates.iter().map(|&index| one.cursor(index)).collect(); + for (point, row) in many.positions(many_index) { + let sample = cursor.at(row).expect("a row never goes back"); + let matched = candidates + .iter() + .zip(&mut candidate_cursors) + .any(|(&index, cursor)| one.present(index, point, cursor)); + if !matched { + pairs.apply(group, &metric, point, sample, SampleRef::Float(value))?; } } } } + // Prometheus fills the many side after every match of the step, for the samples of the one + // side that no operation matched. + if let Some(value) = fill.lhs { + for (one_index, one_series) in one.series.iter().enumerate() { + let key = group_key(&one_series.metric, &matching.labels); + let group = pairs.group_id(&key); + let metric = result_metric( + &metric_of(&key)?, + &one_series.metric, + matching, + include, + drop_name, + )?; + let mut cursor = one.cursor(one_index); + for (point, row) in one.positions(one_index) { + if !pairs + .matched + .as_ref() + .is_some_and(|matched| matched.contains(&(group, point))) + { + let sample = cursor.at(row).expect("a row never goes back"); + pairs.apply(group, &metric, point, SampleRef::Float(value), sample)?; + } + } + } + } + let Pairs { + mut results, + group_keys, + implicit_many_to_one, + .. + } = pairs; // Prometheus fails at the first failing step. Within a step it checks the one side, then // matches, and only after the operator checks that result label sets are unique. if let Some((point, key)) = one_duplicate { @@ -283,7 +338,8 @@ fn binary_field( ), )); } - if let Some((point, key)) = implicit_many_to_one { + if let Some((point, group)) = implicit_many_to_one { + let key = &group_keys[group]; errors.push(( point, 1, @@ -319,6 +375,89 @@ fn binary_field( Ok(results) } +/// The matched pairs of one field and the state Prometheus checks them against. +struct Pairs<'a> { + matching: &'a BinaryMatching, + one_is_left: bool, + results: Results, + group_keys: Vec, + group_ids: HashMap, + /// The match groups an operation matched at a point, kept where Prometheus consults them: + /// one-to-one matching, and filling the many side. A filtered comparison counts as a match, + /// an operation that failed does not. + matched: Option>, + implicit_many_to_one: Option<(usize, usize)>, +} + +impl Pairs<'_> { + /// The id of the match group `key`, which stands for it in `matched` and in the results. + fn group_id(&mut self, key: &GroupKey) -> usize { + if let Some(&id) = self.group_ids.get(key) { + return id; + } + let id = self.group_keys.len(); + self.group_keys.push(key.clone()); + self.group_ids.insert(key.clone(), id); + id + } + + /// Applies the operator to a sample of each side at `point`; a missing sample is no pair. + fn apply( + &mut self, + group: usize, + metric: &MetricName, + point: usize, + many_value: SampleRef<'_>, + one_value: SampleRef<'_>, + ) -> Result<()> { + if matches!(many_value, SampleRef::Missing) || matches!(one_value, SampleRef::Missing) { + return Ok(()); + } + let (lhs_value, rhs_value) = if self.one_is_left { + (one_value, many_value) + } else { + (many_value, one_value) + }; + let Some((result, keep)) = elem_binop(self.matching.op, lhs_value, rhs_value)? else { + return Ok(()); + }; + // One-to-one: a match group may be matched once per point. + if let Some(matched) = &mut self.matched + && !matched.insert((group, point)) + && self.matching.cardinality == Cardinality::OneToOne + && self + .implicit_many_to_one + .is_none_or(|(first, _)| point < first) + { + self.implicit_many_to_one = Some((point, group)); + } + let value = if self.matching.return_bool { + Some(GridSample::Float(if keep { 1.0 } else { 0.0 })) + } else { + keep.then_some(result) + }; + self.results.insert(metric, group, point, value); + Ok(()) + } +} + +/// The labels Prometheus gives a fill sample: the match group of the sample it pairs with. +fn metric_of(key: &GroupKey) -> Result { + let mut name = None; + let mut labels = Vec::with_capacity(key.len()); + for (label, value) in key { + if &**label == "__name__" { + name = Some(value.clone()); + } else { + labels.push(Label { + name: label.clone(), + value: value.clone(), + }); + } + } + MetricName::try_new(name, labels).map_err(external) +} + fn earliest_error(errors: Vec<(usize, u8, String)>) -> Result<()> { match errors .into_iter() @@ -687,17 +826,6 @@ impl<'a> Operand<'a> { } } -/// `sample` as an owned value; `None` when missing. -fn owned(sample: SampleRef<'_>) -> Result> { - Ok(match sample { - SampleRef::Missing => None, - SampleRef::Float(value) => Some(GridSample::Float(value)), - SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new( - FloatHistogram::try_from_view(&view)?, - ))), - }) -} - /// Prometheus `vectorElemBinop` over present samples: the value and whether to keep it, or /// `None` when Prometheus reports the pair as an annotation and skips it without counting the /// match: an operator the sample types do not support, or an addition or subtraction of diff --git a/src/promql/src/vector_match/fill_cases.txt b/src/promql/src/vector_match/fill_cases.txt new file mode 100644 index 00000000000..3d6213c2c89 --- /dev/null +++ b/src/promql/src/vector_match/fill_cases.txt @@ -0,0 +1,2021 @@ +# Generated by promql-compat cmd/narthex-golden-vector built for amd64 (Prometheus v3.15.0 +# engine, seed 1, 200 cases per kind, -experimental fill). Each case lists its operation, the grid, the +# input series and either the result series or the error. Points are `grid index:hex bits`. +case binary - false ignoring zone one - 1 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=y ; 1:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 5:c079dc0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4078980000000000 2:406ad00000000000 3:c08b8e0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 4:c0795c0000000000 5:7ff8000000000001 +result host=h1,job=x ; 1:4078880000000000 2:406ab00000000000 3:c08b960000000000 +result host=h1,job=y ; 4:40796c0000000000 5:7ff8000000000001 +result host=h2,job=y ; 1:7ff8000000000001 +end +case binary <= true on job,zone left - NaN NaN +grid 100000 10000 3 +series __name__=a,host=h1,job=y,zone=z1 ; 2:407a5e0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:c0763e0000000000 1:4075320000000000 +series __name__=a,host=h1,job=x ; 0:c07b560000000000 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x ; 0:c08f130000000000 1:4083b60000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:407fa60000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:4066580000000000 +series __name__=b,host=h2,job=x ; 2:c087190000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4053880000000000 +result host=h1,job=x ; 0:0 +result host=h1,job=x,zone=z1 ; 0:3ff0000000000000 1:3ff0000000000000 +result host=h1,job=y,zone=z1 ; 2:0 +result host=h2,job=x ; 0:0 1:0 +result job=x ; 2:0 +result job=y,zone=z1 ; 1:0 +end +case binary < true on host,zone,__name__ left job Inf Inf +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 3:c08ba10000000000 5:c0897e0000000000 6:4085ca0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 5:408c1e0000000000 6:c08e030000000000 +result host=h2 ; 3:3ff0000000000000 5:3ff0000000000000 6:3ff0000000000000 +result host=h2,job=x,zone=z2 ; 5:0 6:0 +end +case binary / false ignoring zone left job - NaN +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c08e530000000000 +series __name__=b,host=h2,job=y ; 5:7ff8000000000001 +series __name__=b,host=h1,job=y,zone=z1 ; 4:c08e150000000000 5:c060d40000000000 6:4073e00000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 1:c0659c0000000000 +result host=h1,job=y,zone=z1 ; 3:7ff8000000000001 +end +case binary <= true none - one - - 1 +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; 1:c025400000000000 2:c067180000000000 +series __name__=b,host=h2,job=x ; 3:4086d30000000000 +result host=h2,job=x ; 1:3ff0000000000000 2:3ff0000000000000 +end +case binary - false ignoring job left host,job 0 -2.5 +grid 100000 10000 4 +series __name__=a,host=h1,job=y ; 2:7ff8000000000001 3:4050b80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 2:4085500000000000 3:4088f60000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 2:408cc80000000000 +series __name__=a,host=h1,job=x ; 1:c071360000000000 +series __name__=b,host=h1,job=y ; 3:c07f7a0000000000 +result host=h1 ; 1:c0710e0000000000 2:7ff8000000000001 +result host=h1,job=y ; 3:4081d40000000000 +result host=h1,zone=z1 ; 2:4085640000000000 3:40890a0000000000 +result host=h2,zone=z1 ; 2:408cdc0000000000 +end +case binary != true none - one - 1 1 +grid 100000 10000 5 +series __name__=a,host=h2,job=x ; 2:7ff8000000000001 +series __name__=a,host=h1,job=x,zone=z1 ; 3:fff0000000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c065ec0000000000 1:4085910000000000 2:7ff0000000000000 3:40883d0000000000 +series __name__=a,host=h1,job=y ; 3:406dc00000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 3:c0708e0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4083440000000000 +result host=h1,job=x,zone=z1 ; 3:3ff0000000000000 +result host=h1,job=y ; 3:3ff0000000000000 +result host=h2,job=x ; 2:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 0:3ff0000000000000 1:3ff0000000000000 2:3ff0000000000000 3:3ff0000000000000 +end +case binary * false on zone one - Inf Inf +grid 100000 10000 12 +series __name__=a,host=h1,job=y ; 3:408ad50000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 10:4047200000000000 +series __name__=b,host=h1,job=y ; 7:40700c0000000000 8:7ff8000000000001 9:c073260000000000 +result - ; 3:7ff0000000000000 7:7ff0000000000000 8:7ff8000000000001 9:fff0000000000000 +result zone=z1 ; 10:7ff0000000000000 +end +case binary + false ignoring - one - 0 - +grid 100000 10000 3 +series __name__=a,host=h2,job=x ; 1:401a000000000000 +series __name__=a,host=h2,job=y ; 0:c07e840000000000 +series __name__=b,host=h2,job=x ; 2:4051880000000000 +series __name__=b,host=h2,job=y ; 2:c052300000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:c06d7c0000000000 +series __name__=b,host=h1,job=y ; 2:c0869d0000000000 +result host=h1,job=y ; 2:c0869d0000000000 +result host=h2,job=x ; 2:4051880000000000 +result host=h2,job=x,zone=z1 ; 1:c06d7c0000000000 +result host=h2,job=y ; 2:c052300000000000 +end +case binary != false on job,zone left - - Inf +grid 100000 10000 1 +series __name__=a,host=h1,job=x,zone=z1 ; 0:4086890000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:408bc10000000000 +series __name__=a,host=h2,job=y ; 0:4049700000000000 +series __name__=a,host=h2,job=x ; 0:c08a530000000000 +series __name__=a,host=h1,job=y ; 0:c064dc0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4054600000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h1,job=x ; 0:c08e020000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=x,zone=z1 ; 0:408aa10000000000 +error found duplicate series for the match group {job="x", zone="z1"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h2", job="x", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary atan2 false on job right host -2.5 -2.5 +grid 100000 10000 9 +series __name__=a,host=h2,job=x,zone=z1 ; 6:c07a440000000000 7:c0852d0000000000 +series __name__=a,host=h1,job=x ; 1:408bd00000000000 2:c087690000000000 3:4053c00000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 0:0 1:c08aae0000000000 2:4089660000000000 +result host=h1,job=x ; 3:3ff9a38f0b33076c +result host=h1,job=x,zone=z2 ; 1:4002aeeae3b4f170 2:bfe7d474561401df +result host=h2,job=x ; 6:bff93a59110050e1 7:bff93117e1c9f2e5 +result job=x,zone=z2 ; 0:bff921fb54442d18 +end +case binary / false on host,zone one - 1 1 +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 1:c07bb60000000000 3:7ff0000000000000 4:40835f0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 0:c087120000000000 1:7e37e43c8800759c 2:40775e0000000000 3:c0839a0000000000 4:407f120000000000 5:c0869e0000000000 +series __name__=b,host=h1,job=x ; 4:c08e610000000000 5:c05c000000000000 6:408c490000000000 +series __name__=b,host=h2,job=x ; 0:c067400000000000 1:7ff8000000000001 2:c0756e0000000000 +result host=h1 ; 4:bf50da929d696f5c 5:bf82492492492492 6:3f5219f333a70c7b +result host=h2 ; 0:bf76058160581606 1:7ff8000000000001 2:bf67e45ff1114409 3:7ff0000000000000 4:40835f0000000000 +result host=h2,zone=z2 ; 0:bf56316a061182fe 1:1a56e1fc2f8f359 2:3f65e93ba8036c71 3:bf5a1ed059c9ec35 4:3f607a8f8b9e6a36 5:bf56a33d1a9deed8 +end +case binary != true ignoring host left host,job,zone -2.5 1 +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 0:c05d580000000000 1:c08b240000000000 2:4082c00000000000 5:407d1a0000000000 6:408cb50000000000 +series __name__=a,host=h1,job=x ; 3:c0797e0000000000 4:0 5:40744e0000000000 6:40841e0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:7e37e43c8800759c 4:408b010000000000 5:7ff8000000000001 +series __name__=b,host=h1,job=x ; 5:408a370000000000 6:c078900000000000 +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary < false ignoring host,job,zone right job 1 1 +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 2:7ff8000000000001 4:c07dc00000000000 5:408d360000000000 +series __name__=b,host=h2,job=y ; 10:40843c0000000000 11:4076e20000000000 +result __name__=b,host=h2 ; 10:3ff0000000000000 11:3ff0000000000000 +result job=y ; 4:c07dc00000000000 +end +case binary <= true none - one - - 1 +grid 100000 10000 11 +series __name__=a,host=h2,job=x,zone=z1 ; 2:c0837b0000000000 3:4079ae0000000000 4:0 5:7ff8000000000001 6:4083470000000000 +series __name__=a,host=h1,job=x ; 9:c0802b0000000000 +series __name__=a,host=h2,job=x ; 4:4081dd0000000000 5:408d5e0000000000 6:c0834d0000000000 7:7ff0000000000000 8:408af60000000000 9:c083ec0000000000 10:c07ac00000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 4:4076d80000000000 5:4071320000000000 6:407c8a0000000000 +series __name__=a,host=h1,job=y ; 10:c053180000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +result host=h1,job=x ; 9:3ff0000000000000 +result host=h1,job=y ; 10:3ff0000000000000 +result host=h1,job=y,zone=z1 ; 4:0 5:0 6:0 +result host=h2,job=x ; 4:0 5:0 6:3ff0000000000000 7:0 8:0 9:3ff0000000000000 10:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 2:3ff0000000000000 3:0 4:3ff0000000000000 5:0 6:0 +end +case binary - false ignoring host left host,job -2.5 1 +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 3:4078760000000000 6:4082720000000000 +series __name__=a,host=h2,job=y ; 5:7ff8000000000001 +series __name__=b,host=h1,job=x ; 5:4087710000000000 6:4071c40000000000 +series __name__=b,host=h2,job=y ; 1:c06ef80000000000 2:c0811b0000000000 +series __name__=b,host=h2,job=x ; 3:c077000000000000 4:c053e80000000000 5:4077a20000000000 6:408b1b0000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary == true on zone right job 1 -2.5 +grid 100000 10000 7 +series __name__=a,host=h1,job=y ; 2:40831e0000000000 3:7ff8000000000001 4:c084b80000000000 +series __name__=a,host=h2,job=y ; 0:c07aca0000000000 2:c0838f0000000000 4:c0769e0000000000 +series __name__=a,host=h1,job=x ; 1:c084be0000000000 2:0 3:4075260000000000 5:408cf10000000000 6:4081880000000000 +series __name__=a,host=h2,job=x ; 6:7ff8000000000001 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=y ; 2:4085920000000000 4:4086270000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 6:c083820000000000 +series __name__=b,host=h1,job=x ; 4:fff0000000000000 5:c0709c0000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h1", job="y"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary > false none - one - NaN NaN +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 1:4079ea0000000000 2:c086b40000000000 3:408c0e0000000000 4:407b780000000000 5:405a280000000000 6:c074320000000000 +series __name__=a,host=h2,job=y ; 5:c08c210000000000 7:7e37e43c8800759c +series __name__=a,host=h2,job=x,zone=z1 ; 5:4086300000000000 6:c080970000000000 +series __name__=a,host=h2,job=x ; 5:4080390000000000 7:407d4e0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:c0864b0000000000 5:c014000000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 4:c080180000000000 +series __name__=b,host=h1,job=x ; 1:c07cf60000000000 2:40857f0000000000 4:4080340000000000 +result __name__=a,host=h1,job=x ; 1:4079ea0000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 5:4086300000000000 +end +case binary / false ignoring job,zone right job -2.5 NaN +grid 100000 10000 1 +series __name__=a,host=h2,job=y,zone=z1 ; 0:4086be0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c0898b0000000000 +series __name__=b,host=h1,job=y ; 0:c072680000000000 +result host=h1 ; 0:7ff8000000000001 +result host=h2,job=y,zone=z1 ; 0:bfec7dbfb7568f5e +end +case binary ^ false on job one - - 1 +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 2:408a630000000000 4:7ff8000000000001 5:4055200000000000 6:0 +series __name__=b,host=h1,job=x ; 2:c0820b0000000000 3:c079f00000000000 4:c076a20000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 6:fff0000000000000 +series __name__=b,host=h2,job=x ; 1:4063340000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:40881b0000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h2", job="x", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary > true ignoring zone left job 1 1 +grid 100000 10000 11 +series __name__=a,host=h1,job=y ; 2:7ff8000000000001 3:4087400000000000 4:c083360000000000 5:c07fd40000000000 6:4072c80000000000 7:407ac00000000000 8:40786c0000000000 9:c083620000000000 +series __name__=b,host=h1,job=y ; 7:fff0000000000000 8:4070b00000000000 10:c043e00000000000 +result host=h1,job=y ; 2:0 3:3ff0000000000000 4:0 5:0 6:3ff0000000000000 7:3ff0000000000000 8:3ff0000000000000 9:0 10:3ff0000000000000 +end +case binary * false on zone one - Inf Inf +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 4:7ff8000000000001 +series __name__=a,host=h1,job=x,zone=z1 ; 1:7ff0000000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 5:4062140000000000 +series __name__=a,host=h1,job=x ; 0:40613c0000000000 1:0 3:4064b80000000000 4:7ff8000000000001 5:408e320000000000 +series __name__=b,host=h1,job=y ; 6:c082940000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary != true on zone one - 1 0 +grid 100000 10000 10 +series __name__=a,host=h2,job=y,zone=z1 ; 5:402e400000000000 6:c0700c0000000000 7:40852b0000000000 8:4058780000000000 +series __name__=a,host=h2,job=x ; 4:c033400000000000 5:4078820000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 2:c083d60000000000 +series __name__=a,host=h2,job=y ; 5:405d680000000000 +series __name__=b,host=h2,job=x ; 8:c043500000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary != true ignoring zone right zone Inf Inf +grid 100000 10000 9 +series __name__=a,host=h2,job=x ; 6:c083e60000000000 +series __name__=b,host=h1,job=x ; 0:c07c740000000000 1:c055e00000000000 2:4050900000000000 4:c075060000000000 6:c03e200000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 2:c03c400000000000 4:405c580000000000 +series __name__=b,host=h2,job=x ; 4:c08a620000000000 6:fff0000000000000 7:c087ff0000000000 +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary + false ignoring job right zone 0 Inf +grid 100000 10000 8 +series __name__=a,host=h2,job=x,zone=z1 ; 1:406cf80000000000 2:4071a40000000000 5:c08a6e0000000000 6:408a5d0000000000 +series __name__=a,host=h1,job=y ; 0:408eb30000000000 1:c085ad0000000000 2:4066e80000000000 3:407ea60000000000 5:c080320000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=b,host=h2,job=x ; 6:c07a260000000000 +result host=h1 ; 0:408eb30000000000 1:c085ad0000000000 2:4066e80000000000 3:407ea60000000000 5:c080320000000000 +result host=h2,job=x ; 6:7ff0000000000000 +result host=h2,zone=z1 ; 1:406cf80000000000 2:4071a40000000000 5:c08a6e0000000000 6:408a5d0000000000 +end +case binary / false ignoring job left zone - 1 +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 6:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 4:4051700000000000 +series __name__=b,host=h2,job=y ; 6:4080640000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 5:4089570000000000 6:407f2a0000000000 +result host=h1,job=y,zone=z1 ; 6:7da8884c045da7ef +end +case binary ^ false ignoring zone left host NaN NaN +grid 100000 10000 11 +series __name__=a,host=h1,job=y ; 3:c088050000000000 4:c0825e0000000000 5:fff0000000000000 6:4071800000000000 7:4083ee0000000000 8:c0773a0000000000 9:c08e590000000000 +series __name__=a,host=h2,job=x ; 5:407f1a0000000000 7:c076240000000000 8:40754a0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=x,zone=z1 ; 9:c084030000000000 10:408c230000000000 +series __name__=a,host=h1,job=x ; 7:4071e60000000000 8:7ff0000000000000 9:c083990000000000 10:c059a80000000000 +series __name__=b,host=h2,job=x ; 1:40824b0000000000 5:7e37e43c8800759c 6:4078200000000000 7:c029000000000000 8:7ff8000000000001 9:408c9e0000000000 10:4083c80000000000 +series __name__=b,host=h1,job=y ; 3:4076080000000000 +series __name__=b,host=h2,job=y ; 7:40875b0000000000 8:c069d80000000000 9:402f400000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 10:c046200000000000 +result host=h1,job=x ; 7:7ff8000000000001 8:7ff8000000000001 9:7ff8000000000001 10:7ff8000000000001 +result host=h1,job=y ; 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 8:7ff8000000000001 9:7ff8000000000001 +result host=h2,job=x ; 1:7ff8000000000001 5:7ff0000000000000 6:7ff8000000000001 7:7ff8000000000001 8:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 9:7ff8000000000001 10:7ff0000000000000 +result host=h2,job=y ; 7:7ff8000000000001 8:7ff8000000000001 9:7ff8000000000001 +end +case binary atan2 false ignoring host,zone one - Inf 0 +grid 100000 10000 10 +series __name__=a,host=h1,job=y ; 1:7ff8000000000001 +series __name__=a,host=h1,job=x ; 3:405e980000000000 4:0 5:c08e6a0000000000 6:4008000000000000 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=x,zone=z1 ; 7:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 6:40832c0000000000 7:c051b80000000000 +series __name__=b,host=h2,job=x ; 0:4076d20000000000 1:c085f00000000000 2:c070740000000000 +result job=x ; 0:3ff921fb54442d18 1:3ff921fb54442d18 2:3ff921fb54442d18 3:3ff921fb54442d18 4:0 5:bff921fb54442d18 6:3ff921fb54442d18 7:7ff8000000000001 +result job=y ; 1:7ff8000000000001 6:3ff921fb54442d18 7:bff921fb54442d18 +end +case binary atan2 false on job left host Inf Inf +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 4:7e37e43c8800759c +series __name__=a,host=h2,job=x ; 6:c0779c0000000000 +series __name__=a,host=h2,job=y ; 2:4084890000000000 3:40683c0000000000 +series __name__=a,host=h1,job=y ; 4:7ff8000000000001 5:404f400000000000 6:c078e40000000000 +series __name__=a,host=h1,job=x ; 3:40759a0000000000 4:40802c0000000000 +series __name__=b,host=h2,job=y ; 2:c0756e0000000000 3:c087bb0000000000 4:7ff8000000000001 5:406f180000000000 +series __name__=b,host=h1,job=x ; 0:405c080000000000 1:c08a590000000000 2:c06ba80000000000 3:408b9d0000000000 4:c085fb0000000000 6:c071a80000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=y ; +result host=h1,job=x ; 0:3ff921fb54442d18 1:3ff921fb54442d18 2:3ff921fb54442d18 3:3fd7dcc2324c75d2 4:40040ee9aa8e1ec7 6:c001b40f1bbfa192 +result host=h2,job=y ; 2:400069ea22eca411 3:4007220bb590d0da 4:7ff8000000000001 5:3fcf823194bd196f +result host=h2,job=y,zone=z1 ; 4:7ff8000000000001 +result job=y ; 6:8000000000000000 +end +case binary * false on job,zone right host Inf -2.5 +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 4:406f000000000000 5:40837e0000000000 7:c06bbc0000000000 +series __name__=a,host=h1,job=x ; 7:c06bb80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 3:7ff8000000000001 4:40713e0000000000 5:4083990000000000 6:408e8a0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c07a780000000000 3:406a400000000000 4:4056380000000000 +series __name__=b,host=h1,job=x ; 5:7ff8000000000001 6:4084bf0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 5:c06f5c0000000000 7:7ff8000000000001 +series __name__=b,host=h2,job=y ; 1:c0746e0000000000 2:40870f0000000000 3:4083c60000000000 +result host=h1,job=x ; 7:fff0000000000000 +result host=h1,job=x,zone=z1 ; 3:7ff8000000000001 4:7ff0000000000000 5:c103348fe0000000 6:7ff0000000000000 +result host=h2,job=y ; 4:7ff0000000000000 5:7ff0000000000000 7:fff0000000000000 +result job=x ; 5:7ff8000000000001 6:c099eec000000000 +result job=x,zone=z1 ; 7:7ff8000000000001 +result job=y ; 1:4089898000000000 2:c09cd2c000000000 3:c098b78000000000 +result job=y,zone=z1 ; 2:40908b0000000000 3:c080680000000000 4:c06bc60000000000 +end +case binary % false ignoring host,job,zone right host,zone NaN NaN +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 1:4085090000000000 2:408b8b0000000000 4:4076ba0000000000 5:c083b20000000000 7:c088480000000000 8:4081130000000000 9:c080580000000000 10:c07dd60000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 5:c08de20000000000 6:7ff8000000000001 7:7ff0000000000000 8:40868c0000000000 9:4081ba0000000000 10:c076ce0000000000 +series __name__=a,host=h1,job=x ; 8:40756c0000000000 +series __name__=b,host=h1,job=x ; 4:c0870e0000000000 +series __name__=b,host=h2,job=x ; 2:c084150000000000 4:c078020000000000 5:c07e220000000000 +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary + false ignoring - right host Inf - +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; 0:c085f60000000000 +series __name__=a,host=h1,job=x ; 0:c067700000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +series __name__=b,host=h1,job=x ; 0:4065d80000000000 +result host=h1,job=x ; 0:c029800000000000 +result host=h2,job=y ; 0:7ff0000000000000 +end +case binary > true on host,job,zone right - 0 - +grid 100000 10000 11 +series __name__=a,host=h1,job=x,zone=z1 ; 2:c0898e0000000000 3:408cb50000000000 4:c056080000000000 5:408e490000000000 6:c042c00000000000 7:c053a80000000000 8:fff0000000000000 +series __name__=a,host=h1,job=x ; 3:c069100000000000 +series __name__=a,host=h1,job=y ; 2:40828b0000000000 3:c0845d0000000000 4:c06ff40000000000 6:c01b800000000000 7:40846f0000000000 8:c0807f0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 7:4085780000000000 8:c085210000000000 9:c0700a0000000000 +series __name__=b,host=h1,job=x ; 5:c0789e0000000000 7:7ff8000000000001 +series __name__=b,host=h2,job=y ; 8:404d400000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 10:40864f0000000000 +result host=h1,job=x ; 3:0 +result host=h1,job=x,zone=z1 ; 2:0 3:3ff0000000000000 4:0 5:3ff0000000000000 6:0 7:0 8:0 +result host=h1,job=y ; 2:3ff0000000000000 3:0 4:0 6:0 7:3ff0000000000000 8:0 +end +case binary < false ignoring job,zone right - - 1 +grid 100000 10000 4 +series __name__=a,host=h1,job=y,zone=z1 ; 0:4087720000000000 1:4082dd0000000000 2:0 3:c07b700000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:c0705a0000000000 1:c0866e0000000000 +end +case binary + false none - one - NaN - +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 10:407b2c0000000000 +series __name__=a,host=h2,job=y ; 3:c08ea20000000000 +series __name__=a,host=h2,job=x ; 3:c08d240000000000 4:c07db20000000000 6:407a220000000000 7:fff0000000000000 8:4071e60000000000 9:4054b80000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 5:c083b40000000000 6:405c680000000000 7:c087080000000000 8:4085ac0000000000 +series __name__=b,host=h2,job=y ; 7:c08a650000000000 9:c047200000000000 10:4060980000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 9:c07d540000000000 10:4077dc0000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 3:4083d10000000000 4:4057000000000000 5:c03a000000000000 6:4074a20000000000 7:4089040000000000 8:c0861f0000000000 +series __name__=b,host=h1,job=x ; 1:c08b870000000000 +result host=h1,job=x ; 1:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 9:7ff8000000000001 10:7ff8000000000001 +result host=h2,job=y ; 7:7ff8000000000001 9:7ff8000000000001 10:7ff8000000000001 +result host=h2,job=y,zone=z1 ; 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 8:7ff8000000000001 +result host=h2,job=y,zone=z2 ; 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 8:7ff8000000000001 +end +case binary + false on - right host,job,zone NaN - +grid 100000 10000 1 +series __name__=a,host=h2,job=y,zone=z1 ; 0:0 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c066d00000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c071840000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h2", job="x", zone="z1"}, {__name__="a", host="h2", job="y", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary atan2 false on job one - 0 - +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 7:c089420000000000 +series __name__=a,host=h2,job=y ; 6:4082390000000000 7:7ff0000000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:4073f80000000000 1:4058980000000000 2:c07ad20000000000 3:c083740000000000 4:c085fc0000000000 5:4074740000000000 6:c07a3c0000000000 +series __name__=a,host=h1,job=y ; 0:c087d90000000000 1:c06f380000000000 2:c086380000000000 3:7ff8000000000001 4:c089710000000000 +series __name__=b,host=h2,job=y ; 2:c085140000000000 3:40794a0000000000 4:407d500000000000 6:40862c0000000000 7:4072140000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 2:408a6d0000000000 3:407f0a0000000000 4:406be00000000000 5:4077e40000000000 +series __name__=b,host=h1,job=y ; 5:c05aa80000000000 6:40764a0000000000 +error found duplicate series for the match group {job="y"} on the right hand-side of the operation: [{__name__="b", host="h1", job="y"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary > false on host left zone 0 -2.5 +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:7ff0000000000000 +series __name__=a,host=h2,job=y ; 0:40853d0000000000 +series __name__=a,host=h2,job=x ; 0:7e37e43c8800759c +series __name__=b,host=h2,job=y ; 0:c058400000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c08a290000000000 +series __name__=b,host=h2,job=x ; 0:c065f00000000000 +error found duplicate series for the match group {host="h2"} on the right hand-side of the operation: [{__name__="b", host="h2", job="y", zone="z1"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary / false on zone left host - 0 +grid 100000 10000 4 +series __name__=a,host=h1,job=y ; 3:c084bb0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 3:4088690000000000 +series __name__=a,host=h2,job=x ; +series __name__=b,host=h2,job=x,zone=z2 ; 0:4084610000000000 1:c063440000000000 +series __name__=b,host=h2,job=x ; 2:c0619c0000000000 +series __name__=b,host=h1,job=y ; 1:7ff8000000000001 2:c062d00000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h1", job="y"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true none - one - Inf Inf +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 1:c085100000000000 2:c0892e0000000000 3:c07b9c0000000000 4:c08eee0000000000 5:fff0000000000000 6:4085140000000000 8:7ff8000000000001 10:c07a040000000000 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=b,host=h1,job=x ; 10:c087820000000000 +series __name__=b,host=h2,job=y ; 2:0 3:407ef60000000000 4:4066e80000000000 5:c082300000000000 6:c06d180000000000 7:4063040000000000 8:406e3c0000000000 9:c08b7b0000000000 +series __name__=b,host=h2,job=x ; +result host=h1,job=x ; 1:0 2:0 3:0 4:0 5:0 6:0 8:0 10:3ff0000000000000 +result host=h2,job=y ; 2:3ff0000000000000 3:3ff0000000000000 4:3ff0000000000000 5:3ff0000000000000 6:3ff0000000000000 7:3ff0000000000000 8:3ff0000000000000 9:3ff0000000000000 +end +case binary >= true none - one - 0 - +grid 100000 10000 8 +series __name__=a,host=h1,job=x,zone=z1 ; 4:c081a50000000000 5:40862a0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 4:408c480000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +result host=h1,job=x,zone=z2 ; 4:0 +end +case binary * false ignoring host left host,zone Inf Inf +grid 100000 10000 5 +series __name__=a,host=h2,job=x ; 1:c062d80000000000 2:4082790000000000 3:4080010000000000 +series __name__=b,host=h2,job=x ; 0:fff0000000000000 3:4084d20000000000 +result host=h2,job=x ; 0:fff0000000000000 3:4114d34d20000000 +result job=x ; 1:fff0000000000000 2:7ff0000000000000 +end +case binary + false on job,zone right - - Inf +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:c074c20000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c0878a0000000000 +series __name__=a,host=h1,job=y ; 0:c0838a0000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h1,job=y,zone=z2 ; +end +case binary == true ignoring zone left job Inf Inf +grid 100000 10000 5 +series __name__=a,host=h2,job=y ; 2:c063e40000000000 4:4075380000000000 +series __name__=a,host=h1,job=x ; 4:c07ea40000000000 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h1,job=y ; 2:408c550000000000 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:c087e00000000000 1:7ff0000000000000 2:0 +series __name__=b,host=h2,job=y ; 0:4060940000000000 1:c08b5e0000000000 +series __name__=b,host=h2,job=x ; 2:408c0a0000000000 3:c076120000000000 +error found duplicate series for the match group {host="h2", job="y"} on the right hand-side of the operation: [{__name__="b", host="h2", job="y", zone="z1"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary / false ignoring host,job,zone one - -2.5 NaN +grid 100000 10000 11 +series __name__=a,host=h1,job=x ; 10:0 +series __name__=a,host=h1,job=x,zone=z1 ; 4:c08d580000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 8:c06ef40000000000 9:4087360000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 3:c067480000000000 4:7ff8000000000001 5:c07b1a0000000000 6:408e620000000000 7:c060d40000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 8:c08bf80000000000 9:c08e620000000000 +series __name__=b,host=h1,job=x ; 5:4083bb0000000000 6:c084f70000000000 7:c0702c0000000000 8:c086e70000000000 9:c07fc20000000000 10:40840b0000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h1", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary * false on job left zone 0 0 +grid 100000 10000 10 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=x,zone=z1 ; 2:7ff0000000000000 4:c0806f0000000000 5:c081450000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 5:7ff8000000000001 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c069ac0000000000 1:0 2:7ff8000000000001 3:c074c40000000000 4:c064b40000000000 5:404ba00000000000 6:40773a0000000000 7:4074c00000000000 +series __name__=b,host=h2,job=x ; 5:c05f500000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 7:c08b4e0000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h2", job="x", zone="z1"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary < true ignoring job right zone - -2.5 +grid 100000 10000 11 +series __name__=a,host=h1,job=y ; 8:7e37e43c8800759c +series __name__=a,host=h2,job=y ; 6:c05e480000000000 7:c084800000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c08c670000000000 2:407bd00000000000 3:0 4:4078840000000000 5:40781a0000000000 6:40849c0000000000 8:408ea10000000000 9:40743e0000000000 10:4075fa0000000000 +series __name__=b,host=h1,job=y ; 7:c08a420000000000 9:405f180000000000 +result host=h1,job=y ; 7:0 9:3ff0000000000000 +end +case binary % false on job left zone NaN NaN +grid 100000 10000 1 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; +end +case binary == true on host left - 0 0 +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 6:7ff8000000000001 +series __name__=a,host=h1,job=x ; 3:c07cd00000000000 4:405c100000000000 5:4038200000000000 6:c082350000000000 +series __name__=a,host=h1,job=y ; 3:7ff8000000000001 4:4086b90000000000 5:c05f800000000000 +series __name__=a,host=h2,job=x ; 2:4078320000000000 3:c07b060000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 5:c071e40000000000 6:c089450000000000 +series __name__=b,host=h1,job=y ; +result host=h1,job=x ; 3:0 4:0 5:0 6:0 +result host=h1,job=y ; 3:0 4:0 5:0 +result host=h1,job=y,zone=z1 ; 6:0 +result host=h2,job=x ; 2:0 3:0 +end +case binary >= true none - one - - 0 +grid 100000 10000 1 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c07d920000000000 +series __name__=a,host=h1,job=y ; +series __name__=b,host=h1,job=y ; 0:c086300000000000 +result host=h1,job=y,zone=z1 ; 0:0 +end +case binary * false ignoring - left host,job,zone - 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h2,job=x ; 1:406bc40000000000 2:c076f60000000000 4:408ab90000000000 +series __name__=a,host=h1,job=x ; 1:c085130000000000 +series __name__=a,host=h2,job=y ; 5:4063240000000000 +series __name__=b,host=h2,job=x ; 4:7e37e43c8800759c 5:406be00000000000 +result host=h1,job=x ; 1:c085130000000000 +result host=h2,job=x ; 1:406bc40000000000 2:c076f60000000000 4:7ed3f390ac72a237 +result host=h2,job=y ; 5:4063240000000000 +end +case binary * false none - one - - 1 +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 7:7e37e43c8800759c 10:c07d680000000000 +series __name__=b,host=h2,job=y ; 7:7ff8000000000001 8:405f200000000000 9:4085470000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 2:c063540000000000 3:40754e0000000000 4:4086db0000000000 5:c05ba80000000000 6:c052200000000000 7:4084fd0000000000 8:c059800000000000 9:4083c20000000000 10:c08a990000000000 +end +case binary atan2 false ignoring job,zone,__name__ left - NaN Inf +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 4:408c340000000000 5:c071ea0000000000 7:c07d800000000000 +series __name__=a,host=h2,job=y ; 11:408ec80000000000 +series __name__=a,host=h2,job=x ; 2:c05a700000000000 3:407b000000000000 5:c078d40000000000 6:c084d50000000000 +series __name__=b,host=h2,job=y ; 6:c05e380000000000 8:c08c200000000000 9:4082a60000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 8:4088d10000000000 10:c0854c0000000000 +series __name__=b,host=h1,job=x ; 10:7ff8000000000001 +error found duplicate series for the match group {host="h2"} on the right hand-side of the operation: [{__name__="b", host="h2", job="y", zone="z1"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary < false ignoring zone right zone 0 Inf +grid 100000 10000 9 +series __name__=a,host=h2,job=y ; 5:4086fd0000000000 6:408ced0000000000 8:c07d6e0000000000 +series __name__=a,host=h1,job=x ; 4:407b060000000000 5:c068b40000000000 6:c07bee0000000000 +series __name__=b,host=h2,job=y ; 4:4059c00000000000 5:4083760000000000 +series __name__=b,host=h1,job=x ; 2:c084730000000000 3:408ac60000000000 4:4042d00000000000 5:c08daf0000000000 6:40736c0000000000 7:40785a0000000000 +result __name__=b,host=h1,job=x ; 6:c07bee0000000000 +result host=h2,job=y ; 8:c07d6e0000000000 +end +case binary / false none - one - - Inf +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; 3:c0846b0000000000 +series __name__=a,host=h1,job=y ; 1:fff0000000000000 2:4081260000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h2,job=x ; 3:c052200000000000 +result host=h1,job=y ; 1:fff8000000000000 2:0 +result host=h2,job=x ; 3:4022062de74862de +end +case binary + false ignoring host left host - 1 +grid 100000 10000 2 +series __name__=a,host=h1,job=y ; 0:7e37e43c8800759c 1:c066000000000000 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h1,job=y,zone=z1 ; 1:7ff8000000000001 +series __name__=a,host=h2,job=y ; 0:c06aa80000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:408e4e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:0 +series __name__=b,host=h2,job=x ; 0:c07a6c0000000000 +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary == false ignoring job right host - 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c08b920000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 5:4065f80000000000 +series __name__=a,host=h2,job=y ; 2:c081b20000000000 3:7ff0000000000000 4:c08b780000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 5:c053e80000000000 +series __name__=b,host=h1,job=y ; 3:c08cea0000000000 +series __name__=b,host=h2,job=y ; 4:40839f0000000000 +end +case binary == true none - one - 1 0 +grid 100000 10000 8 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z1 ; 3:407f220000000000 4:40823d0000000000 5:c077e00000000000 6:406da00000000000 +result host=h2,job=x,zone=z1 ; 3:0 4:0 5:0 6:0 +end +case binary atan2 false on - one - - Inf +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; 0:408f3e0000000000 2:4045100000000000 +series __name__=a,host=h1,job=y ; 2:7ff0000000000000 +series __name__=a,host=h2,job=x ; 0:c07d6c0000000000 1:c083350000000000 2:c07be60000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c088240000000000 +series __name__=b,host=h2,job=x ; 1:c048e00000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary > true ignoring - left job - 0 +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 3:406e580000000000 +series __name__=b,host=h2,job=x ; 3:c07e2c0000000000 4:4079080000000000 +result host=h2,job=x ; 3:3ff0000000000000 +end +case binary <= false none - one - - 1 +grid 100000 10000 11 +series __name__=a,host=h1,job=x ; 8:408c2c0000000000 9:7ff8000000000001 +series __name__=a,host=h2,job=y,zone=z1 ; 3:c08b430000000000 4:4081930000000000 +series __name__=a,host=h1,job=y ; 6:404a100000000000 7:406b0c0000000000 8:4087650000000000 +series __name__=b,host=h1,job=x ; 1:40805c0000000000 2:c085350000000000 3:c08ab20000000000 +series __name__=b,host=h2,job=x ; 10:c046b00000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 6:c036600000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 3:c08b430000000000 +end +case binary - false on - one - - Inf +grid 100000 10000 4 +series __name__=a,host=h1,job=y ; 2:4033200000000000 +series __name__=a,host=h2,job=x ; 3:4065300000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c079b40000000000 2:4067e40000000000 3:c07d680000000000 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=b,host=h2,job=y ; 2:4083dc0000000000 3:405e300000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:4061d80000000000 +series __name__=b,host=h2,job=x ; 1:c08a940000000000 2:c0711c0000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h2", job="x"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary < false none - one - -2.5 - +grid 100000 10000 5 +series __name__=a,host=h2,job=x ; 2:c08bc10000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:c085410000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:c078c20000000000 +series __name__=a,host=h2,job=y ; 0:c0879b0000000000 1:c07b4a0000000000 2:4085d90000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=x,zone=z1 ; 2:4045000000000000 +result host=h1,job=x,zone=z1 ; 2:c004000000000000 +end +case binary - false on host,zone left job 0 - +grid 100000 10000 11 +series __name__=a,host=h1,job=x ; 7:c083f60000000000 8:408b790000000000 9:c08b180000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:4081690000000000 2:c071360000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:4074e00000000000 2:c080a20000000000 3:c087250000000000 4:c082b40000000000 5:7ff8000000000001 7:4031600000000000 8:406a1c0000000000 9:c066f80000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:7ff8000000000001 +series __name__=b,host=h2,job=x,zone=z1 ; 4:c07bd60000000000 6:405c500000000000 +series __name__=b,host=h2,job=y ; 4:c06cd80000000000 5:4079080000000000 6:c08e010000000000 7:c087b80000000000 +result host=h1,job=y,zone=z1 ; 0:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 4:c063240000000000 6:c05c500000000000 +result host=h2,job=y ; 4:406cd80000000000 5:c079080000000000 6:408e010000000000 7:4087b80000000000 +end +case binary + false ignoring job,zone right - - 0 +grid 100000 10000 7 +series __name__=a,host=h1,job=x ; 3:7ff8000000000001 +series __name__=a,host=h2,job=x,zone=z1 ; 0:0 1:40734a0000000000 2:c082680000000000 3:c051d00000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 4:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 4:c082710000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 2:408e860000000000 4:4084ef0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:c07d940000000000 2:c0848b0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 2:c063c80000000000 3:7e37e43c8800759c +error found duplicate series for the match group {host="h1"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h1", job="y", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary - false on host one - NaN - +grid 100000 10000 1 +series __name__=a,host=h2,job=x,zone=z1 ; 0:0 +series __name__=a,host=h2,job=y,zone=z1 ; 0:4081920000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c07cac0000000000 +series __name__=b,host=h1,job=y ; 0:c03da00000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary * false on zone left - - -2.5 +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c081bd0000000000 4:fff0000000000000 5:c06e340000000000 +series __name__=a,host=h1,job=x ; 1:c080030000000000 3:c051780000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:4083a50000000000 +result host=h1,job=x ; 1:409403c000000000 3:4065d60000000000 +result host=h1,job=y,zone=z1 ; 3:40962c4000000000 4:7ff0000000000000 5:4082e08000000000 +end +case binary / false on host left - Inf 0 +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 5:7ff8000000000001 6:c088ee0000000000 +series __name__=a,host=h1,job=y ; 1:40756a0000000000 +series __name__=a,host=h2,job=y ; 6:7ff8000000000001 7:c08e8b0000000000 +series __name__=a,host=h2,job=x ; 2:40679c0000000000 3:408b9b0000000000 6:407e900000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 7:7e37e43c8800759c +series __name__=b,host=h1,job=x ; 1:4075760000000000 2:4080c00000000000 3:4047700000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 7:c03e600000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 1:c08e910000000000 +error found duplicate series for the match group {host="h1"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h1", job="y", zone="z2"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary > false ignoring host,job,zone right - - -2.5 +grid 100000 10000 12 +series __name__=a,host=h2,job=x,zone=z1 ; 0:4068d80000000000 2:c06c540000000000 3:c08f070000000000 +series __name__=a,host=h2,job=x ; 0:407e180000000000 3:c040800000000000 4:c0813c0000000000 +series __name__=b,host=h2,job=x ; 7:4062340000000000 8:408a2d0000000000 9:4064d00000000000 +series __name__=b,host=h2,job=y ; 5:c062340000000000 7:c069900000000000 8:c0735e0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 5:7ff8000000000001 6:4077b00000000000 7:7ff8000000000001 8:c054480000000000 9:c080050000000000 10:c082160000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h2", job="x", zone="z1"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary != false on host,job,zone one - 1 - +grid 100000 10000 10 +series __name__=a,host=h2,job=y,zone=z1 ; 3:0 4:c085c60000000000 5:406e540000000000 6:c058b00000000000 7:c043a00000000000 8:7e37e43c8800759c 9:4079fc0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 4:c0730a0000000000 5:408add0000000000 7:c07bc00000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:7ff8000000000001 3:c077b20000000000 4:4084a40000000000 5:408dfc0000000000 6:7ff8000000000001 8:c069300000000000 +series __name__=b,host=h2,job=y ; 9:405fb00000000000 +result host=h1,job=y,zone=z1 ; 4:3ff0000000000000 5:3ff0000000000000 7:3ff0000000000000 +result host=h2,job=y ; 9:3ff0000000000000 +result host=h2,job=y,zone=z1 ; 2:3ff0000000000000 3:0 4:c085c60000000000 5:406e540000000000 6:c058b00000000000 8:7e37e43c8800759c +end +case binary == true ignoring - right - - 1 +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; +series __name__=b,host=h2,job=x ; 1:40800c0000000000 2:40756e0000000000 +series __name__=b,host=h2,job=y ; 2:407a100000000000 5:c08efe0000000000 6:4051a00000000000 7:40750e0000000000 +result host=h2,job=x ; 1:0 2:0 +result host=h2,job=y ; 2:0 5:0 6:0 7:0 +end +case binary * false ignoring job one - Inf Inf +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; 4:407e500000000000 5:4084930000000000 6:7ff8000000000001 7:c082e40000000000 8:0 9:c083b30000000000 +series __name__=a,host=h2,job=x ; 6:c086a90000000000 7:7ff8000000000001 +series __name__=a,host=h2,job=x,zone=z1 ; 7:7e37e43c8800759c 9:404c200000000000 +series __name__=a,host=h1,job=y ; 8:c081960000000000 9:c084c90000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 4:408f260000000000 5:40818f0000000000 6:c071600000000000 +series __name__=b,host=h1,job=x ; 6:c08e400000000000 +series __name__=b,host=h2,job=x ; 7:c0743c0000000000 8:40725c0000000000 +series __name__=b,host=h2,job=y ; 7:408d9c0000000000 8:c088c20000000000 +error found duplicate series for the match group {host="h2"} on the right hand-side of the operation: [{__name__="b", host="h2", job="x"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary + false on job,zone left host 1 - +grid 100000 10000 7 +series __name__=a,host=h2,job=x ; 6:405fb00000000000 +series __name__=a,host=h1,job=x ; 3:c089590000000000 4:4081250000000000 5:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z1 ; 3:4070220000000000 4:c085a90000000000 +series __name__=b,host=h2,job=x ; 0:c06cd80000000000 1:c087f90000000000 2:4081ae0000000000 3:c05ca00000000000 4:408ca50000000000 5:c082a30000000000 6:c080c00000000000 +series __name__=b,host=h1,job=x ; 4:4061500000000000 5:c075460000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary <= true ignoring job right job Inf - +grid 100000 10000 10 +series __name__=a,host=h2,job=x ; 5:c08c940000000000 6:c080ca0000000000 7:40844f0000000000 8:4079d80000000000 9:7ff8000000000001 +series __name__=a,host=h2,job=y ; 3:7e37e43c8800759c 4:405dd00000000000 5:4073b40000000000 +series __name__=a,host=h1,job=x ; 5:4076b20000000000 7:c081800000000000 8:c069f00000000000 9:40806f0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h1,job=y ; 0:7ff0000000000000 1:c070a20000000000 4:408a740000000000 5:4052980000000000 6:0 +series __name__=b,host=h2,job=y,zone=z2 ; 8:4080d70000000000 +series __name__=b,host=h2,job=y ; 4:c078020000000000 6:40859b0000000000 8:c058d00000000000 9:408b000000000000 +series __name__=b,host=h2,job=x,zone=z1 ; +error found duplicate series for the match group {host="h2"} on the left hand-side of the operation: [{__name__="a", host="h2", job="x"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary / false ignoring zone,__name__ right host,job - 0 +grid 100000 10000 6 +series __name__=a,host=h1,job=x,zone=z1 ; 5:407f040000000000 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=a,host=h2,job=y ; 2:c076c20000000000 3:7e37e43c8800759c 4:c08c8b0000000000 5:c082a30000000000 +series __name__=a,host=h2,job=x ; +series __name__=b,host=h1,job=x ; 5:c077520000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:40746c0000000000 4:0 5:4076260000000000 +result host=h1,job=x ; 5:bff5479c8412de20 +result host=h2,job=x,zone=z1 ; 3:0 4:fff8000000000000 5:0 +end +case binary == false none - one - - 0 +grid 100000 10000 4 +series __name__=a,host=h2,job=x ; 0:c076a40000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 3:4082b80000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:fff0000000000000 +series __name__=b,host=h2,job=x ; 1:c084d00000000000 2:7e37e43c8800759c +series __name__=b,host=h1,job=x,zone=z1 ; 0:4051c80000000000 1:40831f0000000000 +end +case binary / false ignoring host one - NaN 0 +grid 100000 10000 8 +series __name__=a,host=h1,job=x,zone=z1 ; 3:c04f800000000000 +series __name__=a,host=h1,job=x ; 2:7ff8000000000001 3:c081100000000000 4:c068f00000000000 6:c061f80000000000 7:c07ada0000000000 +series __name__=a,host=h2,job=y ; 5:c048a00000000000 +series __name__=b,host=h1,job=x ; 3:4080f40000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 2:40820e0000000000 3:7ff0000000000000 6:4070be0000000000 +series __name__=b,host=h2,job=y ; 4:7ff8000000000001 +series __name__=b,host=h2,job=x ; +result job=x ; 2:7ff8000000000001 3:bff01a6d01a6d01a 4:fff0000000000000 6:fff0000000000000 7:fff0000000000000 +result job=x,zone=z1 ; 2:7ff8000000000001 3:8000000000000000 6:7ff8000000000001 +result job=y ; 4:7ff8000000000001 5:fff0000000000000 +end +case binary - false ignoring job,zone left job,zone 1 - +grid 100000 10000 8 +series __name__=a,host=h2,job=x,zone=z1 ; 7:408a990000000000 +series __name__=a,host=h1,job=x ; 4:40826d0000000000 5:4079e00000000000 6:c0884f0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 7:c083520000000000 +series __name__=b,host=h1,job=x ; 2:c07e100000000000 3:4089290000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c08bea0000000000 1:c0879e0000000000 +result host=h1,job=x ; 2:407e200000000000 3:c089210000000000 +result host=h2,job=x,zone=z1 ; 0:408bf20000000000 1:4087a60000000000 +end +case binary <= true ignoring - left - - 0 +grid 100000 10000 2 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h1,job=y,zone=z1 ; 1:c08d500000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:4087300000000000 1:7ff0000000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:4079660000000000 +series __name__=b,host=h2,job=x ; +result host=h1,job=y,zone=z1 ; 1:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 0:0 1:0 +result host=h2,job=y,zone=z1 ; 0:0 +end +case binary atan2 false ignoring host,zone left - - 0 +grid 100000 10000 10 +series __name__=a,host=h2,job=x ; 3:408ced0000000000 4:c08e850000000000 6:408c2a0000000000 7:40661c0000000000 8:4080b30000000000 9:40803f0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 5:0 7:4080880000000000 8:40787a0000000000 9:c089a60000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 9:7e37e43c8800759c +series __name__=b,host=h1,job=x,zone=z1 ; 8:c089d10000000000 +series __name__=b,host=h2,job=x ; 8:408a550000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary < false ignoring host left job,zone 1 0 +grid 100000 10000 2 +series __name__=a,host=h1,job=y ; 0:c0871e0000000000 +series __name__=b,host=h1,job=y ; 0:7e37e43c8800759c 1:c061e00000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c080ae0000000000 +result __name__=a,host=h1,job=y ; 0:c0871e0000000000 +end +case binary >= false ignoring host,job right host,zone NaN 1 +grid 100000 10000 6 +series __name__=a,host=h1,job=y,zone=z1 ; 2:c083350000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 3:c065f80000000000 4:c066500000000000 5:408f3d0000000000 +series __name__=a,host=h1,job=x ; 4:c067a80000000000 +series __name__=a,host=h2,job=y ; 2:4072720000000000 +series __name__=b,host=h1,job=x ; 4:405fd00000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 2:c088f70000000000 3:c08ed80000000000 +result __name__=b,host=h1,job=x,zone=z1 ; 2:c083350000000000 +result __name__=b,host=h2,job=x,zone=z1 ; 3:c065f80000000000 +end +case binary % false ignoring - left host,job,zone - 1 +grid 100000 10000 5 +series __name__=a,host=h2,job=x ; 0:c071020000000000 1:404ac00000000000 +series __name__=a,host=h1,job=y ; 2:7e37e43c8800759c +series __name__=a,host=h2,job=y,zone=z1 ; 2:c054980000000000 3:c067580000000000 4:c031a00000000000 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=b,host=h1,job=y,zone=z2 ; 3:c081480000000000 +series __name__=b,host=h1,job=y ; 0:c08efb0000000000 +series __name__=b,host=h2,job=x ; 3:0 4:4048000000000000 +result host=h1,job=y ; 2:0 +result host=h2,job=x ; 0:bfc0000000000000 1:3fe0000000000000 +result host=h2,job=y,zone=z1 ; 2:bfd8000000000000 3:bfe8000000000000 4:bfe4000000000000 +end +case binary != true ignoring host,zone right job 1 1 +grid 100000 10000 8 +series __name__=a,host=h1,job=y ; 7:4071e00000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 6:c0673c0000000000 7:c087720000000000 +series __name__=a,host=h1,job=x ; 5:4061c00000000000 6:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z1 ; 3:c075fa0000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h1", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary > true on - left host 0 -2.5 +grid 100000 10000 7 +series __name__=a,host=h1,job=x ; 2:7ff0000000000000 +series __name__=a,host=h2,job=x ; 1:4089df0000000000 2:c066240000000000 3:4069580000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:c0759e0000000000 2:c07ab40000000000 3:c05ef80000000000 +series __name__=b,host=h2,job=x ; 1:c021c00000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 5:c080d60000000000 6:c080cd0000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h2", job="x", zone="z1"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true on job one - Inf - +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 1:c0893b0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:408c210000000000 +series __name__=a,host=h1,job=x ; 1:0 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:c065b00000000000 +series __name__=b,host=h1,job=x ; 0:c05ed80000000000 +result job=x ; 0:3ff0000000000000 +result job=y ; 0:3ff0000000000000 +end +case binary > true ignoring - left - 1 NaN +grid 100000 10000 7 +series __name__=a,host=h2,job=y ; 4:4057380000000000 +series __name__=a,host=h2,job=x ; 1:4089620000000000 +series __name__=b,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x ; 2:c080570000000000 3:c083d20000000000 +series __name__=b,host=h2,job=y ; 1:4065f80000000000 3:c071ea0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:c030600000000000 5:c086ee0000000000 6:c051800000000000 +result host=h1,job=x,zone=z1 ; 4:3ff0000000000000 5:3ff0000000000000 6:3ff0000000000000 +result host=h2,job=x ; 1:0 2:3ff0000000000000 3:3ff0000000000000 +result host=h2,job=y ; 1:0 3:3ff0000000000000 4:0 +end +case binary atan2 false ignoring host right zone 1 1 +grid 100000 10000 11 +series __name__=a,host=h1,job=x ; 3:7ff0000000000000 4:4032800000000000 5:c084db0000000000 7:4045000000000000 8:c07eee0000000000 +series __name__=a,host=h1,job=y ; 0:408e680000000000 1:c074960000000000 2:7ff8000000000001 3:408e350000000000 5:c078da0000000000 7:c080c20000000000 8:7ff8000000000001 9:407c220000000000 +series __name__=a,host=h2,job=x ; 2:c089610000000000 4:406fa00000000000 6:c069700000000000 7:c075120000000000 8:406e980000000000 9:c082ff0000000000 10:c055480000000000 +series __name__=b,host=h2,job=x ; 2:4053600000000000 +series __name__=b,host=h1,job=x ; 3:4077600000000000 4:4087d20000000000 5:40664c0000000000 6:7ff8000000000001 7:407aae0000000000 8:c05d080000000000 9:4086a70000000000 10:c07e420000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 7:c088c50000000000 8:c08e090000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true on host right zone NaN - +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 4:c07afe0000000000 5:4083ab0000000000 +series __name__=b,host=h1,job=x ; 2:c089f00000000000 +series __name__=b,host=h2,job=y ; 0:7ff0000000000000 1:4085c60000000000 +result host=h1 ; 4:0 5:0 +end +case binary >= false on host,job left zone - 1 +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h1,job=y ; 1:408aab0000000000 2:4087870000000000 +series __name__=b,host=h1,job=y ; 2:4083f80000000000 +series __name__=b,host=h2,job=y ; 1:7ff8000000000001 +result __name__=a,host=h1,job=y ; 1:408aab0000000000 2:4087870000000000 +end +case binary + false none - one - NaN - +grid 100000 10000 10 +series __name__=a,host=h2,job=y ; 4:4088500000000000 5:c08c5a0000000000 6:c07e140000000000 8:4008000000000000 +series __name__=a,host=h2,job=x ; 6:4084e10000000000 +series __name__=a,host=h1,job=x ; 1:7ff8000000000001 2:406a440000000000 3:7ff0000000000000 4:c080da0000000000 5:4084a00000000000 6:408c0d0000000000 7:c06c800000000000 +series __name__=b,host=h1,job=y ; 3:407aba0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 6:c08cbe0000000000 7:404cb00000000000 +series __name__=b,host=h2,job=y ; 9:4089120000000000 +result host=h1,job=y ; 3:7ff8000000000001 +result host=h2,job=y ; 9:7ff8000000000001 +result host=h2,job=y,zone=z1 ; 6:7ff8000000000001 7:7ff8000000000001 +end +case binary / false ignoring job right host,job NaN NaN +grid 100000 10000 11 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h1,job=y ; 7:c082570000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:4057b00000000000 8:c086f30000000000 9:408e4a0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:c08ee70000000000 5:c08da00000000000 6:4084cc0000000000 7:4053e00000000000 +result host=h1,job=y ; 7:7ff8000000000001 +result host=h1,zone=z1 ; 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 6:7ff8000000000001 8:7ff8000000000001 9:7ff8000000000001 +end +case binary % false on host,job right - - 1 +grid 100000 10000 2 +series __name__=a,host=h1,job=x,zone=z1 ; 0:7ff8000000000001 1:c0854c0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h1,job=x ; 1:c08ae10000000000 +series __name__=a,host=h2,job=y ; 1:c032400000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:407b320000000000 +series __name__=b,host=h1,job=x,zone=z2 ; +series __name__=b,host=h2,job=x,zone=z2 ; 0:c082480000000000 +series __name__=b,host=h1,job=x ; 1:fff0000000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:40750a0000000000 +error found duplicate series for the match group {host="h1", job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h1", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary ^ false on host,__name__ one - Inf Inf +grid 100000 10000 11 +series __name__=a,host=h1,job=y,zone=z1 ; 6:406b7c0000000000 7:408ca10000000000 +series __name__=b,host=h1,job=x ; 8:c07f700000000000 9:7e37e43c8800759c +result host=h1 ; 6:7ff0000000000000 7:7ff0000000000000 8:0 9:7ff0000000000000 +end +case binary ^ false ignoring host,job,__name__ right host - -2.5 +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 1:c076740000000000 +series __name__=a,host=h2,job=x ; 0:4077d20000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:40872e0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:408ba60000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4081050000000000 1:408e5c0000000000 +series __name__=b,host=h2,job=y ; 0:408c050000000000 +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary - false none - one - NaN - +grid 100000 10000 5 +series __name__=a,host=h2,job=x,zone=z1 ; 3:c08b7a0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 1:c083a50000000000 2:408ccf0000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h1,job=y,zone=z1 ; 1:c08c510000000000 2:c085420000000000 3:4072a40000000000 +series __name__=b,host=h2,job=x ; 3:7ff8000000000001 +result host=h1,job=y,zone=z1 ; 1:4071580000000000 2:4099088000000000 3:7ff8000000000001 +result host=h2,job=x ; 3:7ff8000000000001 +end +case binary - false ignoring zone right - 1 -2.5 +grid 100000 10000 1 +series __name__=a,host=h1,job=x,zone=z1 ; 0:c08b460000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4071560000000000 +series __name__=b,host=h1,job=x ; 0:7e37e43c8800759c +result host=h1,job=x ; 0:fe37e43c8800759c +result host=h1,job=x,zone=z1 ; 0:c091f88000000000 +end +case binary < true on zone one - -2.5 - +grid 100000 10000 7 +series __name__=a,host=h2,job=y ; 2:7ff0000000000000 +series __name__=a,host=h1,job=y ; 0:c083860000000000 1:407b200000000000 2:40813f0000000000 3:c08c720000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c086b30000000000 2:c075040000000000 3:406e600000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:40886f0000000000 5:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 6:c08aec0000000000 +series __name__=a,host=h1,job=x ; 6:c081630000000000 +series __name__=b,host=h1,job=y ; 6:4087e80000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 5:c057e80000000000 +series __name__=b,host=h1,job=x ; 1:4076e40000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:4064f80000000000 4:c08dda0000000000 +result - ; 1:0 6:3ff0000000000000 +result zone=z1 ; 3:0 4:0 5:0 +end +case binary / false on job left zone Inf - +grid 100000 10000 10 +series __name__=a,host=h2,job=y ; 7:408cad0000000000 +series __name__=a,host=h2,job=x ; 3:4035600000000000 4:40889f0000000000 5:4071880000000000 6:c0829f0000000000 7:406ae80000000000 +series __name__=a,host=h1,job=y ; 8:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 0:406f600000000000 1:c07d7e0000000000 2:c08cd50000000000 4:4084450000000000 5:407f080000000000 7:7ff8000000000001 8:4070940000000000 9:c087f40000000000 +series __name__=b,host=h2,job=x ; 4:c071080000000000 7:c07bf40000000000 8:c0698c0000000000 +result host=h1,job=y ; 8:7db70ef246f0470b +result host=h2,job=x ; 4:c0072159b7a99216 7:bfdecd335f28c856 +result host=h2,job=y ; 7:7ff8000000000001 +result job=x ; 8:fff0000000000000 +result job=y ; 0:7ff0000000000000 1:fff0000000000000 2:fff0000000000000 4:7ff0000000000000 5:7ff0000000000000 9:fff0000000000000 +end +case binary <= false on job,zone right - - Inf +grid 100000 10000 8 +series __name__=a,host=h2,job=x ; 5:40844e0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c072a40000000000 4:4064a00000000000 5:40797e0000000000 6:c086d30000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 5:c0805a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 5:c076a80000000000 6:4088a20000000000 7:40833b0000000000 +end +case binary > false on - one - - NaN +grid 100000 10000 9 +series __name__=a,host=h2,job=x,zone=z1 ; 7:40669c0000000000 8:c06aa00000000000 +series __name__=b,host=h2,job=x ; 2:c064000000000000 3:c07ba00000000000 4:c0847f0000000000 +end +case binary - false ignoring job one - - 0 +grid 100000 10000 6 +series __name__=a,host=h1,job=x ; 0:c07f360000000000 +series __name__=a,host=h2,job=y ; +series __name__=b,host=h1,job=x ; 0:7ff0000000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 4:c07d7e0000000000 5:4063a40000000000 +result host=h1 ; 0:fff0000000000000 +end +case binary atan2 false none - one - 0 - +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; 0:4083940000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:40870d0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; +end +case binary atan2 false ignoring zone left job -2.5 -2.5 +grid 100000 10000 2 +series __name__=a,host=h2,job=x,zone=z1 ; 1:408cf40000000000 +series __name__=a,host=h1,job=x ; 0:407d0c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 0:4045300000000000 +series __name__=a,host=h2,job=x ; 0:7ff8000000000001 +series __name__=b,host=h1,job=x ; 1:c07d480000000000 +result host=h1,job=x ; 0:3ff93803d00c19aa 1:c009170da933f265 +result host=h2,job=x ; 0:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 1:3ff92d08b928356f +result host=h2,job=y,zone=z1 ; 0:3ffa135a985b725c +end +case binary * false ignoring host,__name__ one - NaN NaN +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 0:4050a80000000000 1:c059a00000000000 +series __name__=a,host=h1,job=y ; 0:4079920000000000 2:4056400000000000 3:c08bb40000000000 4:4086850000000000 5:c06b7c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 5:4080d80000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:40768c0000000000 2:4085530000000000 3:7e37e43c8800759c 4:c0851c0000000000 +result job=x ; 0:7ff8000000000001 1:7ff8000000000001 +result job=y ; 0:7ff8000000000001 2:7ff8000000000001 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 +result job=y,zone=z1 ; 1:7ff8000000000001 2:7ff8000000000001 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 +end +case binary * false ignoring host,job,zone left zone NaN 0 +grid 100000 10000 9 +series __name__=a,host=h1,job=y,zone=z1 ; 6:4088140000000000 7:c07fcc0000000000 +series __name__=b,host=h1,job=x ; 7:407db60000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 6:c07d0c0000000000 +series __name__=b,host=h1,job=y ; 5:40831e0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 8:c08d650000000000 +result - ; 5:7ff8000000000001 +result host=h1,job=y ; 7:c10d85b840000000 +result host=h1,job=y,zone=z1 ; 6:c115db2780000000 +result zone=z1 ; 8:7ff8000000000001 +end +case binary - false on - left zone Inf 1 +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h1,job=x ; +series __name__=b,host=h1,job=x,zone=z1 ; 0:c05af00000000000 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h2,job=y,zone=z2 ; 0:40819b0000000000 +series __name__=b,host=h1,job=x,zone=z2 ; +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h2", job="y", zone="z2"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary + false ignoring host,zone left host Inf Inf +grid 100000 10000 4 +series __name__=a,host=h2,job=y,zone=z1 ; 0:c07d1e0000000000 1:404a600000000000 2:40833b0000000000 +series __name__=a,host=h1,job=y ; 1:40790a0000000000 3:c07b740000000000 +series __name__=a,host=h1,job=x ; 1:408a390000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:c055f80000000000 1:404d200000000000 +result host=h1,job=y ; 1:407cae0000000000 +result host=h1,job=y,zone=z1 ; 0:c0814e0000000000 1:405bc00000000000 +result job=x ; 1:7ff0000000000000 +result job=y ; 3:7ff0000000000000 +result job=y,zone=z1 ; 2:7ff0000000000000 +end +case binary ^ false ignoring host,job left host Inf Inf +grid 100000 10000 8 +series __name__=a,host=h1,job=y ; 1:408eaf0000000000 2:c082bf0000000000 4:c084230000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 4:408da20000000000 5:c039400000000000 +series __name__=b,host=h2,job=x ; +series __name__=b,host=h1,job=y ; 4:c06dac0000000000 5:40749e0000000000 6:c008000000000000 7:40897d0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:c08cd70000000000 5:4089ad0000000000 +result host=h1 ; 5:7ff0000000000000 6:0 7:7ff0000000000000 +result host=h1,job=y ; 4:7ff8000000000001 +result host=h1,zone=z1 ; 4:0 5:7ff0000000000000 +result host=h1,zone=z2 ; 4:7ff0000000000000 5:0 +result job=y ; 1:7ff0000000000000 2:7ff0000000000000 +end +case binary >= true ignoring job left job,zone NaN -2.5 +grid 100000 10000 5 +series __name__=a,host=h2,job=y,zone=z1 ; 4:c054a00000000000 +series __name__=a,host=h2,job=y ; 4:0 +series __name__=a,host=h1,job=y ; 1:c08a4c0000000000 2:c08ec30000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h1,job=y,zone=z1 ; 2:4068380000000000 +series __name__=a,host=h2,job=x ; 2:406dcc0000000000 +series __name__=b,host=h1,job=x ; 1:c049c00000000000 2:c0700c0000000000 3:4086740000000000 4:c084060000000000 +series __name__=b,host=h2,job=x ; 2:c021400000000000 3:404d200000000000 4:7ff8000000000001 +result host=h1,job=x ; 1:0 2:0 3:0 4:0 +result host=h1,zone=z1 ; 2:3ff0000000000000 +result host=h2,job=x ; 2:3ff0000000000000 3:0 4:0 +result host=h2,zone=z1 ; 4:0 +end +case binary - false ignoring job right zone 0 1 +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 3:c081730000000000 4:c06c480000000000 5:40804b0000000000 6:4076540000000000 7:c08d830000000000 8:406aa80000000000 9:c086930000000000 10:c06f980000000000 11:c08d840000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 7:4034600000000000 10:c0689c0000000000 +series __name__=a,host=h2,job=y ; 7:c083a30000000000 9:4022c00000000000 10:c089150000000000 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=a,host=h1,job=y ; 4:408b130000000000 5:c07ff80000000000 6:408bd20000000000 7:c040100000000000 8:7e37e43c8800759c +series __name__=b,host=h2,job=x,zone=z1 ; 3:4086080000000000 4:4052b00000000000 5:c089030000000000 6:c072660000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 2:40823a0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +series __name__=b,host=h2,job=y,zone=z1 ; 9:4084130000000000 10:c089ac0000000000 +error found duplicate series for the match group {host="h1"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h1", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary * false on job right host - Inf +grid 100000 10000 2 +series __name__=a,host=h2,job=x ; 0:c078860000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:4078ba0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:407f460000000000 1:c071d60000000000 +series __name__=a,host=h1,job=x ; 1:4081040000000000 +series __name__=a,host=h2,job=y ; 0:4089140000000000 1:c08cd50000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=x ; 1:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 0:408ece0000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true ignoring host,job left zone -2.5 - +grid 100000 10000 6 +series __name__=a,host=h2,job=y ; 1:c081f30000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 3:407ed40000000000 4:4067000000000000 +result zone=z1 ; 3:0 4:0 +end +case binary == false on host,zone right job -2.5 - +grid 100000 10000 9 +series __name__=a,host=h1,job=y ; 2:408ccc0000000000 5:c0856a0000000000 6:c0759e0000000000 7:c074200000000000 8:7ff8000000000001 +series __name__=b,host=h1,job=y ; 2:c088bd0000000000 3:4060900000000000 4:40849e0000000000 5:404c600000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:7ff8000000000001 1:c07f700000000000 3:7ff0000000000000 4:4028c00000000000 5:c08d9f0000000000 7:4081e50000000000 +end +case binary < false on job left - -2.5 - +grid 100000 10000 1 +series __name__=a,host=h2,job=y,zone=z1 ; 0:407b800000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c04b800000000000 +series __name__=b,host=h2,job=y ; +series __name__=b,host=h2,job=x,zone=z1 ; 0:408bc40000000000 +result __name__=a,host=h2,job=x,zone=z1 ; 0:c04b800000000000 +end +case binary <= true ignoring zone,__name__ right host,zone - 0 +grid 100000 10000 10 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=b,host=h2,job=y,zone=z1 ; 9:c06bd40000000000 +result host=h2,job=y ; 9:0 +end +case binary > false on zone one - 0 - +grid 100000 10000 2 +series __name__=a,host=h2,job=x,zone=z1 ; 0:407cec0000000000 1:0 +series __name__=b,host=h2,job=x,zone=z1 ; 0:40828d0000000000 1:fff0000000000000 +result zone=z1 ; 1:0 +end +case binary > false on host,__name__ right job,zone 0 0 +grid 100000 10000 11 +series __name__=a,host=h1,job=y,zone=z1 ; 7:4080ff0000000000 8:404ba00000000000 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h1,job=y ; 8:fff0000000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 6:4083800000000000 8:408f0d0000000000 9:4050380000000000 +series __name__=b,host=h2,job=x ; 9:4089a40000000000 10:7e37e43c8800759c +error multiple matches for labels: grouping labels must ensure unique matches +end +case binary atan2 false ignoring host,job right - NaN NaN +grid 100000 10000 11 +series __name__=a,host=h2,job=y ; 7:405fe80000000000 9:4073e80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 9:7ff8000000000001 +series __name__=a,host=h1,job=x ; 9:c080f60000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 5:4089700000000000 7:c07d800000000000 8:fff0000000000000 +series __name__=b,host=h2,job=y ; 10:c0876d0000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary atan2 false none - one - Inf - +grid 100000 10000 1 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h1,job=y,zone=z1 ; 0:7ff8000000000001 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h1,job=y,zone=z2 ; 0:c020400000000000 +series __name__=b,host=h2,job=y ; 0:c08e720000000000 +series __name__=b,host=h2,job=x ; 0:c067100000000000 +result host=h1,job=y,zone=z2 ; 0:3ff921fb54442d18 +result host=h2,job=x ; 0:3ff921fb54442d18 +result host=h2,job=y ; 0:3ff921fb54442d18 +end +case binary * false on - left host,job,zone NaN - +grid 100000 10000 2 +series __name__=a,host=h2,job=x,zone=z1 ; 0:406cc00000000000 1:fff0000000000000 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=y ; 1:c07b620000000000 +series __name__=b,host=h1,job=y ; +end +case binary / false none - one - -2.5 - +grid 100000 10000 7 +series __name__=a,host=h1,job=y,zone=z1 ; 5:408b300000000000 +series __name__=a,host=h2,job=x ; 1:408e830000000000 2:c081390000000000 +series __name__=a,host=h1,job=x ; 3:c07fda0000000000 4:4089050000000000 5:407f580000000000 +series __name__=a,host=h1,job=y ; 5:c078900000000000 +series __name__=b,host=h1,job=x ; +series __name__=b,host=h1,job=y,zone=z1 ; 0:c07e560000000000 +series __name__=b,host=h2,job=x ; 1:406e040000000000 3:c07ab40000000000 +series __name__=b,host=h2,job=y ; 6:c07f680000000000 +result host=h1,job=y,zone=z1 ; 0:3f7518dae1dee769 +result host=h2,job=x ; 1:401043b2b4f8efe0 3:3f77f79c8936602b +result host=h2,job=y ; 6:3f7460cbc7f5cf9a +end +case binary == false on zone one - - NaN +grid 100000 10000 2 +series __name__=a,host=h1,job=x,zone=z1 ; 0:408c160000000000 1:40748e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:4048d00000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:4088790000000000 1:4084db0000000000 +error found duplicate series for the match group {zone="z1"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h1", job="y", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary - false on zone one - - -2.5 +grid 100000 10000 8 +series __name__=a,host=h1,job=x,zone=z1 ; 7:c065ec0000000000 +series __name__=a,host=h1,job=y ; 2:4082c30000000000 3:4073fa0000000000 4:c083b30000000000 +series __name__=a,host=h2,job=y ; 5:c073ac0000000000 +series __name__=b,host=h2,job=y ; 7:4076c60000000000 +series __name__=b,host=h1,job=y ; 5:c08bac0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 6:40816b0000000000 7:c085440000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:40896b0000000000 +result - ; 2:4082d70000000000 3:4074220000000000 4:c0839f0000000000 5:4081d60000000000 +result zone=z1 ; 7:c0659c0000000000 +end +case binary > true ignoring - right job - Inf +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; +series __name__=b,host=h2,job=x,zone=z1 ; 3:403ae00000000000 4:c08a2b0000000000 +series __name__=b,host=h2,job=y ; 5:c086880000000000 +result host=h2,job=x,zone=z1 ; 3:3ff0000000000000 4:3ff0000000000000 +result host=h2,job=y ; 5:3ff0000000000000 +end +case binary < false none - one - Inf Inf +grid 100000 10000 6 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c07ba80000000000 4:407c2e0000000000 5:4071340000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:406ac80000000000 2:c0783e0000000000 3:4085fb0000000000 4:c0661c0000000000 +series __name__=a,host=h2,job=x ; 1:c082670000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 5:407e0c0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 3:40738a0000000000 +result __name__=a,host=h1,job=y,zone=z1 ; 3:c07ba80000000000 4:407c2e0000000000 5:4071340000000000 +result __name__=a,host=h2,job=x ; 1:c082670000000000 +result __name__=a,host=h2,job=y,zone=z1 ; 1:406ac80000000000 2:c0783e0000000000 3:4085fb0000000000 4:c0661c0000000000 +end +case binary != false ignoring zone one - 0 NaN +grid 100000 10000 5 +series __name__=a,host=h1,job=x,zone=z1 ; 2:c084d10000000000 3:7ff8000000000001 +series __name__=a,host=h1,job=x ; 1:c08d200000000000 2:4052c80000000000 3:c08d1c0000000000 +series __name__=a,host=h2,job=x ; 3:c084800000000000 4:4085df0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:4080070000000000 2:7ff8000000000001 +series __name__=b,host=h2,job=x,zone=z1 ; 4:c08e880000000000 +series __name__=b,host=h2,job=x ; 3:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z2 ; 3:c083d40000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 2:c0833b0000000000 3:4082820000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary * false ignoring host,job right job,zone 1 0 +grid 100000 10000 1 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h1,job=y,zone=z1 ; 0:7e37e43c8800759c +series __name__=a,host=h1,job=x ; 0:c082640000000000 +series __name__=a,host=h2,job=y ; 0:4075fc0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c058700000000000 +series __name__=b,host=h2,job=y ; 0:7ff8000000000001 +series __name__=b,host=h1,job=x ; 0:4069b40000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary * false ignoring job,zone right job,zone - Inf +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; 9:c082210000000000 +series __name__=a,host=h2,job=y ; 0:40861c0000000000 1:c081f00000000000 2:c082a30000000000 3:c07aea0000000000 4:408ae80000000000 5:407dc40000000000 6:c068f00000000000 7:4089c30000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 1:c081e50000000000 2:7e37e43c8800759c 3:0 4:408b4f0000000000 6:c012800000000000 7:7ff8000000000001 8:4079ba0000000000 9:c064780000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 2:7ff8000000000001 4:c073b80000000000 +series __name__=b,host=h1,job=y,zone=z1 ; +error found duplicate series for the match group {host="h2"} on the left hand-side of the operation: [{__name__="a", host="h2", job="y", zone="z1"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary == true ignoring zone one - Inf - +grid 100000 10000 11 +series __name__=a,host=h2,job=x ; 8:c086c90000000000 9:c03ec00000000000 +series __name__=a,host=h1,job=y ; 1:7ff0000000000000 2:fff0000000000000 3:40814a0000000000 4:406a800000000000 6:c08a8c0000000000 7:40823c0000000000 8:c08c7a0000000000 9:7ff8000000000001 10:408ea00000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 1:408d470000000000 2:4059600000000000 3:4088ef0000000000 4:408cd90000000000 +series __name__=a,host=h1,job=x ; 9:7ff8000000000001 +series __name__=b,host=h1,job=x,zone=z2 ; 3:4076380000000000 4:c077080000000000 +result host=h1,job=x ; 3:0 4:0 +end +case binary == false ignoring - left - NaN - +grid 100000 10000 12 +series __name__=a,host=h2,job=x ; 11:4053d80000000000 +series __name__=a,host=h2,job=y ; 7:406cd00000000000 8:4088190000000000 9:40713a0000000000 10:7ff8000000000001 +series __name__=a,host=h1,job=y ; 9:c0745c0000000000 +series __name__=b,host=h1,job=x ; 7:c07e7c0000000000 8:c079ba0000000000 9:c08b860000000000 10:c082450000000000 +series __name__=b,host=h2,job=y ; 2:4077ea0000000000 3:fff0000000000000 4:408d780000000000 5:c07b4c0000000000 6:c083c90000000000 7:4089db0000000000 8:408a310000000000 9:4088510000000000 10:c088b60000000000 +end +case binary / false none - one - 0 Inf +grid 100000 10000 5 +series __name__=a,host=h1,job=y ; 0:0 1:c08d850000000000 +series __name__=b,host=h1,job=x ; 3:408cc60000000000 +series __name__=b,host=h1,job=y ; 0:4069d00000000000 1:40691c0000000000 2:4076040000000000 3:40875d0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 2:c05bc00000000000 +result host=h1,job=x ; 3:0 +result host=h1,job=y ; 0:0 1:c012cf699e301c0a 2:0 3:0 +result host=h1,job=y,zone=z2 ; 2:8000000000000000 +end +case binary != true ignoring - left job NaN 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 3:407b800000000000 +series __name__=a,host=h2,job=y ; 5:c073880000000000 +series __name__=a,host=h1,job=x ; 5:4084650000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 2:c07c3a0000000000 +series __name__=b,host=h1,job=x ; 2:408f370000000000 3:408d430000000000 4:407c000000000000 +series __name__=b,host=h2,job=x ; 1:c080730000000000 +result host=h1,job=x ; 2:3ff0000000000000 3:3ff0000000000000 4:3ff0000000000000 5:3ff0000000000000 +result host=h2,job=x ; 1:3ff0000000000000 3:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 2:3ff0000000000000 +result host=h2,job=y ; 5:3ff0000000000000 +end +case binary ^ false ignoring host right host,zone - 0 +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 2:407a6a0000000000 +series __name__=a,host=h2,job=y ; 0:0 1:4080950000000000 2:4089ce0000000000 3:c079060000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 5:4070680000000000 +series __name__=b,host=h2,job=y ; 1:4058480000000000 2:4080f50000000000 +result host=h2,job=y ; 1:76e18773d32422b0 2:7ff0000000000000 +end +case binary - false ignoring - right job,zone NaN - +grid 100000 10000 5 +series __name__=a,host=h2,job=y ; 4:7ff8000000000001 +series __name__=a,host=h1,job=y ; 4:408a210000000000 +series __name__=a,host=h2,job=x ; 2:c08bf50000000000 3:c07dea0000000000 +series __name__=b,host=h2,job=y,zone=z2 ; +series __name__=b,host=h2,job=x ; 3:4049600000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 1:c089410000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 1:4063e00000000000 +series __name__=b,host=h1,job=y ; 2:c0801b0000000000 3:c086a20000000000 4:4074960000000000 +result host=h1,job=y ; 4:407fac0000000000 +result host=h2,job=x ; 2:7ff8000000000001 3:c0808b0000000000 +result host=h2,job=y ; 4:7ff8000000000001 +end +case binary <= false ignoring host one - - 1 +grid 100000 10000 2 +series __name__=a,host=h2,job=x ; 1:40780a0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:7ff0000000000000 1:4062d80000000000 +series __name__=a,host=h2,job=y ; 1:408bb70000000000 +series __name__=b,host=h2,job=y ; 0:c08d110000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:c037e00000000000 +series __name__=b,host=h2,job=x ; 1:7e37e43c8800759c +series __name__=b,host=h1,job=x,zone=z2 ; 0:4086520000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c088180000000000 +result __name__=a,job=x ; 1:40780a0000000000 +end +case binary % false ignoring job,__name__ right host - NaN +grid 100000 10000 5 +series __name__=a,host=h1,job=x,zone=z1 ; 1:7ff0000000000000 2:c03c800000000000 4:408d1e0000000000 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h2,job=x ; 0:4046e00000000000 1:c081960000000000 2:40812b0000000000 3:c08f1c0000000000 4:4079d40000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 3:4089100000000000 +series __name__=b,host=h1,job=x ; 1:c085590000000000 2:4089750000000000 3:4021800000000000 +result host=h1,job=x ; 1:7ff8000000000001 2:7ff8000000000001 3:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 3:7ff8000000000001 +end +case binary - false on zone right job -2.5 0 +grid 100000 10000 5 +series __name__=a,host=h2,job=y,zone=z1 ; 1:407bf60000000000 2:408eff0000000000 3:7ff8000000000001 4:fff0000000000000 +series __name__=a,host=h1,job=x ; 4:40782a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=y,zone=z1 ; 0:c0706a0000000000 1:4088500000000000 +series __name__=b,host=h1,job=x ; 3:c04cb00000000000 +series __name__=b,host=h2,job=x ; 4:7ff8000000000001 +result host=h1 ; 3:404cb00000000000 +result host=h2,job=x ; 4:7ff8000000000001 +result host=h2,job=y,zone=z1 ; 1:c074aa0000000000 +result host=h2,zone=z1 ; 0:40706a0000000000 +result job=y,zone=z1 ; 2:408f130000000000 3:7ff8000000000001 4:fff0000000000000 +end +case binary <= true ignoring host left - 0 1 +grid 100000 10000 1 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c083b60000000000 +series __name__=a,host=h1,job=x ; 0:c08b840000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z2 ; 0:c08df20000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c051780000000000 +series __name__=b,host=h1,job=x ; 0:c087c40000000000 +result host=h1,job=x ; 0:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 0:3ff0000000000000 +result job=x,zone=z2 ; 0:0 +result job=y,zone=z1 ; 0:0 +end +case binary >= false on - one - 1 1 +grid 100000 10000 6 +series __name__=a,host=h1,job=x ; 5:fff0000000000000 +series __name__=a,host=h1,job=y ; 0:7ff8000000000001 1:4087460000000000 +series __name__=b,host=h1,job=y ; 0:7ff0000000000000 1:405de80000000000 2:c087a40000000000 3:40740e0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 4:c0857b0000000000 5:7e37e43c8800759c +series __name__=b,host=h1,job=x ; 5:c077da0000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h1", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary ^ false ignoring host,zone one - 0 0 +grid 100000 10000 10 +series __name__=a,host=h2,job=y,zone=z1 ; 7:c070fc0000000000 +series __name__=a,host=h1,job=x ; 8:c0894b0000000000 +series __name__=a,host=h1,job=y ; 0:c07e2c0000000000 1:7ff8000000000001 2:c081460000000000 3:4057880000000000 4:c06c540000000000 5:40774e0000000000 6:c0722c0000000000 +series __name__=a,host=h2,job=y ; 9:c0805f0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:405d800000000000 1:c087570000000000 3:40860d0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 7:408bca0000000000 8:4047e00000000000 +series __name__=b,host=h1,job=x ; 4:4044200000000000 +series __name__=b,host=h2,job=y ; 7:c05d500000000000 8:c05c600000000000 +series __name__=b,host=h1,job=y ; 3:7ff8000000000001 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary >= false ignoring - left host,zone 0 0 +grid 100000 10000 3 +series __name__=a,host=h2,job=x ; 1:c069cc0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:4040a00000000000 2:40845b0000000000 +series __name__=a,host=h2,job=y ; 2:c079b20000000000 +series __name__=a,host=h1,job=x ; 0:7e37e43c8800759c 1:408a830000000000 2:fff0000000000000 +series __name__=b,host=h2,job=x ; 1:0 +series __name__=b,host=h1,job=x,zone=z1 ; 0:c075960000000000 +result __name__=a,host=h1,job=x ; 0:7e37e43c8800759c 1:408a830000000000 +result __name__=a,host=h1,job=x,zone=z1 ; 1:4040a00000000000 2:40845b0000000000 +result host=h1,job=x,zone=z1 ; 0:0 +end +case binary > false ignoring zone left job,zone -2.5 - +grid 100000 10000 5 +series __name__=a,host=h2,job=y ; 4:c0855a0000000000 +series __name__=b,host=h2,job=y ; 3:c072a40000000000 4:408cc30000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 4:c05e380000000000 +series __name__=b,host=h2,job=x ; +result host=h2,job=x,zone=z1 ; 4:c004000000000000 +result host=h2,job=y ; 3:c004000000000000 +end +case binary != false ignoring job,zone one - - 0 +grid 100000 10000 2 +series __name__=a,host=h2,job=y ; 0:c0875b0000000000 +series __name__=a,host=h1,job=x ; 1:4071320000000000 +series __name__=a,host=h1,job=y ; 0:c078ce0000000000 1:c0833c0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 0:408aac0000000000 +series __name__=b,host=h2,job=y ; 0:fff0000000000000 +series __name__=b,host=h1,job=y ; 1:7ff0000000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:c08cba0000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary atan2 false ignoring host right host 1 - +grid 100000 10000 7 +series __name__=a,host=h2,job=y,zone=z1 ; 2:407e940000000000 3:4068180000000000 4:4066500000000000 5:408dfe0000000000 +series __name__=a,host=h2,job=x ; 2:4069ec0000000000 3:408b2a0000000000 4:fff0000000000000 +series __name__=a,host=h1,job=y ; 0:c081bf0000000000 +series __name__=a,host=h1,job=x ; 4:408c210000000000 5:c06b880000000000 +series __name__=a,host=h2,job=y ; 6:405bd00000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 6:c079040000000000 +series __name__=b,host=h1,job=x ; 0:c074a60000000000 2:408c110000000000 4:4083b40000000000 +series __name__=b,host=h1,job=y ; 4:c083ab0000000000 5:c08bf20000000000 6:4080580000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary atan2 false none - one - -2.5 Inf +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; +series __name__=a,host=h2,job=y ; 4:4089320000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c0857a0000000000 4:7ff8000000000001 5:c086a20000000000 6:4076e20000000000 7:408b9a0000000000 8:c016800000000000 9:c08b740000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:40844b0000000000 7:0 8:407ba40000000000 9:4054300000000000 10:c070e60000000000 11:7ff8000000000001 +series __name__=a,host=h2,job=x ; 7:40849f0000000000 9:c086060000000000 10:c068f40000000000 +series __name__=b,host=h1,job=x ; 10:c08f270000000000 11:fff0000000000000 +series __name__=b,host=h2,job=y ; 3:408e310000000000 4:406ef80000000000 5:403ec00000000000 6:c06ab40000000000 7:c08d660000000000 9:407f2a0000000000 10:40763e0000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 9:c050480000000000 10:c074880000000000 +result host=h1,job=x ; 10:c0091cd880c9f449 11:c00921fb54442d18 +result host=h1,job=y,zone=z1 ; 3:8000000000000000 4:7ff8000000000001 5:8000000000000000 6:0 7:0 8:8000000000000000 9:8000000000000000 +result host=h1,job=y,zone=z2 ; 9:c008d366fcdc2a03 10:c00912656416c41a +result host=h2,job=x ; 7:0 9:8000000000000000 10:8000000000000000 +result host=h2,job=x,zone=z1 ; 6:0 7:0 8:0 9:0 10:8000000000000000 11:7ff8000000000001 +result host=h2,job=y ; 3:bf6532b29b492203 4:3ff45cd8f7d1314f 5:bfb4c46fe50bf1cf 6:c0090a03ff6e0fcd 7:c0091c8a0fa57e87 9:bf74894b2b15c02f 10:bf7cc60f8f0a99b8 +end +case binary <= true on host,zone one - NaN - +grid 100000 10000 1 +series __name__=a,host=h2,job=x ; +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z2 ; +end +case binary != true on job,zone left - NaN NaN +grid 100000 10000 4 +series __name__=a,host=h1,job=y ; +series __name__=a,host=h1,job=x ; 0:c058580000000000 1:7ff8000000000001 +series __name__=a,host=h2,job=x,zone=z1 ; 2:c0805f0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 2:c0834e0000000000 +series __name__=b,host=h2,job=x ; 2:4070e40000000000 +series __name__=b,host=h1,job=y ; 3:4082320000000000 +series __name__=b,host=h2,job=y ; 0:407a2e0000000000 +result host=h1,job=x ; 0:3ff0000000000000 1:3ff0000000000000 +result host=h1,job=x,zone=z1 ; 2:3ff0000000000000 +result host=h2,job=x,zone=z1 ; 2:3ff0000000000000 +result job=x ; 2:3ff0000000000000 +result job=y ; 0:3ff0000000000000 3:3ff0000000000000 +end +case binary * false ignoring host,zone right job,zone - 1 +grid 100000 10000 1 +series __name__=a,host=h2,job=x ; 0:4070d80000000000 +series __name__=b,host=h2,job=y ; +end +case binary % false on - left host - -2.5 +grid 100000 10000 8 +series __name__=a,host=h1,job=y,zone=z1 ; 6:7e37e43c8800759c +series __name__=b,host=h2,job=y,zone=z1 ; 7:c055b80000000000 +series __name__=b,host=h1,job=x ; 1:7ff8000000000001 2:408ab40000000000 3:7ff8000000000001 4:406c200000000000 5:4084b40000000000 +result job=y,zone=z1 ; 6:0 +end +case binary atan2 false on job right host,zone Inf Inf +grid 100000 10000 10 +series __name__=a,host=h1,job=y ; 9:c081b70000000000 +series __name__=a,host=h1,job=x ; 9:40808e0000000000 +series __name__=b,host=h2,job=x ; 5:408a1e0000000000 6:c08b540000000000 7:4043100000000000 9:c078260000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 2:c06ba00000000000 3:408ca40000000000 4:7ff8000000000001 5:c087b00000000000 7:c08dcd0000000000 8:4063780000000000 9:7e37e43c8800759c +result host=h1,job=x ; 9:40019b8cd194018d +result host=h1,job=y ; 9:8237ba1d4a6e81ed +result job=x ; 5:3ff921fb54442d18 6:3ff921fb54442d18 7:3ff921fb54442d18 +result job=y ; 2:3ff921fb54442d18 3:3ff921fb54442d18 4:7ff8000000000001 5:3ff921fb54442d18 7:3ff921fb54442d18 8:3ff921fb54442d18 +end +case binary == true on job,zone one - - 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=x,zone=z1 ; 2:4075d80000000000 3:c070c60000000000 4:408df30000000000 +series __name__=a,host=h2,job=y ; 2:c0818a0000000000 4:405b080000000000 +series __name__=a,host=h1,job=x ; 4:c081cc0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 5:406e9c0000000000 +series __name__=b,host=h1,job=x ; 4:c074720000000000 +series __name__=b,host=h2,job=y ; 0:c041c00000000000 1:408d2a0000000000 2:c063440000000000 4:4066a00000000000 5:c089ee0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:40799c0000000000 1:407fbe0000000000 2:c064cc0000000000 3:4078aa0000000000 4:c07a480000000000 +series __name__=b,host=h1,job=y ; 2:4043000000000000 3:0 4:c034400000000000 +error found duplicate series for the match group {job="y"} on the right hand-side of the operation: [{__name__="b", host="h1", job="y"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary <= false none - one - 1 1 +grid 100000 10000 6 +series __name__=a,host=h2,job=x ; 4:7ff8000000000001 5:c07fea0000000000 +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=y ; 4:7ff0000000000000 5:c084ef0000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:4082a20000000000 1:4085e90000000000 2:408f0e0000000000 3:7ff8000000000001 4:4087080000000000 5:4083310000000000 +series __name__=b,host=h2,job=x ; 5:4072c60000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:4077a60000000000 1:c061ec0000000000 3:4062d40000000000 +result __name__=a,host=h2,job=x ; 5:c07fea0000000000 +result __name__=a,host=h2,job=y ; 5:c084ef0000000000 +end +case binary > false on host,__name__ right job NaN NaN +grid 100000 10000 6 +series __name__=a,host=h2,job=y,zone=z1 ; 4:405b400000000000 +series __name__=a,host=h2,job=y ; 2:fff0000000000000 +series __name__=a,host=h1,job=y ; 4:c073e80000000000 +series __name__=b,host=h2,job=y ; 5:c064580000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:40801c0000000000 1:4075d20000000000 2:408c880000000000 3:c078300000000000 4:c08d1b0000000000 5:40740a0000000000 +series __name__=b,host=h2,job=x ; 2:4071ac0000000000 +series __name__=b,host=h1,job=y ; 2:4077500000000000 3:407cba0000000000 +end +case binary + false on host,zone one - Inf Inf +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; +series __name__=a,host=h2,job=x ; 8:c087a80000000000 10:408be20000000000 11:7e37e43c8800759c +series __name__=a,host=h2,job=y,zone=z1 ; 10:407dc80000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 11:c07c9e0000000000 +series __name__=b,host=h1,job=x ; 7:407c2a0000000000 8:fff0000000000000 9:403a600000000000 11:4051080000000000 +series __name__=b,host=h2,job=x ; 5:c0832c0000000000 6:407ede0000000000 +result host=h1 ; 7:7ff0000000000000 8:fff8000000000000 9:7ff0000000000000 11:7ff0000000000000 +result host=h2 ; 5:7ff0000000000000 6:7ff0000000000000 8:7ff0000000000000 10:7ff0000000000000 11:7ff0000000000000 +result host=h2,zone=z1 ; 10:7ff0000000000000 11:7ff0000000000000 +end +case binary == true on host right zone 1 Inf +grid 100000 10000 4 +series __name__=a,host=h1,job=x ; 1:c06e880000000000 +series __name__=a,host=h2,job=y ; +series __name__=b,host=h1,job=y,zone=z1 ; 0:c07c560000000000 1:407a740000000000 2:c08bbf0000000000 +series __name__=b,host=h1,job=x ; 3:4087c90000000000 +series __name__=b,host=h2,job=y ; 0:408c870000000000 1:c0831c0000000000 2:c07b880000000000 +result host=h1,job=x ; 3:0 +result host=h1,job=y ; 0:0 1:0 2:0 +result host=h2,job=y ; 0:0 1:0 2:0 +end +case binary / false ignoring host,job,zone one - 1 - +grid 100000 10000 5 +series __name__=a,host=h2,job=y ; 1:c08d630000000000 2:c07ad80000000000 +series __name__=a,host=h1,job=y ; 0:4087b00000000000 1:4089270000000000 2:4083e40000000000 3:c058d80000000000 4:408c400000000000 +series __name__=a,host=h1,job=x ; 0:c088860000000000 2:4069580000000000 3:c086c90000000000 4:404b600000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:7ff0000000000000 3:407f600000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary <= true ignoring host right job - 1 +grid 100000 10000 7 +series __name__=a,host=h1,job=x ; 4:c080f90000000000 +series __name__=a,host=h2,job=y ; 4:c08e420000000000 5:407ae20000000000 6:7ff8000000000001 +series __name__=a,host=h1,job=y ; 2:c08bf20000000000 +series __name__=b,host=h1,job=x ; 4:4051c00000000000 +result host=h1,job=x ; 4:3ff0000000000000 +end +case binary - false on zone left job NaN - +grid 100000 10000 3 +series __name__=a,host=h2,job=x ; 1:0 +series __name__=b,host=h2,job=x,zone=z1 ; 2:405fc00000000000 +series __name__=b,host=h1,job=x ; 2:405cd80000000000 +series __name__=b,host=h2,job=x ; 0:408d890000000000 2:c08f390000000000 +error found duplicate series for the match group {} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary % false on host right job Inf Inf +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 9:40802e0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:408e450000000000 5:4057600000000000 6:c0704a0000000000 7:4083470000000000 10:4088ad0000000000 11:4086ac0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 9:408d750000000000 10:40866a0000000000 +result host=h1,job=x ; 9:40802e0000000000 +result host=h2,job=x ; 4:408e450000000000 5:4057600000000000 6:c0704a0000000000 7:4083470000000000 11:4086ac0000000000 +result host=h2,job=x,zone=z1 ; 10:4052180000000000 +result host=h2,zone=z1 ; 9:7ff8000000000001 +end +case binary >= false ignoring - left - 0 - +grid 100000 10000 1 +series __name__=a,host=h2,job=y ; 0:408d180000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c06da40000000000 +series __name__=a,host=h1,job=y ; 0:408e670000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c089ef0000000000 +series __name__=b,host=h1,job=x ; 0:407d520000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:c08f300000000000 +series __name__=b,host=h2,job=y ; 0:c07d6a0000000000 +result __name__=a,host=h2,job=y ; 0:408d180000000000 +result host=h2,job=y,zone=z1 ; 0:0 +end +case binary - false none - one - Inf - +grid 100000 10000 4 +series __name__=a,host=h1,job=x ; 3:7ff8000000000001 +series __name__=a,host=h1,job=y,zone=z1 ; 0:407a760000000000 1:c070240000000000 2:4041d00000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 2:c087850000000000 3:0 +series __name__=b,host=h1,job=x ; 2:4084790000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:c07cce0000000000 2:c043b00000000000 +result host=h1,job=x ; 2:7ff0000000000000 +result host=h1,job=x,zone=z1 ; 0:7ff0000000000000 2:7ff0000000000000 +result host=h1,job=y,zone=z1 ; 2:4088a20000000000 3:7ff0000000000000 +end +case binary atan2 false none - one - 1 1 +grid 100000 10000 11 +series __name__=a,host=h1,job=y,zone=z1 ; 2:c079aa0000000000 3:c0839f0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h2,job=y ; 3:408a080000000000 4:4067600000000000 5:c088d10000000000 6:0 +series __name__=a,host=h1,job=x ; 8:c087ef0000000000 9:4075060000000000 +series __name__=a,host=h1,job=y ; 10:4082810000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 9:c08e960000000000 +result host=h1,job=x ; 8:bff91ca235567358 9:3ff915ce0e38cd2d +result host=h1,job=y ; 10:3ff91b107626535d +result host=h1,job=y,zone=z1 ; 2:bff91801b9770412 3:bff91b754a896035 9:40091fe3a889265a +result host=h2,job=y ; 3:3ff91d1088f92cb4 4:3ff90c14063a4079 5:bff91cd2e9bdcafb 6:0 +end +case binary > false on host,zone right - Inf - +grid 100000 10000 9 +series __name__=a,host=h2,job=y,zone=z1 ; 6:c08bff0000000000 7:c08d170000000000 8:4067500000000000 +series __name__=a,host=h2,job=y ; 2:7ff8000000000001 4:40821e0000000000 +series __name__=b,host=h2,job=y ; 7:c08a5d0000000000 +series __name__=b,host=h1,job=y ; 1:408bd70000000000 2:4056380000000000 3:fff0000000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 7:4088e20000000000 8:4080ad0000000000 +end +case binary % false on job left - -2.5 -2.5 +grid 100000 10000 8 +series __name__=a,host=h2,job=x ; 5:7e37e43c8800759c +series __name__=a,host=h2,job=x,zone=z1 ; 5:40798a0000000000 +series __name__=a,host=h1,job=y ; 6:c055a80000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h2,job=y,zone=z1 ; 7:40745c0000000000 +series __name__=b,host=h2,job=x ; 1:406cd00000000000 3:fff0000000000000 +result host=h1,job=y ; 6:bffa000000000000 +result host=h2,job=x ; 5:0 +result host=h2,job=x,zone=z1 ; 5:3ff2000000000000 +result job=x ; 1:c004000000000000 3:c004000000000000 +result job=y ; 7:c004000000000000 +end +case binary / false on host,job,zone left - - 1 +grid 100000 10000 10 +series __name__=a,host=h2,job=x,zone=z1 ; 5:c085820000000000 6:c07dc00000000000 7:c03c600000000000 8:4053300000000000 9:406c680000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 7:4088470000000000 +series __name__=a,host=h1,job=x ; 9:c089870000000000 +series __name__=a,host=h1,job=y ; 5:c072e40000000000 6:c08d2b0000000000 +series __name__=a,host=h2,job=y ; 7:40807a0000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 7:404ce00000000000 8:fff0000000000000 +series __name__=b,host=h1,job=y ; 6:7e37e43c8800759c 7:c08a430000000000 +result host=h1,job=x ; 9:c089870000000000 +result host=h1,job=x,zone=z1 ; 7:4088470000000000 +result host=h1,job=y ; 5:c072e40000000000 6:82438898c35f9b0f +result host=h2,job=x,zone=z1 ; 5:c085820000000000 6:c07dc00000000000 7:bfdf7225adfdc897 8:8000000000000000 9:406c680000000000 +result host=h2,job=y ; 7:40807a0000000000 +end +case binary % false ignoring job right - NaN NaN +grid 100000 10000 9 +series __name__=a,host=h1,job=y,zone=z1 ; 5:c08c320000000000 6:c04ff00000000000 7:408cce0000000000 8:c086b20000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h1,job=x,zone=z1 ; 2:c086cb0000000000 3:4081070000000000 +series __name__=b,host=h1,job=x ; 4:4081e90000000000 5:7e37e43c8800759c 6:c040800000000000 +result host=h1,job=x ; 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 +result host=h1,job=x,zone=z1 ; 2:7ff8000000000001 3:7ff8000000000001 +result host=h1,zone=z1 ; 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 8:7ff8000000000001 +end +case binary < false none - one - Inf Inf +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; 2:4081600000000000 +series __name__=b,host=h2,job=y,zone=z2 ; 0:c072f40000000000 1:c08e900000000000 +result __name__=a,host=h2,job=y ; 2:4081600000000000 +end +case binary % false none - one - - NaN +grid 100000 10000 5 +series __name__=a,host=h2,job=x,zone=z1 ; 4:408c220000000000 +series __name__=a,host=h1,job=x ; 3:fff0000000000000 +series __name__=b,host=h2,job=y ; 0:c08d5b0000000000 1:4083e50000000000 2:0 3:c070540000000000 4:4083960000000000 +result host=h1,job=x ; 3:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 4:7ff8000000000001 +end +case binary <= false ignoring host,zone one - 1 0 +grid 100000 10000 6 +series __name__=a,host=h1,job=y,zone=z1 ; 3:c06d2c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 3:408e380000000000 4:c087c20000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 4:c069440000000000 5:c0807f0000000000 +series __name__=a,host=h2,job=x ; 3:7e37e43c8800759c +series __name__=b,host=h1,job=y ; 2:4080f00000000000 +series __name__=b,host=h1,job=x ; 3:4050080000000000 4:4086500000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary ^ false ignoring - right job - NaN +grid 100000 10000 8 +series __name__=a,host=h2,job=x ; 4:4074440000000000 +series __name__=a,host=h2,job=y ; 6:c08dae0000000000 +series __name__=a,host=h1,job=x ; 2:c07c740000000000 3:c075120000000000 4:7ff8000000000001 5:4068440000000000 7:4088ac0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 1:4072040000000000 2:406e2c0000000000 3:408d9b0000000000 4:c081100000000000 5:c052800000000000 +series __name__=a,host=h1,job=y,zone=z1 ; 4:4080f70000000000 5:c058380000000000 +series __name__=b,host=h2,job=y ; 5:4084e80000000000 6:7ff8000000000001 7:40874b0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 0:4072760000000000 3:40809b0000000000 5:7ff8000000000001 +series __name__=b,host=h2,job=x ; 4:c064a00000000000 5:fff0000000000000 +result host=h2,job=x ; 4:0 5:7ff8000000000001 +result host=h2,job=x,zone=z2 ; 0:7ff8000000000001 3:7ff8000000000001 5:7ff8000000000001 +result host=h2,job=y ; 5:7ff8000000000001 6:7ff8000000000001 7:7ff8000000000001 +end +case binary - false ignoring host,zone left host,job,zone - 1 +grid 100000 10000 10 +series __name__=a,host=h1,job=x ; 3:40824a0000000000 4:4082910000000000 5:4084ce0000000000 +series __name__=a,host=h2,job=x ; 8:c0805d0000000000 9:c078fa0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 6:c080680000000000 7:c07c500000000000 +series __name__=b,host=h1,job=y ; 5:4065500000000000 6:c080380000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 7:408d780000000000 8:4089a40000000000 +series __name__=b,host=h1,job=x ; 7:4080e70000000000 8:4071bc0000000000 +error found duplicate series for the match group {job="x"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x"}, {__name__="b", host="h2", job="x", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary + false none - one - 1 Inf +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 1:7e37e43c8800759c 2:c08c510000000000 3:4073d60000000000 4:407c880000000000 5:c082c20000000000 6:c075240000000000 7:4069cc0000000000 +series __name__=a,host=h1,job=y ; 1:40719e0000000000 2:7ff0000000000000 3:4078620000000000 +series __name__=b,host=h1,job=x ; 4:fff0000000000000 5:c075bc0000000000 +series __name__=b,host=h1,job=y ; 4:c066e40000000000 +series __name__=b,host=h2,job=y ; 3:4089e70000000000 +result host=h1,job=x ; 4:fff0000000000000 5:c075ac0000000000 +result host=h1,job=y ; 1:7ff0000000000000 2:7ff0000000000000 3:7ff0000000000000 4:c066c40000000000 +result host=h2,job=y ; 1:7ff0000000000000 2:7ff0000000000000 3:4091e90000000000 4:7ff0000000000000 5:7ff0000000000000 6:7ff0000000000000 7:7ff0000000000000 +end +case binary != true on host one - 0 -2.5 +grid 100000 10000 2 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=b,host=h2,job=x,zone=z2 ; 1:4080e00000000000 +result host=h2 ; 1:3ff0000000000000 +end +case binary < true ignoring job one - -2.5 0 +grid 100000 10000 3 +series __name__=a,host=h1,job=y,zone=z1 ; 0:c072d20000000000 1:c08cc80000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 0:408ea70000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 0:7ff8000000000001 +error found duplicate series for the match group {host="h1", zone="z1"} on the right hand-side of the operation: [{__name__="b", host="h1", job="x", zone="z1"}, {__name__="b", host="h1", job="y", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary ^ false ignoring job,zone left job 1 1 +grid 100000 10000 9 +series __name__=a,host=h2,job=y ; 5:c07bce0000000000 7:4079f00000000000 8:c08a8f0000000000 +series __name__=a,host=h1,job=x ; 7:408c0c0000000000 +series __name__=a,host=h2,job=x ; 2:4072000000000000 3:c08e720000000000 4:c085670000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 3:4080750000000000 4:4083940000000000 6:c081ff0000000000 7:4077aa0000000000 +series __name__=b,host=h1,job=x ; 3:0 4:4080090000000000 5:4020000000000000 6:406bfc0000000000 +result host=h1 ; 7:408c0c0000000000 +result host=h1,job=x ; 3:3ff0000000000000 4:3ff0000000000000 5:3ff0000000000000 6:3ff0000000000000 +result host=h2 ; 2:4072000000000000 5:c07bce0000000000 8:c08a8f0000000000 +result host=h2,job=y ; 3:7ff8000000000001 4:7ff8000000000001 6:3ff0000000000000 7:7ff0000000000000 +end +case binary / false ignoring host right host,job -2.5 -2.5 +grid 100000 10000 8 +series __name__=a,host=h1,job=x ; 3:4083950000000000 4:407e500000000000 +series __name__=a,host=h1,job=y ; 2:7ff8000000000001 3:c086880000000000 5:4075040000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 5:7ff8000000000001 6:c07f680000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:4073860000000000 +series __name__=b,host=h1,job=x ; 7:40830f0000000000 +series __name__=b,host=h1,job=y ; 2:c022000000000000 3:c06f480000000000 4:407a0c0000000000 5:4065a40000000000 +result host=h1,job=x ; 3:c06f54cccccccccd 4:c068400000000000 +result host=h1,job=y ; 2:7ff8000000000001 3:40070c880e525983 5:3fff13686ee70c04 +result host=h2,job=y,zone=z1 ; 5:7ff8000000000001 6:4069200000000000 +result job=x ; 7:bf70ca52cc1b7e81 +result job=y ; 4:bf789232ad8885ea +result job=y,zone=z1 ; 2:bf8063fb7e1ad6ec +end +case binary % false on host,zone right - -2.5 -2.5 +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 7:4075e00000000000 +series __name__=a,host=h1,job=y ; 7:c0750e0000000000 8:c07d080000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 2:407ae80000000000 3:c04a800000000000 4:c052f80000000000 5:c087f50000000000 6:4060b00000000000 7:c089420000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 3:c0818d0000000000 4:c051780000000000 +series __name__=b,host=h1,job=y ; 9:4089cf0000000000 10:c075480000000000 +series __name__=b,host=h2,job=y ; 11:c08bf40000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 10:fff0000000000000 11:c07d380000000000 +result host=h1 ; 7:bffe000000000000 8:c000000000000000 +result host=h1,job=x,zone=z1 ; 3:c004000000000000 4:c004000000000000 +result host=h1,job=y ; 9:c004000000000000 10:c004000000000000 +result host=h1,job=y,zone=z1 ; 2:c004000000000000 3:c004000000000000 4:c004000000000000 5:c004000000000000 6:c004000000000000 7:c004000000000000 +result host=h2 ; 7:0 +result host=h2,job=x,zone=z1 ; 10:c004000000000000 11:c004000000000000 +result host=h2,job=y ; 11:c004000000000000 +end +case binary == false ignoring job left - NaN NaN +grid 100000 10000 5 +series __name__=a,host=h2,job=y,zone=z1 ; 0:0 1:4088a70000000000 2:4067840000000000 +series __name__=a,host=h1,job=y ; 4:4073140000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 3:c0852b0000000000 +series __name__=a,host=h2,job=x ; 0:4087550000000000 1:7ff8000000000001 2:404ab00000000000 3:c0817a0000000000 4:c04b600000000000 +series __name__=b,host=h1,job=y ; +series __name__=b,host=h2,job=y ; 4:7ff0000000000000 +series __name__=b,host=h2,job=x ; +end +case binary % false none - one - Inf NaN +grid 100000 10000 7 +series __name__=a,host=h1,job=y ; 4:7e37e43c8800759c 5:c05a000000000000 +series __name__=a,host=h2,job=x,zone=z1 ; +series __name__=a,host=h1,job=y,zone=z1 ; 1:405b280000000000 2:c08d3f0000000000 3:408b180000000000 4:4080400000000000 5:4064500000000000 6:4056780000000000 +series __name__=a,host=h2,job=x ; 5:405d080000000000 +series __name__=b,host=h1,job=x ; 2:408f180000000000 3:c029800000000000 4:c068f40000000000 5:c072760000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:4087490000000000 2:c082120000000000 3:4067280000000000 4:fff0000000000000 5:c089fe0000000000 6:c05e780000000000 +series __name__=b,host=h1,job=y ; 1:4082600000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:4073c00000000000 +result host=h1,job=x ; 2:7ff8000000000001 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 +result host=h1,job=x,zone=z1 ; 1:7ff8000000000001 2:7ff8000000000001 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 +result host=h1,job=y ; 1:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 +result host=h1,job=y,zone=z1 ; 1:7ff8000000000001 2:7ff8000000000001 3:7ff8000000000001 4:7ff8000000000001 5:7ff8000000000001 6:7ff8000000000001 +result host=h2,job=x ; 5:7ff8000000000001 +result host=h2,job=x,zone=z1 ; 0:7ff8000000000001 +end +case binary % false ignoring job right zone 0 0 +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; 1:4080fc0000000000 +series __name__=a,host=h2,job=x ; 0:c077d60000000000 1:0 2:c08ee80000000000 +series __name__=b,host=h2,job=y ; 0:4078cc0000000000 1:c0786e0000000000 2:4061580000000000 +series __name__=b,host=h1,job=x ; +error found duplicate series for the match group {host="h2"} on the left hand-side of the operation: [{__name__="a", host="h2", job="x"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary % false ignoring host,zone right host - 0 +grid 100000 10000 4 +series __name__=a,host=h1,job=x ; 2:7ff0000000000000 3:4064b40000000000 +series __name__=a,host=h1,job=y ; 0:fff0000000000000 +series __name__=a,host=h2,job=x ; 3:c07f8c0000000000 +series __name__=b,host=h1,job=y ; 1:c08d440000000000 +series __name__=b,host=h1,job=x,zone=z2 ; 0:c052400000000000 1:c079b40000000000 +series __name__=b,host=h2,job=x ; 1:0 2:c072620000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary - false ignoring host,job,zone right job,zone 0 -2.5 +grid 100000 10000 1 +series __name__=a,host=h1,job=y ; 0:4089720000000000 +series __name__=a,host=h2,job=x ; 0:c077ce0000000000 +series __name__=a,host=h1,job=x ; +series __name__=b,host=h1,job=y ; 0:7ff8000000000001 +series __name__=b,host=h2,job=x ; 0:405a480000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:c073be0000000000 +series __name__=b,host=h1,job=x ; 0:4081c70000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h1", job="y"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary != false ignoring host,zone,__name__ one - - Inf +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; 1:4086f10000000000 2:4077b20000000000 4:7ff8000000000001 +series __name__=a,host=h2,job=y ; 4:408aac0000000000 +series __name__=b,host=h2,job=y ; 2:408e000000000000 3:403ec00000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 2:c0699c0000000000 3:7ff8000000000001 +error found duplicate series for the match group {job="y"} on the right hand-side of the operation: [{__name__="b", host="h1", job="y", zone="z1"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary * false ignoring zone left host,zone Inf 1 +grid 100000 10000 5 +series __name__=a,host=h2,job=x,zone=z1 ; 1:7e37e43c8800759c 2:c087e10000000000 3:c073540000000000 +series __name__=a,host=h2,job=x ; 0:c054b00000000000 1:c080310000000000 2:402a000000000000 3:408aca0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=a,host=h2,job=y ; 4:c08de70000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 3:4083020000000000 +series __name__=b,host=h2,job=y ; 1:fff0000000000000 2:406a740000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 0:7ff8000000000001 1:408e280000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 0:0 2:7ff0000000000000 3:40779e0000000000 4:408a270000000000 +error found duplicate series for the match group {host="h2", job="y"} on the right hand-side of the operation: [{__name__="b", host="h2", job="y", zone="z1"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary <= true ignoring host,job right host,job,zone Inf Inf +grid 100000 10000 7 +series __name__=a,host=h2,job=y,zone=z1 ; 5:407fb20000000000 +series __name__=b,host=h2,job=y,zone=z1 ; +result host=h2,job=y,zone=z1 ; 5:3ff0000000000000 +end +case binary == false ignoring host,job right job,zone NaN 1 +grid 100000 10000 10 +series __name__=a,host=h1,job=x,zone=z1 ; 1:c07bbc0000000000 2:7ff8000000000001 3:c083fa0000000000 +series __name__=a,host=h1,job=y ; 7:c0603c0000000000 +series __name__=a,host=h2,job=y,zone=z1 ; 2:c08c610000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 2:c03d000000000000 3:405fe80000000000 4:4077820000000000 5:408a060000000000 6:4089090000000000 7:7ff0000000000000 9:405e500000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 1:c067d40000000000 2:4020c00000000000 3:c037600000000000 4:c083910000000000 5:c08b360000000000 +series __name__=b,host=h1,job=x,zone=z1 ; 1:c0876c0000000000 4:7ff8000000000001 5:407afa0000000000 6:c087160000000000 +error found duplicate series for the match group {zone="z1"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h2", job="y", zone="z1"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary atan2 false on host,__name__ one - Inf - +grid 100000 10000 2 +series __name__=a,host=h1,job=y,zone=z1 ; +series __name__=a,host=h1,job=x,zone=z1 ; +series __name__=a,host=h2,job=x ; 0:c077ac0000000000 +series __name__=a,host=h1,job=x ; 1:408a780000000000 +series __name__=b,host=h2,job=x ; 1:4081d90000000000 +series __name__=b,host=h2,job=y ; 1:405e400000000000 +series __name__=b,host=h1,job=x ; 1:c08b8b0000000000 +error found duplicate series for the match group {__name__="b", host="h2"} on the right hand-side of the operation: [{__name__="b", host="h2", job="x"}, {__name__="b", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary - false ignoring host right host,zone - NaN +grid 100000 10000 3 +series __name__=a,host=h2,job=y ; 0:c070160000000000 +series __name__=a,host=h1,job=y ; 1:4045a00000000000 +series __name__=a,host=h1,job=x ; 2:0 +series __name__=a,host=h2,job=x ; 2:c078b00000000000 +series __name__=b,host=h1,job=y ; 1:408c3a0000000000 +series __name__=b,host=h1,job=x ; 0:7e37e43c8800759c +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary <= true ignoring - right host,zone NaN 1 +grid 100000 10000 2 +series __name__=a,host=h1,job=y ; 0:7ff0000000000000 +series __name__=b,host=h2,job=y ; 0:c085090000000000 +result host=h1,job=y ; 0:0 +result host=h2,job=y ; 0:0 +end +case binary > true on - right - Inf NaN +grid 100000 10000 12 +series __name__=a,host=h1,job=x ; 0:c070e80000000000 +series __name__=a,host=h1,job=y ; 8:7ff8000000000001 9:408bb70000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 6:c082ef0000000000 7:407a6c0000000000 +series __name__=a,host=h2,job=x ; 6:c082ec0000000000 7:c063480000000000 +series __name__=b,host=h1,job=x ; +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h2", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true ignoring job,zone one - -2.5 1 +grid 100000 10000 3 +series __name__=a,host=h2,job=y,zone=z1 ; 0:c08b540000000000 1:c05f100000000000 2:7ff0000000000000 +series __name__=a,host=h1,job=x ; 2:407fe80000000000 +series __name__=a,host=h1,job=x,zone=z1 ; 1:406ba40000000000 2:c07a1a0000000000 +series __name__=a,host=h1,job=y ; 1:c06e900000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:408ebc0000000000 2:407d680000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 2:c078580000000000 +error multiple matches for labels: many-to-one matching must be explicit (group_left/group_right) +end +case binary / false on host right zone - NaN +grid 100000 10000 8 +series __name__=a,host=h2,job=y ; 2:408bbe0000000000 3:4089960000000000 4:c070580000000000 5:c0705e0000000000 +series __name__=a,host=h2,job=x ; 7:7ff8000000000001 +series __name__=a,host=h2,job=x,zone=z1 ; 2:4087830000000000 3:7ff8000000000001 5:c085c90000000000 +series __name__=a,host=h1,job=x ; 5:4082470000000000 6:7e37e43c8800759c +series __name__=a,host=h2,job=y,zone=z1 ; +series __name__=b,host=h1,job=x ; +series __name__=b,host=h1,job=y ; 0:c083ed0000000000 1:7ff0000000000000 +error found duplicate series for the match group {host="h2"} on the left hand-side of the operation: [{__name__="a", host="h2", job="x", zone="z1"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary >= true ignoring zone left host 1 - +grid 100000 10000 5 +series __name__=a,host=h1,job=y,zone=z1 ; 4:40864d0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 1:4079360000000000 2:4050580000000000 3:c0750a0000000000 +series __name__=b,host=h1,job=y ; 2:c077480000000000 3:40684c0000000000 +series __name__=b,host=h1,job=x,zone=z1 ; +error found duplicate series for the match group {host="h1", job="y"} on the right hand-side of the operation: [{__name__="b", host="h1", job="y", zone="z1"}, {__name__="b", host="h1", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary < true ignoring host one - -2.5 -2.5 +grid 100000 10000 5 +series __name__=a,host=h2,job=y,zone=z1 ; 2:c078dc0000000000 3:407b280000000000 4:c0888c0000000000 +series __name__=b,host=h2,job=y ; 2:4088770000000000 3:c087ea0000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 1:7ff0000000000000 +result job=y ; 2:3ff0000000000000 3:0 +result job=y,zone=z1 ; 1:3ff0000000000000 2:3ff0000000000000 3:0 4:3ff0000000000000 +end +case binary >= true none - one - NaN - +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 10:c08f3e0000000000 11:c08a890000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 9:c082c70000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 10:c082130000000000 11:40824e0000000000 +series __name__=b,host=h1,job=y ; 2:406f200000000000 4:c08ce30000000000 5:4079520000000000 6:c085e50000000000 7:c07a180000000000 8:c08f3c0000000000 9:7ff8000000000001 10:c067cc0000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 1:4048b00000000000 2:4085430000000000 3:c082f60000000000 +result host=h1,job=y ; 2:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 +result host=h2,job=x,zone=z1 ; 10:0 11:0 +result host=h2,job=x,zone=z2 ; 1:0 2:0 3:0 +end +case binary >= false ignoring job one - - Inf +grid 100000 10000 2 +series __name__=a,host=h1,job=y ; 1:0 +series __name__=b,host=h1,job=y,zone=z1 ; 0:c05e080000000000 1:fff0000000000000 +series __name__=b,host=h1,job=x ; 1:408e280000000000 +series __name__=b,host=h1,job=y,zone=z2 ; 0:4042c00000000000 +end +case binary * false none - one - NaN - +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 2:7ff0000000000000 +series __name__=a,host=h1,job=x ; 5:4055f00000000000 6:407eba0000000000 7:c080390000000000 9:c087cc0000000000 10:c08baf0000000000 +series __name__=b,host=h2,job=y ; 11:4085e30000000000 +series __name__=b,host=h2,job=y,zone=z1 ; 10:fff0000000000000 11:40722e0000000000 +series __name__=b,host=h1,job=y,zone=z1 ; 6:407bf40000000000 7:4080390000000000 +result host=h1,job=y,zone=z1 ; 6:7ff8000000000001 7:7ff8000000000001 +result host=h2,job=y ; 11:7ff8000000000001 +result host=h2,job=y,zone=z1 ; 10:7ff8000000000001 11:7ff8000000000001 +end +case binary ^ false on job right - NaN NaN +grid 100000 10000 3 +series __name__=a,host=h1,job=x,zone=z1 ; 1:406de40000000000 2:c07c5a0000000000 +series __name__=a,host=h1,job=x ; 2:c06ad40000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 0:c08c650000000000 +series __name__=b,host=h2,job=x,zone=z1 ; 2:c06f500000000000 +series __name__=b,host=h2,job=x,zone=z2 ; 2:c06f740000000000 +error found duplicate series for the match group {job="x"} on the left hand-side of the operation: [{__name__="a", host="h1", job="x", zone="z1"}, {__name__="a", host="h1", job="x"}];many-to-many matching not allowed: matching labels must be unique on one side +end +case binary % false on - right host,zone - NaN +grid 100000 10000 12 +series __name__=a,host=h2,job=y ; 5:408df90000000000 6:c074560000000000 7:c0832f0000000000 8:c076780000000000 10:c08c2d0000000000 +series __name__=a,host=h2,job=x,zone=z1 ; 10:4085020000000000 11:4075280000000000 +series __name__=b,host=h2,job=y ; 11:c070e80000000000 +error found duplicate series for the match group {} on the left hand-side of the operation: [{__name__="a", host="h2", job="x", zone="z1"}, {__name__="a", host="h2", job="y"}];many-to-many matching not allowed: matching labels must be unique on one side +end diff --git a/src/promql/src/vector_match/tests.rs b/src/promql/src/vector_match/tests.rs index 31a5f9bcc2c..3fac9bfb07e 100644 --- a/src/promql/src/vector_match/tests.rs +++ b/src/promql/src/vector_match/tests.rs @@ -23,7 +23,8 @@ use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use super::{ - BinaryMatching, BinaryOp, Cardinality, MatchingLabels, SetOp, binary_vectors, set_vectors, + BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp, binary_vectors, + set_vectors, }; use crate::grid_series::GridSeriesBuilder; use crate::grid_series::reference::{ @@ -481,6 +482,7 @@ fn binary_vectors_match_prometheus_reference() { return_bool, labels, cardinality, + fill: FillValues::default(), }; let fields = lhs_fields.min(rhs_fields); let points = grid.timestamps().len(); @@ -555,6 +557,7 @@ fn rejects_operands_on_other_grids_and_unpaired_or_fields() { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; assert!(binary_vectors(&matching, &lhs.schema, &lhs.series, &schema(1, &other), &[]).is_err()); assert!(matches!( @@ -614,6 +617,7 @@ fn reports_the_earliest_failing_point() { return_bool: false, labels: MatchingLabels::On(vec![Arc::from("job")]), cardinality: Cardinality::ManyToOne(Vec::new()), + fill: FillValues::default(), }; let error = binary_vectors(&matching, &schema, &lhs, &schema, &rhs) .unwrap_err() @@ -655,6 +659,26 @@ fn canonical_bits(value: f64) -> u64 { /// `prometheus_cases.txt`. #[test] fn vector_operations_match_prometheus() { + let (matched, failed) = check_cases(include_str!("prometheus_cases.txt")); + assert!( + matched > 100 && failed > 20, + "{matched} matched, {failed} failed" + ); +} + +/// Binary operations with fill modifiers, evaluated by the Prometheus v3.15.0 engine; see the +/// header of `fill_cases.txt`. +#[test] +fn fill_modifiers_match_prometheus() { + let (matched, failed) = check_cases(include_str!("fill_cases.txt")); + assert!( + matched > 100 && failed > 20, + "{matched} matched, {failed} failed" + ); +} + +/// Checks each case of a fixture and returns how many matched results and how many failed. +fn check_cases(text: &str) -> (usize, usize) { let parse_labels = |labels: &str| -> Labels { labels .split(',') @@ -672,7 +696,6 @@ fn vector_operations_match_prometheus() { .collect() }; let (mut matched, mut failed) = (0, 0); - let text = include_str!("prometheus_cases.txt"); for case in text.split("end\n").filter(|case| case.contains("case ")) { let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect(); let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect(); @@ -729,6 +752,10 @@ fn vector_operations_match_prometheus() { other => panic!("unexpected line {other}"), } } + let fill = |value: Option<&&str>| match value { + None | Some(&"-") => None, + Some(value) => Some(value.parse::().unwrap()), + }; let labels = |kind: &str, list: &str| match kind { "on" => MatchingLabels::On(names(list)), _ => MatchingLabels::Ignoring(names(list)), @@ -760,6 +787,10 @@ fn vector_operations_match_prometheus() { "right" => Cardinality::OneToMany(names(spec[6])), _ => Cardinality::OneToOne, }, + fill: FillValues { + lhs: fill(spec.get(7)), + rhs: fill(spec.get(8)), + }, }; binary_vectors(&matching, &schema, &lhs, &schema, &rhs) } @@ -806,10 +837,7 @@ fn vector_operations_match_prometheus() { (actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"), } } - assert!( - matched > 100 && failed > 20, - "{matched} matched, {failed} failed" - ); + (matched, failed) } /// Results that share a label set once `__type__` is dropped fail as a grouping violation within @@ -858,6 +886,7 @@ fn colliding_results_fail_by_where_they_collide() { return_bool: false, labels, cardinality: Cardinality::ManyToOne(Vec::new()), + fill: FillValues::default(), }; let error = binary_vectors(&matching, &schema, &lhs, &schema, rhs) .unwrap_err() @@ -1002,6 +1031,7 @@ fn histogram_operators_match_prometheus() { "right" => Cardinality::OneToMany(Vec::new()), _ => Cardinality::OneToOne, }, + fill: FillValues::default(), }; binary_vectors(&matching, &schema, &lhs, &schema, &rhs) } @@ -1127,12 +1157,66 @@ fn colliding_reset_hints_skip_the_pair() { return_bool: false, labels: MatchingLabels::On(vec![Arc::from("job")]), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; let result = binary_vectors(&matching, &schema, &lhs, &schema, &rhs).unwrap(); assert_eq!(result.len(), 1, "{op:?}"); } } +/// A pair whose operation fails is not a match, so `fill_left` still fills for the right-hand +/// sample of that pair; the fixtures hold floats only. +#[test] +fn a_failed_pair_leaves_its_sample_to_the_fill() { + let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 10_000, 1).unwrap()).unwrap()); + let schema = Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("value"), + }] + .into(), + eval_grid: Some(grid), + }); + let labels = |pairs: &[(&str, &str)]| -> Labels { + pairs + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect() + }; + let histogram = "0/0/0/4014000000000000/4014000000000000/0/0_1/4014000000000000///"; + let lhs = [mixed_series( + &schema, + &labels(&[("__name__", "a"), ("job", "x")]), + &BTreeMap::new(), + &BTreeMap::from([(0, histogram.to_string())]), + ) + .unwrap()]; + let rhs = [mixed_series( + &schema, + &labels(&[("__name__", "b"), ("job", "x")]), + &BTreeMap::from([(0, 2.0f64.to_bits())]), + &BTreeMap::new(), + ) + .unwrap()]; + // A histogram plus a float is skipped, so `b` is unmatched: 10 + 2 under the match labels. + let matching = BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from("job")]), + cardinality: Cardinality::OneToOne, + fill: FillValues { + lhs: Some(10.0), + rhs: None, + }, + }; + let result = binary_vectors(&matching, &schema, &lhs, &schema, &rhs).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(labels_of(&result[0].metric), labels(&[("job", "x")])); + assert!(matches!( + result[0].fields.as_slice()[0].sample(0), + SampleRef::Float(value) if value == 12.0 + )); +} + /// A binary pairing walks two operands of many single-position runs and still reports every /// position exactly once. /// @@ -1170,6 +1254,7 @@ fn a_pairing_reads_many_single_position_runs_once() { return_bool: false, labels: MatchingLabels::On(vec![Arc::from("job")]), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; let result = binary_vectors( &matching, @@ -1218,6 +1303,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; let result = binary_vectors( &matching, @@ -1249,6 +1335,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; let result = binary_vectors( &filtered, @@ -1278,6 +1365,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() { return_bool: true, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }; let result = binary_vectors( &booled, From 43856a7dbf34ea0f58af2d37805baeb4deaa8736 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:47:15 +0800 Subject: [PATCH 06/10] refactor(promql): simplify native execution memory estimates Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- .../src/histogram_eval/float_histogram.rs | 14 +- src/promql/src/native/execute.rs | 955 +++++------------- src/promql/src/native/execute/tests.rs | 718 ++++--------- src/promql/src/range_eval.rs | 190 ++-- src/promql/src/range_eval/tests.rs | 118 ++- 5 files changed, 658 insertions(+), 1337 deletions(-) diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 30147d01645..acce48c1776 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -80,18 +80,10 @@ impl FloatHistogram { }) } - /// The bytes this histogram's own heap buffers hold, by capacity. + /// Estimates the heap held by the bucket lists, custom bounds and preserved span layout. /// - /// Everything a histogram keeps besides its scalars is on the heap: the bucket lists of both - /// sides, the custom bounds, and the span layout of a histogram read from a view, with the - /// `[Vec; 2]` array that holds the two layout vectors. No scalar of the struct shows any of it: - /// a histogram of 4096 positive buckets is 64 KiB of buckets, and a window that retains one - /// histogram per grid point retains that much per point. - /// - /// The layout array is stored inline in the histogram, so a ledger charging - /// `size_of::()` per slot already pays for those 48 bytes. Counting the whole - /// footprint as one figure here costs a header of over-estimate on a reservation, against a - /// payload of tens of kilobytes that would otherwise be missing from it entirely. + /// A histogram can own tens of kilobytes of buckets that its struct size does not include. + /// Capacity slack and small header overestimates are acceptable for window reservations. pub(crate) fn heap_bytes(&self) -> usize { fn buckets(side: &Buckets) -> usize { side.capacity() * std::mem::size_of::<(i32, f64)>() diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index b1e2afe9a28..ada6cbe323c 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -15,9 +15,9 @@ //! Running a bound tree, node by node. //! //! [`NativeExecutionState`] owns the run-time state one execution of a [`NativeTree`] needs, keyed -//! by the position [`metrics::walk`] gives each node. The tree is what the compiler produced and -//! carries no state of its own, so a second execution builds a second state from the same tree and -//! the two never share a buffer, an evaluator or a memory reservation. +//! by the position [`crate::native::metrics::walk`] gives each node. The tree is what the compiler +//! produced and carries no state of its own, so a second execution builds a second state from the +//! same tree and the two never share a buffer, an evaluator or a memory reservation. //! //! [`NativeExecutor`] drives that state one chunk at a time. Nodes hand each other //! [`EvaluatedChunk`]s: a source hands over raw samples, and everything above a window hands over @@ -62,8 +62,8 @@ use datatypes::series::{MetricName, SeriesOrdering}; use crate::grid_series::{LabelSet, label_set}; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; -use crate::native::metrics::{self, NodeMetrics, NodePath}; -use crate::native::plan::{BoundWindow, NativeExpr, NativeTree}; +use crate::native::metrics::{NodeMetrics, NodePath}; +use crate::native::plan::{NativeExpr, NativeTree}; use crate::range_eval::RangeEvaluator; #[cfg(test)] @@ -110,232 +110,18 @@ impl NativeChunk { } } - /// The bytes this chunk holds, counting each shared allocation it references that `charged` has - /// not met yet. - fn bytes(&self, charged: &mut ChargedAllocations) -> usize { + /// An estimate of the bytes this chunk holds. + /// + /// It is what the chunk alone stands for, so a buffer or a histogram table two chunks share is + /// counted once per chunk. That over-count is the price of a figure that costs one pass over + /// the chunk it names and keeps no state between chunks; it is bounded by the number of queued + /// chunks, not by the data they carry together. + fn bytes(&self) -> usize { match self { - Self::Raw(chunk) => raw_bytes(chunk, charged), - Self::Evaluated(chunk) => evaluated_bytes(chunk, charged), + Self::Raw(chunk) => raw_bytes(chunk), + Self::Evaluated(chunk) => evaluated_bytes(chunk), } } - - /// The bytes this chunk occupies on its own, which no other chunk holds a reference to. - /// - /// It is the struct term of [`Self::bytes`] and nothing else: everything beside it is a buffer or - /// a histogram table, which a sibling chunk of the series can share and which the queue counts - /// per allocation rather than per chunk. - fn own_bytes(&self) -> usize { - match self { - Self::Raw(_) => std::mem::size_of::(), - Self::Evaluated(_) => std::mem::size_of::(), - } - } -} - -/// The shared allocations one accounting pass has already counted. -/// -/// A chunk holds very little of what it costs: a field of native histograms holds no floats at all, -/// only indices into an immutable `Arc` table, and both that table and the buffers -/// behind the field's Arrow arrays are batch-wide allocations that a chunk can hold a slice of. Two -/// chunks of one series can share one table by cloning the `Arc`, and both can hold sibling slices -/// of one buffer, so a pass counts an allocation the first time it meets it. Charging it per -/// referencing chunk instead would make the reservation grow with the number of chunks a node holds -/// rather than with the data in them -- the figure the pool has to rank. -/// -/// One pass walks one chunk, so the list stays as short as the allocations that chunk met and is -/// dropped with the pass; nothing outlives the call it was made for. The queue of one node is not -/// recounted by such a pass: [`QueuedCharge`] folds a chunk in as it enters and out as it leaves, -/// carrying the same dedupe across the queue. -#[derive(Default)] -struct ChargedAllocations { - /// The address of every histogram table this pass has counted, with the bytes it contributes. - tables: Vec<(*const HistogramBatch, usize)>, - /// The address of every Arrow buffer this pass has counted, with the bytes it contributes. - buffers: Vec<(*const u8, usize)>, -} - -impl ChargedAllocations { - /// The bytes `table` holds, or zero when this pass has already counted it. - fn table(&mut self, table: &Arc) -> usize { - let address = Arc::as_ptr(table); - if self.tables.iter().any(|(counted, _)| *counted == address) { - return 0; - } - // The batch struct holds the struct array and the column arrays beside it, which are views - // of that array's children: the array reports the buffers of all of them, once. - let bytes = std::mem::size_of::() - .saturating_add(table.as_arrow().get_array_memory_size()); - self.tables.push((address, bytes)); - bytes - } - - /// The bytes the allocation `buffer` is a slice of, or zero when this pass has already counted - /// it. - /// - /// The capacity is the whole allocation, which is what a slice keeps alive: a key of a few - /// bytes sliced out of a decoded dictionary values buffer pins that buffer. A buffer that owns - /// no memory of its own reports no capacity, and then the bytes it shows are all there is. - fn buffer(&mut self, buffer: &Buffer) -> usize { - let address = buffer.data_ptr().as_ptr().cast_const(); - if self.buffers.iter().any(|(counted, _)| *counted == address) { - return 0; - } - let bytes = buffer.capacity().max(buffer.len()); - self.buffers.push((address, bytes)); - bytes - } - - /// The bytes the buffers of one Arrow array hold. - fn array(&mut self, array: &dyn Array) -> usize { - let data = array.to_data(); - let values = data.buffers().iter().fold(0usize, |total, buffer| { - total.saturating_add(self.buffer(buffer)) - }); - // The validity bitmap is not one of `buffers`: a field of a series with a missing sample - // carries one, and it is an allocation like any other. - let nulls = data - .nulls() - .map_or(0, |nulls| self.buffer(nulls.inner().inner())); - values.saturating_add(nulls) - } -} - -/// The bytes the chunks one node queues hold, kept as chunks enter and leave the queue. -/// -/// A node is asked for its queue's figure on every enqueue and every pop, and the queue can hold a -/// whole series at once, for a caller that pushes a series before pulling it. Recounting the queue -/// with a [`ChargedAllocations`] pass each time is one pass over every queued chunk per operation, -/// which is quadratic in the chunks that caller queues. What is kept here instead is a count per -/// shared allocation, with the bytes that allocation contributes and the running total they add up -/// to, so an operation walks only the allocations of the one chunk it names. -/// -/// The dedupe is the one [`ChargedAllocations`] makes inside a chunk, carried across the queue. It -/// is per queued chunk that references an allocation, not per field or per segment that does: the -/// chunk is walked with one pass, so a chunk whose two fields index one table is one reference to -/// it, and the walk a pop makes of the same chunk meets the same references. A chunk is therefore -/// charged its own struct once, and an allocation once for as long as at least one queued chunk -/// references it -- the figure a whole-queue pass would give, without the pass. -#[derive(Default)] -struct QueuedCharge { - /// Every histogram table the queued chunks reference, by address, with how many queued chunks - /// reference it and the bytes it contributes to the total while at least one does. - tables: HashMap, - /// Every Arrow buffer the queued chunks reference, likewise: two chunks of one series hold - /// sibling slices of one buffer, and the address of the allocation is what makes them one. - buffers: HashMap, - /// What the queued chunks hold: their own structs, and the allocations above added once each. - /// This is what the node reserves for its queue. - bytes: usize, - /// How many chunks the accounting has walked, test-only. - /// - /// An enqueue or a pop walks the chunk it names, so this grows by one per operation whatever - /// the queue holds. A figure recounted from the whole queue would grow with the depth of the - /// queue, which is what a test refuses. - #[cfg(test)] - walked: usize, -} - -/// How many queued chunks reference one shared allocation, and the bytes it contributes while at -/// least one of them does. -#[derive(Clone, Copy)] -struct Counted { - chunks: usize, - bytes: usize, -} - -impl QueuedCharge { - /// Counts the allocations `chunk` references, as that chunk enters the queue, and returns the - /// queue's new total. - fn enqueue(&mut self, chunk: &NativeChunk) -> usize { - let charged = self.walk(chunk); - // The struct a chunk is held by is its own; only what it points at can be shared. - self.bytes = self.bytes.saturating_add(chunk.own_bytes()); - for &(table, bytes) in &charged.tables { - count_reference(&mut self.tables, &mut self.bytes, table as usize, bytes); - } - for &(buffer, bytes) in &charged.buffers { - count_reference(&mut self.buffers, &mut self.bytes, buffer as usize, bytes); - } - self.bytes - } - - /// Gives the allocations `chunk` references back, as that chunk leaves the queue, and returns - /// the queue's new total. - /// - /// An allocation another queued chunk still references stays charged: only the last reference - /// takes its bytes out, which is what keeps a shared table counted once for as long as the - /// queue holds it. - fn pop(&mut self, chunk: &NativeChunk) -> usize { - let charged = self.walk(chunk); - self.bytes = self.bytes.saturating_sub(chunk.own_bytes()); - for &(table, _) in &charged.tables { - drop_reference(&mut self.tables, &mut self.bytes, table as usize); - } - for &(buffer, _) in &charged.buffers { - drop_reference(&mut self.buffers, &mut self.bytes, buffer as usize); - } - self.bytes - } - - /// The shared allocations one chunk references, each met once. - /// - /// The pass is over `chunk` alone: what the queue holds is folded in from the allocations the - /// pass met rather than recounted by walking the queue. The same chunk walked again meets the - /// same addresses, which is what makes the subtraction on the way out match the addition on the - /// way in. - fn walk(&mut self, chunk: &NativeChunk) -> ChargedAllocations { - let mut charged = ChargedAllocations::default(); - // The figure this sums is the chunk's own; the queue needs the allocations behind it, which - // `charged` now holds. - let _ = chunk.bytes(&mut charged); - #[cfg(test)] - { - self.walked += 1; - } - charged - } -} - -/// Counts one more reference to the allocation at `address`, which contributes `bytes`, and adds -/// those bytes to `total` when the queue did not already hold it. -fn count_reference( - counts: &mut HashMap, - total: &mut usize, - address: usize, - bytes: usize, -) { - let entry = counts - .entry(address) - .or_insert(Counted { chunks: 0, bytes }); - if entry.chunks == 0 { - // The first chunk to meet the allocation is what makes the queue pay for it: a chunk - // sharing it afterwards adds a reference, not bytes. - *total = total.saturating_add(entry.bytes); - } - entry.chunks += 1; -} - -/// Gives one reference to the allocation at `address` back, and takes its bytes out of `total` when -/// it was the last one, so a queue that emptied leaves no entry and no bytes behind. -fn drop_reference(counts: &mut HashMap, total: &mut usize, address: usize) { - let last = match counts.get_mut(&address) { - // The chunk entered the queue before it left it, so one leaving cannot reach zero while - // another chunk of the queue still references the allocation. - Some(entry) if entry.chunks > 1 => { - entry.chunks -= 1; - false - } - Some(_) => true, - // Every chunk that leaves was queued, so its allocations were counted on the way in. An - // address missing here is exactly the asymmetry that would leak or undercharge silently. - None => { - debug_assert!(false, "the queue released an allocation it never counted"); - false - } - }; - if last && let Some(entry) = counts.remove(&address) { - *total = total.saturating_sub(entry.bytes); - } } /// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its @@ -343,55 +129,66 @@ fn drop_reference(counts: &mut HashMap, total: &mut usize, addre /// /// The figure is what the chunk keeps alive rather than one float per field and row: a histogram /// field holds no floats at all, only indices into the table its samples live in. -fn raw_bytes(chunk: &RawSeriesChunk, charged: &mut ChargedAllocations) -> usize { +fn raw_bytes(chunk: &RawSeriesChunk) -> usize { std::mem::size_of::() - .saturating_add(charged.buffer(&chunk.primary_key)) - .saturating_add(charged.buffer(chunk.time.as_buffer().inner())) - .saturating_add(fields_bytes(&chunk.fields, charged)) + .saturating_add(buffer_bytes(&chunk.primary_key)) + .saturating_add(chunk.metric.as_ref().map_or(0, metric_bytes)) + .saturating_add(buffer_bytes(chunk.time.as_buffer().inner())) + .saturating_add(fields_bytes(&chunk.fields)) } /// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields. /// -/// The figure is what the chunk keeps alive rather than one float per field and decided position: -/// a histogram field holds no floats at all, only indices into the table its samples live in. The -/// grid itself is shared by every chunk addressed on it, so it is not counted per chunk. -fn evaluated_bytes(chunk: &EvaluatedChunk, charged: &mut ChargedAllocations) -> usize { - std::mem::size_of::() - .saturating_add(fields_bytes(&chunk.series.fields, charged)) +/// The grid is shared by every chunk addressed on it, so it is not counted per chunk. +fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { + std::mem::size_of::().saturating_add(fields_bytes(&chunk.series.fields)) } /// The bytes the fields of a chunk hold: the sample buffers of every segment, and the histogram /// tables those segments reference. -fn fields_bytes(fields: &SeriesFields, charged: &mut ChargedAllocations) -> usize { +fn fields_bytes(fields: &SeriesFields) -> usize { fields .iter() .map(|field| { - field - .segments() - .iter() - .map(|segment| segment_bytes(segment, charged)) - .fold(0usize, usize::saturating_add) + field.segments().iter().fold(0usize, |total, segment| { + total.saturating_add(segment_bytes(segment)) + }) }) .fold(0usize, usize::saturating_add) } /// The bytes one dense segment of samples holds. -fn segment_bytes(segment: &Samples, charged: &mut ChargedAllocations) -> usize { +fn segment_bytes(segment: &Samples) -> usize { match segment.dense() { - Some(DenseSamplesRef::Float(values)) => charged.array(values), - Some(DenseSamplesRef::Histogram(histograms)) => charged - .array(histograms.indices()) - .saturating_add(charged.table(histograms.batch())), - Some(DenseSamplesRef::Mixed(mixed)) => charged - .array(mixed.floats()) - .saturating_add(charged.array(mixed.histograms().indices())) - .saturating_add(charged.table(mixed.histograms().batch())), - // `segments` hands out dense segments only, so a nested chunk never reaches here; one that - // somehow did is charged for the descriptor alone rather than for buffers it nests. + Some(DenseSamplesRef::Float(values)) => values.get_array_memory_size(), + Some(DenseSamplesRef::Histogram(histograms)) => histograms + .indices() + .get_array_memory_size() + .saturating_add(table_bytes(histograms.batch())), + Some(DenseSamplesRef::Mixed(mixed)) => mixed + .floats() + .get_array_memory_size() + .saturating_add(mixed.histograms().indices().get_array_memory_size()) + .saturating_add(table_bytes(mixed.histograms().batch())), + // `segments` hands out dense segments only, so a nested chunk never reaches here. None => 0, } } +/// The bytes one histogram table holds: the batch struct and the arrays its columns view. +fn table_bytes(table: &Arc) -> usize { + std::mem::size_of::().saturating_add(table.as_arrow().get_array_memory_size()) +} + +/// The bytes the allocation `buffer` is a slice of. +/// +/// The capacity is the whole allocation, which is what a slice keeps alive: a key of a few bytes +/// sliced out of a decoded dictionary values buffer pins that buffer. A buffer that owns no memory +/// of its own reports no capacity, and then the bytes it shows are all there is. +fn buffer_bytes(buffer: &Buffer) -> usize { + buffer.capacity().max(buffer.len()) +} + /// Which node kinds the runtime executes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum NodeTag { @@ -414,31 +211,11 @@ impl NodeTag { } } -/// The operation a node binds, kept aside until the whole tree has been visited. -/// -/// A window's evaluator needs its input's schema, and the input is visited after the window, so -/// the binding is collected first and the run-time state is built from the complete set. -enum Seed { - Input, - Window(BoundWindow), - Map(Arc<[MathOp]>), -} - -/// One visited node, before its input's position is resolved. -struct PendingNode { - tag: NodeTag, - path: NodePath, - metrics: Arc, - /// What this node produces, when it produces samples. - output_schema: Option>, - seed: Seed, -} - /// One node of the flattened tree. #[derive(Clone, Copy, Debug)] struct NodeSpec { tag: NodeTag, - /// The position of this node's input, resolved from the tree's own positions. + /// The index of this node's input, which is the node the build pass reaches next. input: Option, } @@ -446,12 +223,11 @@ struct NodeSpec { /// /// The reservation is the pool's, so a node that buffers input competes with every other operator /// in the query; the metrics report the same figure so a slow node can be told apart from a wide -/// one. +/// one. The reservation is also the figure itself: a node holds nothing beside what it reserved, so +/// a gauge reads its size rather than a copy that could drift from it. struct NodeBuffer { metrics: Arc, reservation: MemoryReservation, - /// The bytes `reservation` holds, mirrored so a chunk leaving returns exactly them. - held: usize, } impl NodeBuffer { @@ -461,35 +237,43 @@ impl NodeBuffer { Self { metrics, reservation: consumer.register(pool), - held: 0, } } - /// Reserves the bytes of a chunk this node starts holding. - fn hold(&mut self, bytes: usize) -> Result<()> { + /// Reserves `bytes` beside what this node already holds. + fn grow(&mut self, bytes: usize) -> Result<()> { self.reservation.try_grow(bytes)?; - self.held += bytes; - self.metrics.record_reserved_bytes(self.held); + self.record(); Ok(()) } /// Reserves exactly `bytes`, which is what this node holds from now on. /// - /// A node that consumes its input chunk by chunk what it holds afterwards is not the sum of - /// what it consumed, so the reservation is set from the state that is left rather than grown - /// per chunk. - fn hold_exactly(&mut self, bytes: usize) -> Result<()> { + /// What a node that consumes its input chunk by chunk holds afterwards is not the sum of what + /// it consumed, so the reservation is set from the state that is left rather than grown per + /// chunk. + fn resize(&mut self, bytes: usize) -> Result<()> { self.reservation.try_resize(bytes)?; - self.held = bytes; - self.metrics.record_reserved_bytes(bytes); + self.record(); Ok(()) } + /// Gives `bytes` of what this node holds back to the pool. + fn shrink(&mut self, bytes: usize) -> Result<()> { + self.reservation.try_shrink(bytes)?; + self.record(); + Ok(()) + } + + /// Reports what this node now reserves. + fn record(&self) { + self.metrics.record_reserved_bytes(self.reservation.size()); + } + /// Returns every byte this node holds to the pool. fn release(&mut self) { - self.held = 0; self.reservation.free(); - self.metrics.record_reserved_bytes(0); + self.record(); } } @@ -525,13 +309,28 @@ impl Run { #[derive(Default)] struct Emitted { sets: HashMap, - /// The bytes the entries in `sets` hold, kept as a running total. + /// How many run vectors, runs and label payload bytes every entry holds, counted as the entries + /// change rather than by walking them. /// - /// A node records every label set it has ever handed out and must charge for all of them, so - /// the figure is read after every output. Recomputing it there walks every entry recorded so - /// far, which is quadratic over a series that keeps producing label sets; folding one entry's - /// change in as it happens keeps the read constant. - entries: usize, + /// A node records every label set it has ever handed out and charges for all of them, so the + /// figure is read after every output; walking the table there would cost a pass over every entry + /// recorded so far for each output. Folding one entry's change in as it happens keeps the read + /// constant, and the update is the shape of the change itself: a vector's length before and + /// after [`absorb`], one vector per field a history gains, and one terminal pass over a closing + /// history's vector lengths. + counts: Counts, +} + +/// What the entries of an [`Emitted`] table hold, as running totals. +#[derive(Default)] +struct Counts { + /// The run vectors, one per field of one entry. + vectors: usize, + /// The occupied runs in every vector. + runs: usize, + /// The payload of every label set and of every owner: the bytes of their names and values with + /// one row per label. + payload: usize, } /// What one node has handed out under one output label set. @@ -549,10 +348,6 @@ struct History { owner: Option, /// Whether the series on this label set closed. A second series cannot close it again. closed: bool, - /// The heap this entry owns: the runs its per-field vectors hold and the owner's name and tags, - /// kept current by [`Emitted::occupy`]. The header and the slot it sits in are charged by the - /// table's capacity. - bytes: usize, } impl History { @@ -594,22 +389,6 @@ fn metric_bytes(metric: &MetricName) -> usize { .sum::() } -/// The bytes a history holds: the per-field vectors, the runs in them and its owner. -/// -/// This is what the entry itself allocates, not the slot it is filed under: the `History` lives in -/// the map's slot, and that slot is what [`Emitted::bytes`] charges with the table's capacity. A -/// `size_of::()` term here billed every entry one header for a value it does not own, -/// once in this figure and again in the slot term beside it. -fn history_bytes(history: &History) -> usize { - history.fields.capacity() * std::mem::size_of::>() - + history - .fields - .iter() - .map(|runs| runs.capacity() * std::mem::size_of::()) - .sum::() - + history.owner.as_ref().map_or(0, metric_bytes) -} - impl Emitted { /// Records what `chunk` occupies, rejecting it against what this node already handed out. /// @@ -678,69 +457,61 @@ impl Emitted { return Ok(()); } let fields = chunk.series.fields.len(); - // The change is folded in here rather than recomputed when the figure is read: a node - // keeps every label set it has ever handed out, so a fresh walk after each output costs a - // pass over the whole table for a table that only ever grows. let history = match self.sets.entry(labels) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { - self.entries += label_bytes(entry.key()); + self.counts.payload += label_bytes(entry.key()); entry.insert(History::default()) } }; - let before = history.bytes; // The series that contributes the values is the one that owns the label set, so a chunk of // another one cannot close it later on. if !empty && let Some(source) = source && history.owner.as_ref() != Some(source) { + self.counts.payload = self + .counts + .payload + .saturating_sub(history.owner.as_ref().map_or(0, metric_bytes)) + .saturating_add(metric_bytes(source)); history.owner = Some(source.clone()); } if history.fields.len() < fields { + self.counts.vectors += fields - history.fields.len(); history.fields.resize_with(fields, Vec::new); } for (index, runs) in occupied.into_iter().enumerate() { - absorb(&mut history.fields[index], &runs); + let stored = &mut history.fields[index]; + let before = stored.len(); + absorb(stored, &runs); + self.counts.runs = self.counts.runs - before + stored.len(); } if chunk.is_last { history.closed = true; // No later chunk reads these runs: a closed label set refuses every series that would // use them. Keeping them charges the pool for a series that has already been answered. + self.counts.runs -= history.fields.iter().map(Vec::len).sum::(); + self.counts.vectors -= history.fields.len(); history.fields = Vec::new(); } - let after = history_bytes(history); - history.bytes = after; - self.entries = self.entries - before + after; Ok(()) } /// An estimate of the bytes this table holds, which the node reserves for. /// - /// It counts each label's name and value bytes with a tuple per label, the runs a history keeps - /// in its per-field vectors, the owner each entry keeps with its name and tags, and the table's - /// capacity at one label-set slot plus one history slot per entry -- which is where a `History` - /// header itself is charged, once, for the entry that lives in it. It leaves out the map's - /// buckets and the `Arc` headers of the strings it shares, so it is a lower bound rather than a - /// measurement. - /// - /// The per-entry part is a running total, so reading this after every output does not walk the - /// table: only the entry that changed and the table's own capacity are read here. + /// It counts one label-set slot and one history header per entry, one vector per field of a + /// history, the runs in those vectors, and the payload of every label set and owner. Each of + /// those is a running total, so the figure is read in constant time however many series the node + /// has handed out; it leaves out the map's buckets, the slack of a vector's capacity and the + /// `Arc` headers of the strings it shares, so it is an approximation rather than a measurement. fn bytes(&self) -> usize { - self.entries - + self.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) - } - - /// The same figure by walking every entry, used by a test to keep the running total honest. - #[cfg(test)] - fn bytes_recomputed(&self) -> usize { - self.sets - .iter() - .map(|(labels, history)| label_bytes(labels) + history_bytes(history)) - .sum::() - + self.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) + let slots = + self.sets.len() * (std::mem::size_of::() + std::mem::size_of::()); + slots + + self.counts.vectors * std::mem::size_of::>() + + self.counts.runs * std::mem::size_of::() + + self.counts.payload } } @@ -934,88 +705,15 @@ struct MapRuntime { schema: Arc, } -/// What a window node holds. -struct WindowRuntime { - /// This window's own evaluator, with its own input and output grid; `None` once closed. - evaluator: Option, -} - -impl WindowRuntime { - /// The run-time state of the window `op`, reading the samples of `input`. - fn try_new(input: &SeriesSchema, op: &BoundWindow) -> Result { - // One evaluator per window, with the grids the node was bound to: the output grid is the - // node's own grid, which is also the grid its chunks are addressed on. - let evaluator = - RangeEvaluator::try_new(input, Arc::clone(&op.output_grid), op.window, op.function)?; - Ok(Self { - evaluator: Some(evaluator), - }) - } - - /// The bytes this window's charge accounts for, as its evaluator's storage stands now. - /// - /// Between pushes this is the accounted retained size: the sample buffers the evaluator keeps - /// per field, by capacity, with the payload of every native histogram they retain, the row a - /// push fills with the histograms it boxes, the pending batch's inner vectors, and the identity - /// payload of the series still open -- the allocation behind its primary key, not the bytes the - /// key shows. It is a lower bound on what is held, not a measurement of it. - /// - /// The kernel's scratch is left out, being a constant factor of the window samples already - /// counted. The `Emitted` table's own map overhead and the `Arc` headers of the strings it - /// shares are charged for beside this figure rather than inside it. Of the pending batch only - /// the inner vectors are counted, not the outer `spans` and `columns` that hold them. - /// - /// During a push the evaluator also holds the incoming chunk, which the caller charges while - /// the call runs; vector growth during a push is not reserved at all, and is not bounded by one - /// doubling either, since a bulk append can allocate more than twice the previous capacity and - /// several vectors can grow at once. So this is the storage's current size, not a peak over a - /// push. - /// - /// The evaluator is the only one that knows: it keeps samples per field, each field with its - /// own timestamps, values, reset index and native histograms, and it drops them by its own - /// rule. Mirroring that rule here would be a second copy of it, free to drift from the first. - fn retained_bytes(&self) -> usize { - self.evaluator - .as_ref() - .map_or(0, RangeEvaluator::retained_bytes) - } - - /// Feeds one input chunk to the evaluator and returns the chunk it yields, if any. - fn push(&mut self, path: &NodePath, chunk: &NativeChunk) -> Result> { - let evaluator = self.evaluator.as_mut().ok_or_else(|| closed(path))?; - match chunk { - // Raw samples are read window by window by the evaluator itself. - NativeChunk::Raw(chunk) => evaluator.push(chunk), - // An evaluated input is read as computed samples: the evaluator carries the window - // state of one series across its chunks and closes it on the chunk that says so. - // Handing each chunk over as it arrives is what lets this window report a decision - // before its input series has ended; buffering the chunks into a whole series first - // would hold the input's bytes and delay every result to the end of the series. - NativeChunk::Evaluated(chunk) => evaluator.push_series(&chunk.series, chunk.is_last), - } - } - - /// Closes this window, reporting an input that ended mid-series. - /// - /// The evaluator is what knows whether a series is still open, for evaluated input as much as - /// for raw: a chunk that did not say `is_last` leaves it holding the series. - fn finish(&mut self) -> Result<()> { - match self.evaluator.take() { - Some(evaluator) => evaluator.finish(), - None => Ok(()), - } - } -} - /// The per-node run-time state of a node. struct NodeRuntime { buffer: NodeBuffer, - /// Source chunks queued by the caller, for an input node. - queued: VecDeque, - /// What `queued` holds, folded in as chunks enter and out as they leave. - queued_charge: QueuedCharge, - /// What a window node holds. - window: Option, + /// Source chunks queued by the caller, for an input node, each with the estimate it was queued + /// with: what a chunk is worth is read once, as it enters, and given back as it leaves. + queued: VecDeque<(NativeChunk, usize)>, + /// A window node's evaluator, with its own input and output grid; `None` before it is built and + /// once it is closed. + window: Option, /// What a map node applies. map: Option, /// What this node has already handed out under each output label set, for a node that rewrites @@ -1039,58 +737,38 @@ struct NodeRuntime { } impl NodeRuntime { - /// Queues a source chunk, holding the bytes it needs until it leaves. + /// Queues a source chunk, holding what it is worth until it leaves. /// - /// What this node holds is its queue and nothing else, so the reservation is the queue's - /// running total: a chunk of a series can share its histogram table with a chunk of the same - /// series beside it, and counting the queue chunk by chunk would charge that one table once per - /// chunk instead of once for the allocation. - /// - /// The total is kept incrementally rather than recounted from the queue: recomputing it here - /// costs a pass over every queued chunk per chunk queued, so a caller that queues a whole series - /// before pulling it pays quadratically in the chunks it holds. What this costs instead is one - /// pass over the chunk entering, and the same on the way out. + /// What this node holds is its queue and nothing else, so the reservation is the sum of the + /// estimates of the chunks in it. A chunk is measured once, as it enters, and the figure it was + /// queued with is given back as it leaves, so neither operation walks the queue. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { let positions = chunk.positions(); - let bytes = self.queued_charge.enqueue(&chunk); - self.queued.push_back(chunk); - self.buffer.hold_exactly(bytes)?; + let bytes = chunk.bytes(); + // The chunk is held from here on, so the pool admits it before the queue keeps it: a + // rejected chunk leaves nothing behind. + self.buffer.grow(bytes)?; + self.queued.push_back((chunk, bytes)); self.buffer.metrics.record_input(1, positions); Ok(()) } - /// The bytes the chunks this node still queues hold, counted as one accounting pass. - /// - /// Test-only: what the node reserves for its queue is the running total of [`QueuedCharge`], so - /// this walk is the figure that total is checked against rather than the figure it is read from. - #[cfg(test)] - fn queued_bytes_recomputed(&self) -> usize { - let mut charged = ChargedAllocations::default(); - self.queued - .iter() - .map(|chunk| chunk.bytes(&mut charged)) - .fold(0usize, usize::saturating_add) - } - /// Hands over the next queued source chunk, if there is one. /// /// The handover is what [`Self::open_source_series`] follows: after this call the flag says /// whether the series the consumer just received a chunk of is still open, which is what closing /// the execution reads to tell a truncated input from one that ended cleanly. fn pop_source(&mut self) -> Result> { - let Some(chunk) = self.queued.pop_front() else { + let Some((chunk, bytes)) = self.queued.pop_front() else { return Ok(None); }; - // The leaving chunk gives back only what it alone held: an allocation a chunk still in the - // queue references stays charged, and no chunk left behind is walked to find that out. - let bytes = self.queued_charge.pop(&chunk); let metrics = Arc::clone(&self.buffer.metrics); { // An input node's own work is handing the chunk over, so its self time covers that and - // nothing its producer did. + // nothing its producer did. The chunk leaves this node, so the pool no longer has to + // hold it. let _timer = metrics.timer(); - // The chunk leaves this node, so the pool no longer has to hold it. - self.buffer.hold_exactly(bytes)?; + self.buffer.shrink(bytes)?; } metrics.record_output(1, chunk.positions()); // An evaluated source is already addressed on its grid, so its decided positions are grid @@ -1112,12 +790,9 @@ impl NodeRuntime { /// `None` means the operation emptied every position and the chunk does not close its series: /// there is nothing to hand on, and the input may still decide more. fn map(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result> { - let (bytes, positions, closing) = ( - evaluated_bytes(&chunk, &mut ChargedAllocations::default()), - chunk.series.time.len(), - chunk.is_last, - ); - self.buffer.hold(bytes)?; + let (positions, closing) = (chunk.series.time.len(), chunk.is_last); + // The chunk is held for as long as this node works on it. + self.buffer.grow(evaluated_bytes(&chunk))?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { // The timer covers this node's own work only: it is dropped before the driver polls @@ -1144,18 +819,15 @@ impl NodeRuntime { // the one that arrived. self.track(path, Some(&chunk.series.metric), output)?; } - let bytes = self.emitted_bytes(); - self.buffer.hold_exactly(bytes)?; + // The chunk is gone and the label sets this node has handed out are what is left. + let emitted = self.emitted_bytes(); + self.buffer.resize(emitted)?; Ok(output) } /// Feeds one chunk to this node's window. fn window(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { - let (bytes, positions, closing) = ( - chunk.bytes(&mut ChargedAllocations::default()), - chunk.positions(), - chunk.is_last(), - ); + let (positions, closing) = (chunk.positions(), chunk.is_last()); // Which series this chunk came from, for the label-set table below. A window consumes one // series to its `is_last` before the next, so the chunk that closes an output label set is // the one of the series that produced its values, which is what lets the table accept a @@ -1163,15 +835,22 @@ impl NodeRuntime { // series, so there is nothing to pass on. let source = chunk.metric(); // The chunk is held for as long as the evaluator consumes it. - self.buffer.hold(bytes)?; + self.buffer.grow(chunk.bytes())?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { let _timer = metrics.timer(); - match self.window.as_mut() { - Some(window) => window.push(path, &chunk), - None => Err(DataFusionError::Execution(format!( - "the node at {path} holds no window" - ))), + match (self.window.as_mut(), &chunk) { + // Raw samples are read window by window by the evaluator itself. + (Some(evaluator), NativeChunk::Raw(chunk)) => evaluator.push(chunk), + // An evaluated input is read as computed samples: the evaluator carries the window + // state of one series across its chunks and closes it on the chunk that says so. + // Handing each chunk over as it arrives is what lets this window report a decision + // before its input series has ended; buffering the chunks into a whole series first + // would hold the input's bytes and delay every result to the end of the series. + (Some(evaluator), NativeChunk::Evaluated(chunk)) => { + evaluator.push_series(&chunk.series, chunk.is_last) + } + (None, _) => Err(closed(path)), } }; metrics.record_input(1, positions); @@ -1190,30 +869,17 @@ impl NodeRuntime { self.track(path, source, output)?; } // The chunk has been consumed: what this node still holds is what the evaluator kept of it - // and the label sets it has already handed out. Between pushes the charge for both is the - // accounted size of that storage, a lower bound on what is held rather than a measurement: - // the evaluator's buffers by capacity -- with the payload of the histograms they retain and - // of the ones the row boxes -- and every label set handed out, leaving out the kernel's - // scratch, this table's map overhead with the `Arc` headers of its strings and the outer - // vectors of the pending batch. During one push the evaluator additionally holds the - // incoming chunk, charged by `hold` above for as long as the call runs, and vector growth - // is not reserved and not bounded by one doubling — a bulk append can allocate more than - // twice the previous capacity, and several vectors can grow at once — so this figure is - // what the storage stands at, not a peak over the push. - // - // The reason the figure must not be per-chunk: charging every chunk consumed makes the - // reservation grow with the chunk count, so a fixed window over a long series reads as an - // allocation failure even though the window holds no more samples. - // - // Both terms are charged whether or not this chunk produced one: a chunk that yields - // nothing leaves the evaluator's samples and every earlier series' history exactly where - // they were, so dropping the charge here would release memory this node still holds. + // and the label sets it has already handed out. Both are charged whether or not this chunk + // produced one -- a chunk that yields nothing leaves the evaluator's samples and every + // earlier series' history exactly where they were -- and neither is charged per chunk + // consumed, which would make a fixed window over a long series read as an allocation + // failure even though the window holds no more samples. let retained = self .window .as_ref() - .map_or(0, WindowRuntime::retained_bytes); + .map_or(0, RangeEvaluator::retained_bytes); let emitted = self.emitted_bytes(); - self.buffer.hold_exactly(retained.saturating_add(emitted))?; + self.buffer.resize(retained.saturating_add(emitted))?; Ok(output) } @@ -1259,30 +925,24 @@ impl NodeRuntime { self.open_source_series = false; self.queued.clear(); self.queued.shrink_to_fit(); - // The queue's counts go with the queue: they are what a later chunk would be folded onto, - // and a chunk that is dropped is a chunk the pool no longer has to hold. The reservation is - // returned below, once, for everything this node still held. - self.queued_charge = QueuedCharge::default(); + // The reservation is returned once, below, for everything this node still held. self.buffer.release(); } } /// The run-time state of one execution of a bound tree. /// -/// The state is keyed by tree position: the same positions [`metrics::walk`] derives, so a node's -/// state, its metrics and the name it is shown under cannot drift apart. Because none of it lives -/// on the tree, one compiled tree serves every execution that builds a state from it. +/// The state is keyed by tree position: the same positions [`crate::native::metrics::walk`] +/// derives, so a node's state, its metrics and the name it is shown under cannot drift apart. +/// Because none of it lives on the tree, one compiled tree serves every execution that builds a +/// state from it. pub struct NativeExecutionState { - /// The tree's structure, flattened in traversal order. + /// The tree's structure, flattened in traversal order, so the root is at index 0. nodes: Vec, /// The position of each node, in the same order. paths: Vec, /// The per-node state, in the same order. runtimes: Vec, - /// The index of every node, so a caller names a node the way the metrics do. - by_path: HashMap, - /// The index of the root node. - root: usize, /// The index of the tree's input node. source: usize, /// Whether the source hands over evaluated chunks rather than raw samples. @@ -1300,153 +960,119 @@ impl NativeExecutionState { metrics_set: &ExecutionPlanMetricsSet, partition: usize, ) -> Result { - // One traversal names and registers every node: the same walk `EXPLAIN` uses, so a node - // cannot be shown at one position and registered at another. - let mut pending: Vec = Vec::new(); - let mut unsupported: Option = None; - // The first input whose declared order this runtime cannot execute, and where it says so. - // Every node here reads one series at a time, so an input that interleaves them is one this - // runtime cannot execute. Recorded per input rather than kept from the first one seen: a - // tree with two inputs would otherwise have its second declaration read and dropped. - let mut unsupported_ordering_found: Option<(SeriesOrdering, NodePath)> = None; - metrics::walk(tree.root(), &mut |node, path| { + // One pass down the tree names and registers every node in the order + // `crate::native::metrics::walk` gives it: the same rule `EXPLAIN` uses, so a node cannot be + // shown at one position and registered at another. Every node this runtime executes is + // unary, so that order is the chain from the root to the input, and a node's input is the + // next one the pass reaches. + let mut nodes: Vec = Vec::new(); + let mut paths: Vec = Vec::new(); + let mut runtimes: Vec = Vec::new(); + let mut source: Option<(usize, Arc)> = None; + let mut node = tree.root(); + let mut path = NodePath::root(); + loop { + let index = nodes.len(); let handles = Arc::new(NodeMetrics::default()); - handles.register(path, metrics_set, partition); - let plan = match &node.expr { + handles.register(&path, metrics_set, partition); + let (tag, child) = match &node.expr { NativeExpr::Input(bound) => { + // Every node here reads one series at a time and assumes its chunks arrive + // together: a window feeds a series to its evaluator up to the chunk carrying + // `is_last`, and an input node keeps one flag for the series it handed over, + // which is what reports one that never closed. An input that declares + // `Interleaved` can leave a series open across another series' chunks, which + // either of those would misread, so the tree is refused here rather than run. + // That is a precondition of the runtime, not a limitation to document: the tree + // stays free to declare the ordering -- the compiler's job is not narrowed here + // -- and no tree this runtime executes declares it. if bound.ordering == SeriesOrdering::Interleaved { - unsupported_ordering_found - .get_or_insert_with(|| (bound.ordering, path.clone())); + return Err(unsupported_ordering(bound.ordering, &path)); } - Some((NodeTag::Input, Seed::Input)) - } - NativeExpr::Window { op, .. } => Some((NodeTag::Window, Seed::Window(op.clone()))), - NativeExpr::Map { op, .. } => Some((NodeTag::Map, Seed::Map(Arc::clone(&op.ops)))), - // The kinds below are legal in a bound tree, and `validate` stays the authority on - // that; this runtime simply does not execute them yet. - NativeExpr::Scalar(_) => { - unsupported.get_or_insert_with(|| not_implemented("Scalar", path)); - None - } - NativeExpr::Instant { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Instant", path)); - None - } - NativeExpr::Aggregate { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Aggregate", path)); - None - } - NativeExpr::Binary { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Binary", path)); - None - } - }; - if let Some((tag, seed)) = plan { - pending.push(PendingNode { - tag, - path: path.clone(), - metrics: handles, - output_schema: node.output.samples().cloned(), - seed, - }); - } - }); - // Rejected before a single chunk is read: a tree the runtime cannot execute must not - // start, because a partial answer would be one the caller never asked for. - if let Some(error) = unsupported { - return Err(error); - } - - // Every node here reads one series at a time and assumes its chunks arrive together: a - // window feeds a series to its evaluator up to the chunk carrying `is_last`, and an input - // node keeps one flag for the series it handed over, which is what reports one that never - // closed. An input that declares `Interleaved` can leave a series open across another - // series' chunks, which either of those would misread, so the tree is refused here rather - // than run. That is a precondition of the runtime, not a limitation to document: the tree - // stays free to declare the ordering -- the compiler's job is not narrowed here -- and no - // tree this runtime executes declares it. - if let Some((ordering, source)) = &unsupported_ordering_found { - return Err(unsupported_ordering(*ordering, source)); - } - - // A node's input is the node at the same position extended by the step the traversal took, - // so the structure is read off the positions instead of a second traversal that could - // disagree with the first. - let mut by_path = HashMap::with_capacity(pending.len()); - for (index, node) in pending.iter().enumerate() { - by_path.insert(node.path.clone(), index); - } - - let mut nodes = Vec::with_capacity(pending.len()); - let mut paths = Vec::with_capacity(pending.len()); - let mut runtimes = Vec::with_capacity(pending.len()); - for (index, node) in pending.iter().enumerate() { - let input = match node.tag { - NodeTag::Input => None, - NodeTag::Window | NodeTag::Map => { - let path = node.path.input(); - Some(*by_path.get(&path).ok_or_else(|| { + let samples = node.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution(format!( - "the native tree has no node at the input of {}", - node.path + "the input node at {path} does not produce samples" )) - })?) + })?; + source = Some((index, samples)); + (NodeTag::Input, None) } + NativeExpr::Window { input, .. } => (NodeTag::Window, Some(input.as_ref())), + NativeExpr::Map { input, .. } => (NodeTag::Map, Some(input.as_ref())), + // The kinds below are legal in a bound tree, and `validate` stays the authority on + // that; this runtime simply does not execute them yet. Rejected before a single + // chunk is read: a tree the runtime cannot execute must not start, because a + // partial answer would be one the caller never asked for. + NativeExpr::Scalar(_) => return Err(not_implemented("Scalar", &path)), + NativeExpr::Instant { .. } => return Err(not_implemented("Instant", &path)), + NativeExpr::Aggregate { .. } => return Err(not_implemented("Aggregate", &path)), + NativeExpr::Binary { .. } => return Err(not_implemented("Binary", &path)), }; - let buffer = NodeBuffer::new(&node.path, Arc::clone(&node.metrics), &pool); + let buffer = NodeBuffer::new(&path, handles, &pool); let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), - queued_charge: QueuedCharge::default(), window: None, map: None, emitted: None, open_source_series: false, }; - match &node.seed { - Seed::Input => {} - Seed::Map(ops) => { - let schema = node.output_schema.clone().ok_or_else(|| { + match &node.expr { + NativeExpr::Input(_) => {} + NativeExpr::Map { op, .. } => { + let schema = node.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution(format!( - "the map node at {} does not produce samples", - node.path + "the map node at {path} does not produce samples" )) })?; runtime.map = Some(MapRuntime { - ops: Arc::clone(ops), + ops: Arc::clone(&op.ops), schema, }); // A map drops the metric name, so it is one of the nodes that can turn two // series into one label set. runtime.emitted = Some(Emitted::default()); } - Seed::Window(window) => { - let child = input.ok_or_else(|| { + NativeExpr::Window { input, op } => { + let input_schema = input.output.samples().ok_or_else(|| { DataFusionError::Execution(format!( - "the window at {} has no input", - node.path + "the window at {path} consumes samples, but its input produces none" )) })?; - let input_schema = pending[child].output_schema.clone().ok_or_else(|| { - DataFusionError::Execution(format!( - "the window at {} consumes samples, but its input produces none", - node.path - )) - })?; - runtime.window = Some(WindowRuntime::try_new(&input_schema, window)?); + // One evaluator per window, with the grids the node was bound to: the output + // grid is the node's own grid, which is also the grid its chunks are addressed + // on. + runtime.window = Some(RangeEvaluator::try_new( + input_schema, + Arc::clone(&op.output_grid), + op.window, + op.function, + )?); // A window drops the metric name and the empty-valued labels, so a `rate` over // a series whose tag is empty and one where it is absent produces one label set // from two series. runtime.emitted = Some(Emitted::default()); } + NativeExpr::Scalar(_) + | NativeExpr::Instant { .. } + | NativeExpr::Aggregate { .. } + | NativeExpr::Binary { .. } => { + // Rejected above, where the pass has the position to name. + } } - debug_assert_eq!(nodes.len(), index); + // The input is the node the pass reaches next: the chain has no other node between + // this one and its input, and nothing is read off the positions afterwards. nodes.push(NodeSpec { - tag: node.tag, - input, + tag, + input: child.map(|_| index + 1), }); - paths.push(node.path.clone()); + paths.push(path.clone()); runtimes.push(runtime); + let Some(child) = child else { + break; + }; + node = child; + path = path.input(); } // The runtime's output is an evaluated chunk. Raw samples have no grid, and a scalar or @@ -1471,27 +1097,13 @@ impl NativeExecutionState { // The supported nodes are unary, so a tree of them has exactly one input node; it is where // the caller's chunks enter. - let root = *by_path.get(&NodePath::root()).ok_or_else(|| { - DataFusionError::Execution("the native tree has no root node".to_string()) - })?; - let source = nodes - .iter() - .position(|node| node.tag == NodeTag::Input) - .ok_or_else(|| { - DataFusionError::Execution("the native tree has no input node".to_string()) - })?; - let source_schema = pending[source].output_schema.clone().ok_or_else(|| { - DataFusionError::Execution(format!( - "the input node at {} does not produce samples", - pending[source].path - )) + let (source, source_schema) = source.ok_or_else(|| { + DataFusionError::Execution("the native tree has no input node".to_string()) })?; Ok(Self { nodes, paths, runtimes, - by_path, - root, source, source_is_evaluated: source_schema.eval_grid.is_some(), }) @@ -1499,7 +1111,7 @@ impl NativeExecutionState { /// The metrics of the node at `path`. pub fn metrics(&self, path: &NodePath) -> Option<&Arc> { - let index = *self.by_path.get(path)?; + let index = self.paths.iter().position(|candidate| candidate == path)?; Some(&self.runtimes[index].buffer.metrics) } @@ -1507,7 +1119,7 @@ impl NativeExecutionState { pub fn reserved_bytes(&self) -> usize { self.runtimes .iter() - .map(|runtime| runtime.buffer.held) + .map(|runtime| runtime.buffer.reservation.size()) .sum() } @@ -1521,63 +1133,6 @@ impl NativeExecutionState { self.nodes.is_empty() } - /// What the node at `path` charges for: the bytes its window's evaluator retains and the bytes - /// of the label sets it has handed out. - /// - /// Test-only: a window's reservation has to be exactly these two numbers, so a test compares - /// the reservation against them rather than against a figure the runtime keeps on the side. - #[cfg(test)] - fn window_charge(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - let runtime = &self.runtimes[index]; - ( - runtime - .window - .as_ref() - .map_or(0, WindowRuntime::retained_bytes), - runtime.emitted_bytes(), - ) - } - - /// The bytes the label sets at `path` charge for, and the same figure walked in full. - /// - /// Test-only: the running total is only correct if folding one entry's change in agrees with - /// recounting the table, so a test compares the two after the table has changed shape. - #[cfg(test)] - fn emitted_charge_pair(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - self.runtimes[index] - .emitted - .as_ref() - .map_or((0, 0), |emitted| { - (emitted.bytes(), emitted.bytes_recomputed()) - }) - } - - /// The bytes the queue at `path` charges for, and the same figure recounted by walking it. - /// - /// Test-only: the queue's running total is only correct if folding one chunk in as it enters and - /// out as it leaves agrees with one pass over what is left, so a test compares the two after the - /// queue has changed shape. - #[cfg(test)] - fn queued_charge_pair(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - let runtime = &self.runtimes[index]; - ( - runtime.queued_charge.bytes, - runtime.queued_bytes_recomputed(), - ) - } - /// How many nodes still hold the state a window buffers into. /// /// Test-only: releasing a stopped execution has to drop the evaluators and their sample @@ -1603,7 +1158,7 @@ impl NativeExecutionState { fn close(&mut self) -> Result<()> { let mut result = Ok(()); for (path, runtime) in self.paths.iter().zip(self.runtimes.iter_mut()) { - if let Some(window) = runtime.window.as_mut() + if let Some(window) = runtime.window.take() && let Err(error) = window.finish() && result.is_ok() { @@ -1668,8 +1223,8 @@ impl NativeExecutor { /// materialises nothing beyond the chunk in hand. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; - let root = self.state.root; - let result = self.pull(root).and_then(|chunk| match chunk { + // The root is the node the state was built from, which the pass puts first. + let result = self.pull(0).and_then(|chunk| match chunk { Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)), // Rejected when the state was built; kept as an error rather than a panic so an // impossible tree cannot take the process down. diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 93f810f83e7..c424ebda404 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -34,11 +34,10 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis} use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ - ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, NativeExecutor, - NodeBuffer, NodeRuntime, QueuedCharge, Run, absorb_rebuilds, label_bytes, map_chunk, raw_bytes, + Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, NodeRuntime, + absorb_rebuilds, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; -use crate::grid_series::{LabelSet, label_set}; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ @@ -345,7 +344,7 @@ fn raw_shared_histogram_chunk( .unwrap() } -/// A source node's runtime: the queue, its accounting and the reservation the two are held for. +/// A source node's runtime: the queue and the reservation it is held for. fn source_runtime(pool: &Arc) -> NodeRuntime { NodeRuntime { buffer: NodeBuffer::new( @@ -354,7 +353,6 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { pool, ), queued: VecDeque::new(), - queued_charge: QueuedCharge::default(), window: None, map: None, emitted: None, @@ -1052,6 +1050,54 @@ fn an_error_releases_the_reservation() { assert_eq!(pool.reserved(), 0); } +/// A chunk the pool cannot admit fails the execution and gives back everything it already held. +/// +/// The window holds the first chunk's samples, so the second one is refused against a reservation +/// that is already standing: the failure has to hand that reservation back too, rather than leaving +/// the pool full for as long as the caller keeps the stopped executor alive. +#[test] +fn a_pool_that_cannot_admit_a_chunk_releases_what_it_held() { + let tree = NativeTree::try_new(window(input(), grid(0, 60_000, 4))).unwrap(); + let schema = raw_schema(); + let set = ExecutionPlanMetricsSet::new(); + // Room for the first chunk and what the window keeps of it, not for the second one. + let pool = bounded_pool(16 << 10); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + + execution + .push_raw(raw_chunk(&schema, &[0], &[1.0], false)) + .unwrap(); + drop(execution.next_chunk().unwrap()); + let held = pool.reserved(); + assert!(held > 0, "the open series has to be reserved for"); + + // A hundred thousand samples are hundreds of kilobytes whatever the pool already holds. + let timestamps: Vec = (0..100_000).collect(); + let values = vec![1.0; 100_000]; + let error = execution + .push_raw(raw_chunk(&schema, ×tamps, &values, true)) + .expect_err("a chunk larger than the pool was admitted"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + + // The chunk never entered the queue, and everything the execution held went back to the pool + // while the executor is still alive. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + let current = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); + assert_eq!(gauge(&set, ¤t), 0); + let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); + assert!(gauge(&set, &peak) >= held); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + /// A map that drops the metric name cannot hand two series on under one label set. /// /// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own series, @@ -1411,6 +1457,71 @@ fn two_open_series_that_share_a_label_set_are_accepted_when_no_position_collides ); } +/// A `NaN` is a value and a missing sample is not, so only the `NaN` occupies its position. +/// +/// `abs` drops the metric name, so the two series below are one label set to the map, which is where +/// the two are read against each other. A position holding no sample is a position the series never +/// claimed, and another series may fill it; a position holding a `NaN` is decided and holds a value, +/// like any other, so a second value there is the collision no merge resolves. +#[test] +fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { + let map_grid = grid(0, 60_000, 1); + let tree = || { + NativeTree::try_new(map( + evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Contiguous), + vec![MathOp::Abs], + )) + .unwrap() + }; + let schema = evaluated_schema(Arc::clone(&map_grid)); + + // The first series' sample at position 0, the second series' sample there, and whether the two + // can share the label set `abs` leaves them. + let cases = [ + (vec![Some(f64::NAN)], vec![Some(1.0)], false), + (vec![Some(1.0)], vec![Some(f64::NAN)], false), + (vec![Some(f64::NAN)], vec![None], true), + (vec![Some(1.0)], vec![None], true), + (vec![None], vec![Some(f64::NAN)], true), + ]; + // Both chunks are open, so the label set is still open when the second series arrives: a closed + // set refuses every second series, and this test is about what occupies a position. + let drain = |execution: &mut NativeExecutor| -> Result<(), DataFusionError> { + while execution.next_chunk()?.is_some() {} + Ok(()) + }; + for (first, second, accepted) in cases { + let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + first.clone(), + false, + )) + .unwrap(); + drain(&mut execution).expect("the first open chunk is handed on"); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 0, + second.clone(), + false, + )) + .unwrap(); + let outcome = drain(&mut execution); + assert_eq!( + outcome.is_ok(), + accepted, + "{first:?} and {second:?} were {}: {:?}", + if accepted { "refused" } else { "handed on" }, + outcome.err(), + ); + } +} + /// One series arriving in pieces is not two series: a chunk that continues where its label set /// ended is handed on. /// @@ -1466,15 +1577,12 @@ fn a_series_that_continues_where_it_ended_is_not_a_second_series() { /// A window reserves what it retains, not what it has consumed. /// -/// A long series is fed one sample per chunk to a pool with a fixed budget, pulling and dropping -/// the result of every chunk and closing only on the last one. The same one-sample-per-chunk input -/// leaves the evaluator's storage at the same size however many chunks it arrives in, so the -/// reservation reaches the same figure whether the data is split into 64 chunks or into 1024. -/// -/// What the reservation has to be is not left to a constant: after every pull it is compared with -/// what the same window's evaluator says it retains and what the label sets it handed out hold. A -/// figure that merely did not grow with the chunk count would fail that, as would one that let the -/// emitted table go. +/// A long series is fed one sample per chunk to a pool with a fixed budget, pulling and dropping the +/// result of every chunk and closing only on the last one. The same one-sample-per-chunk input +/// leaves the evaluator's storage at the same size however many chunks it arrives in, so the peak +/// reservation is the same whether the data is split into 64 chunks or into 1024, and it stays a +/// small constant rather than the running total of what arrived. A figure charged per chunk +/// consumed would grow with the chunk count and exhaust the budget the first chunks fit in. #[test] fn a_window_reserves_what_it_retains_not_what_it_consumed() { // A 1 ms window on a 1 ms grid, so every chunk's sample is out of the window of the next one. @@ -1507,23 +1615,20 @@ fn a_window_reserves_what_it_retains_not_what_it_consumed() { }); // The output of every chunk is dropped: a consumer reading the series as it arrives // never holds it, and neither may the node. - let pulled = execution.next_chunk().unwrap_or_else(|error| { + drop(execution.next_chunk().unwrap_or_else(|error| { panic!("chunk {index} of the {count}-chunk series did not fit: {error}") - }); - drop(pulled); + })); let held = execution.state().reserved_bytes(); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); assert_eq!( held, - retained.saturating_add(emitted), - "chunk {index} of {count} holds {held} bytes, but the window retains {retained} \ - and handed out {emitted}" + pool.reserved(), + "chunk {index} of {count}: the state and the pool disagree on what is held" ); assert!( - held <= (4 << 10), + held <= (8 << 10), "chunk {index} of {count} holds {held} bytes of a 1 ms window over one sample" ); - peak = peak.max(held).max(pool.reserved()); + peak = peak.max(held); } peak }; @@ -1538,11 +1643,9 @@ fn a_window_reserves_what_it_retains_not_what_it_consumed() { /// A window's retention is per field, as the evaluator's storage is. /// /// The same one-sample-per-chunk input goes to a window over one float field, over two and over -/// three, and the reservation is compared with what each window retains after every pull. Every -/// field costs its own timestamps, values and row slot, so the figure grows by the same amount per -/// field; a figure counting one timestamp and one float per row would not. The widths are compared -/// by their increments rather than as a multiple of one: the identity of the open series is part of -/// the reservation and is counted once however many fields the series carries. +/// three. Every field costs its own timestamps, values and row slot, so the reservation a window +/// reaches grows with the width of the series; a figure counting one timestamp and one float per +/// row, or one field per series, would not. #[test] fn a_window_retains_the_samples_of_every_field() { // The most the window ever retained, over the same input and the same short window. @@ -1561,31 +1664,20 @@ fn a_window_retains_the_samples_of_every_field() { )) .unwrap(); drop(execution.next_chunk().unwrap()); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); - let held = execution.state().reserved_bytes(); - assert_eq!( - held, - retained.saturating_add(emitted), - "{width} field(s), chunk {index} of {count}: {held} bytes reserved, but the \ - window retains {retained} and handed out {emitted}" - ); - peak = peak.max(retained); + peak = peak.max(execution.state().reserved_bytes()); } peak }; let (one, two, three) = (peak(1), peak(2), peak(3)); assert!( two > one, - "a window over two fields retained {two} bytes, no more than the {one} bytes a window over \ - one field retains" + "a window over two fields reserved {two} bytes, no more than the {one} bytes a window over \ + one field reserves" ); - assert_eq!( - two - one, - three - two, - "a third field costs {} bytes where a second cost {}: the retention is not one field's \ - storage per field", - three - two, - two - one + assert!( + three > two, + "a window over three fields reserved {three} bytes, no more than the {two} bytes a window \ + over two fields reserves" ); } @@ -1606,7 +1698,8 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { )) .unwrap(); let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); execution .push_raw(raw_chunk(&schema, &[0, 60_000], &[1.0, 2.0], false)) @@ -1617,16 +1710,12 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { .expect("the first chunk decided both points"); assert_eq!(sample_values(&first), vec![Some(1.0), Some(2.0)]); drop(first); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + let after_output = execution.state().reserved_bytes(); assert!( - emitted > 0, + after_output > 0, "the window handed out a position, which it has to hold" ); - assert_eq!( - execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "the reservation does not cover the {emitted} bytes the window handed out" - ); + assert_eq!(after_output, pool.reserved()); // Both points are decided, so this chunk decides nothing and the window yields no chunk. execution @@ -1636,16 +1725,11 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { execution.next_chunk().unwrap().is_none(), "a chunk after every point was decided produced a chunk" ); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); assert!( - emitted > 0, - "the window's emitted table emptied itself between chunks" - ); - assert_eq!( - execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "a chunk with no output released the {emitted} bytes the emitted table still holds" + execution.state().reserved_bytes() > 0, + "a chunk with no output released the bytes the emitted table still holds" ); + assert_eq!(execution.state().reserved_bytes(), pool.reserved()); } /// A window cannot run over an interleaved input, and the runtime says so before reading a chunk. @@ -1731,52 +1815,6 @@ fn an_interleaved_input_is_refused_without_a_window() { assert!(message.contains("root.input"), "{message}"); } -/// The charge for the label sets a node has handed out does not depend on how it is read. -/// -/// The table only grows, so the figure is folded in as each entry changes rather than walked after -/// every output. Folding it wrong would show up as a running total that drifts from the same figure -/// recounted in full, so both are compared after every chunk: distinct label sets add entries, and -/// later chunks of one set grow its run vectors and the table's own capacity. -#[test] -fn the_emitted_charge_is_the_same_folded_in_as_walked() { - let grid = grid(0, 60_000, 4); - let tree = - NativeTree::try_new(map(evaluated_input(Arc::clone(&grid)), vec![MathOp::Abs])).unwrap(); - let schema = evaluated_schema(Arc::clone(&grid)); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - - let chunks = [ - ("a", "x", 0, vec![Some(-1.0), None, Some(-2.0), None], false), - ("a", "x", 0, vec![None, Some(-3.0), None, None], true), - ("b", "y", 0, vec![None, None, None, Some(-4.0)], true), - ( - "c", - "z", - 0, - vec![Some(-5.0), Some(-6.0), Some(-7.0), Some(-8.0)], - true, - ), - ]; - for (name, job, start, values, is_last) in chunks { - execution - .push_evaluated(evaluated_chunk_of( - &schema, - named_metric(name, job), - start, - values, - is_last, - )) - .unwrap(); - while execution.next_chunk().unwrap().is_some() {} - let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); - assert!(folded > 0, "the node handed out nothing to charge for"); - assert_eq!( - folded, walked, - "the folded charge of {folded} bytes is not the {walked} bytes the table holds" - ); - } -} - /// A series that produced values under a label set, followed by one that produced none under the /// same label set, is not a collision: the second contributes no sample, so the answer is just the /// first one's values. @@ -2175,14 +2213,12 @@ fn an_input_that_ends_mid_series_is_reported_without_a_window() { } } -/// A window over native histograms reserves what it retains, payload included, and the label-set -/// ledger it charges beside that agrees with a full walk of the table. +/// A window over native histograms reserves what it retains, payload included. /// -/// The chunk accounting walks the samples a chunk holds instead of charging one float per field and -/// row, so a histogram field -- which holds no float at all -- reaches both figures as the table its -/// indices point into. Neither may drift from what the node says it holds: the reservation is the -/// retained bytes plus the emitted ones, and the running total of the emitted table is the same -/// figure recounted in full. +/// A chunk is estimated from the samples it holds rather than from one float per field and row, so a +/// histogram field -- which holds no float at all -- reaches the figure as the table its indices point +/// into. A window over such a series therefore reserves for the payload it keeps, and a one-sample +/// histogram chunk is worth more than a one-sample float chunk of the same shape. #[test] fn a_window_over_histograms_reserves_what_it_retains() { let out = grid(0, 10_000, 2); @@ -2195,383 +2231,120 @@ fn a_window_over_histograms_reserves_what_it_retains() { )) .unwrap(); let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); for (timestamp, is_last) in [(0, false), (10_000, true)] { execution .push_raw(raw_histogram_chunk(&schema, &[timestamp], 2, is_last)) .unwrap(); while execution.next_chunk().unwrap().is_some() {} - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); - assert!( - emitted > 0, - "the window handed nothing out, so the ledger below charges for nothing" - ); assert_eq!( execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "the reservation is not what the window retains ({retained} bytes) plus what it handed \ - out ({emitted} bytes)", + pool.reserved(), + "the state and the pool disagree on what the window holds" ); - let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); - assert_eq!( - folded, walked, - "the folded charge of {folded} bytes is not the {walked} bytes the table holds", + assert!( + pool.reserved() > 0, + "a window over a histogram series reserves for nothing" ); } -} -/// One histogram table is charged once, however many chunks of the series reference it. -/// -/// The chunks of one series can share the immutable table their histogram indices point into, and a -/// node holding both of them holds one table: the source charges its queue as one accounting pass, -/// which counts the table the first time it meets it and the address the `Arc` holds is what makes -/// two clones one table. -#[test] -fn a_histogram_table_is_charged_once_per_pass() { - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - let chunk = |timestamp: i64, is_last: bool| { - let samples = - Samples::try_from_histogram(UInt32Array::from(vec![Some(index)]), Arc::clone(&table)) - .unwrap(); - RawSeriesChunk::try_new( - &schema, - Buffer::from_slice_ref(b"series-a"), - Some(metric()), - RawTimestamps::try_new(ScalarBuffer::from(vec![timestamp])).unwrap(), - SeriesFields::one(samples), - is_last, - ) - .unwrap() - }; - let (first, second) = (chunk(0, false), chunk(10_000, true)); - - let mut charged = ChargedAllocations::default(); - let queue = raw_bytes(&first, &mut charged).saturating_add(raw_bytes(&second, &mut charged)); - let alone = raw_bytes(&first, &mut ChargedAllocations::default()) - .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); + // The table the indices point into is what the field costs, so the same one-sample chunk is + // worth more as a histogram than as a float. + let histogram = raw_histogram_chunk(&schema, &[0], 2, true); + let float = raw_chunk(&schema, &[0], &[1.0], true); assert!( - queue < alone, - "a queue of two chunks sharing one table is charged {queue} bytes, no less than the \ - {alone} bytes they are charged apart: the table was counted twice", - ); - - // What the source reserves is exactly that one pass: it holds its queue and nothing else, and - // nothing has been pulled yet. - let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 1))).unwrap(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - execution.push_raw(first).unwrap(); - execution.push_raw(second).unwrap(); - assert_eq!( - execution.state().reserved_bytes(), - queue, - "the queue of two chunks sharing one table was not charged as one pass", + raw_bytes(&histogram) > raw_bytes(&float), + "a histogram chunk is estimated at {} bytes, no more than the {} bytes of a float chunk of \ + the same shape", + raw_bytes(&histogram), + raw_bytes(&float), ); } -/// A queue of two chunks that share one table charges it once, and the running total is what one -/// pass over the queue counts. +/// A source reserves the estimate of every queued chunk, and gives each one back as it leaves. /// -/// The figure the node reserves while both chunks are queued is the incremental one: the table is -/// met by the first chunk that references it and is not charged again by the second. Charging it -/// per chunk fails the record check, and recounting the queue per enqueue fails the count of -/// chunks walked in the test below. +/// The figure is symmetric: what a chunk added when it entered is what comes out when it leaves, so a +/// queue that empties returns its reservation to the pool exactly. Two chunks of one series may share +/// one immutable histogram table, and each of them is charged for it: the estimate is per chunk, which +/// costs a bounded over-count of a shared table rather than a pass over the queue per operation. #[test] -fn a_queued_allocation_is_charged_once() { +fn a_source_charges_its_queue_and_gives_it_back() { let pool = pool(); let mut source = source_runtime(&pool); let schema = raw_schema(); let mut builder = HistogramBatchBuilder::new(); let index = push_histogram(&mut builder, 2); let table = builder.finish().unwrap(); - let chunk = |timestamp: i64, is_last: bool| { - raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) - }; - let (first, second) = (chunk(0, false), chunk(10_000, true)); - - // What the two chunks cost charged apart, and what the second one costs on its own: the - // difference between the two is what the shared table is worth. - let apart = raw_bytes(&first, &mut ChargedAllocations::default()) - .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); - let second_alone = raw_bytes(&second, &mut ChargedAllocations::default()); + let first = raw_shared_histogram_chunk(&schema, &table, index, 0, false); + let second = raw_shared_histogram_chunk(&schema, &table, index, 10_000, true); + let (first_bytes, second_bytes) = (raw_bytes(&first), raw_bytes(&second)); source.enqueue(NativeChunk::Raw(first)).unwrap(); - let one = source.queued_charge.bytes; - assert_eq!( - one, - source.queued_bytes_recomputed(), - "one queued chunk is not charged what one pass over it counts" - ); - assert_eq!( - source.buffer.held, one, - "the reservation is not the queue's figure" - ); - assert_eq!(pool.reserved(), one); + assert_eq!(source.buffer.reservation.size(), first_bytes); + assert_eq!(pool.reserved(), first_bytes); source.enqueue(NativeChunk::Raw(second)).unwrap(); - let two = source.queued_charge.bytes; - let counted = *source - .queued_charge - .tables - .get(&(Arc::as_ptr(&table) as usize)) - .expect("the queue did not count the table both chunks index into"); assert_eq!( - counted.chunks, 2, - "two queued chunks reference the table, but the queue counts {}", - counted.chunks + source.buffer.reservation.size(), + first_bytes + second_bytes, + "the queue is not the sum of the estimates it holds" ); - assert_eq!( - two, - source.queued_bytes_recomputed(), - "the running total is not what one pass over the queue counts" - ); - assert_eq!( - two - one, - second_alone - counted.bytes, - "the chunk that entered charged the shared table a second time" - ); - assert!( - two < apart, - "a queue of two chunks sharing one table is charged {two} bytes, no less than the {apart} \ - bytes they are charged apart: the table was counted twice", - ); - assert_eq!(source.buffer.held, two); - assert_eq!(pool.reserved(), two); -} + assert_eq!(pool.reserved(), first_bytes + second_bytes); -/// A shared table is given back with the last queued chunk that references it, not the first. -/// -/// A leak here shows as a reservation that never returns: the first pop takes one reference away -/// and the table stays charged, the second takes the last one and the table goes with it. -#[test] -fn a_queued_allocation_is_given_back_with_its_last_chunk() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - let address = Arc::as_ptr(&table) as usize; - let chunk = |timestamp: i64, is_last: bool| { - raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) - }; - - source.enqueue(NativeChunk::Raw(chunk(0, false))).unwrap(); - source - .enqueue(NativeChunk::Raw(chunk(10_000, true))) - .unwrap(); - assert_eq!(source.queued_charge.tables[&address].chunks, 2); - - let first = source + let popped = source .pop_source() .unwrap() .expect("the queue held two chunks"); - assert!(!first.is_last()); + assert!(!popped.is_last()); + // One table, two queued chunks, two shares of its estimate: what leaves is what the chunk that + // left was charged, and the other chunk's share stays. assert_eq!( - source.queued_charge.tables[&address].chunks, 1, - "the chunk left in the queue still references the table, so it is still charged" + source.buffer.reservation.size(), + second_bytes, + "the chunk that left did not give its estimate back" ); - assert!( - source.queued_charge.bytes > 0, - "the queue still holds a chunk, but charges for nothing" - ); - assert_eq!( - source.queued_charge.bytes, - source.queued_bytes_recomputed(), - "the pop did not leave the running total at one pass over the queue" - ); - assert_eq!(source.buffer.held, source.queued_charge.bytes); + assert_eq!(pool.reserved(), second_bytes); source .pop_source() .unwrap() .expect("the queue held two chunks"); - assert!( - !source.queued_charge.tables.contains_key(&address), - "the last chunk referencing the table left, but the queue still counts it" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "a buffer outlived the chunks that referenced it" - ); + assert_eq!(source.buffer.reservation.size(), 0); assert_eq!( - source.queued_charge.bytes, 0, - "the queue is empty, but it is still charged for" + pool.reserved(), + 0, + "the queue emptied, but the pool holds its bytes" ); - assert_eq!( - source.buffer.held, 0, - "the reservation did not come back with the queue" - ); - assert_eq!(pool.reserved(), 0); assert!(source.pop_source().unwrap().is_none()); } -/// Queueing a chunk accounts for that chunk alone, however deep the queue is. +/// Releasing a node drops its queue and returns the reservation once. /// -/// The figure is the number of chunks the accounting walked, not wall time: `N` enqueues have to -/// walk `N` chunks and `N` pops another `N`, whatever the queue held. Recounting the queue per -/// operation -- the defect this refuses -- walks `N * (N + 1) / 2` chunks for the enqueues alone. +/// A node stopped with chunks still queued holds nothing afterwards: the queue goes, and the bytes it +/// was reserved for go back to the pool rather than staying held for as long as the caller keeps the +/// stopped executor alive. #[test] -fn queueing_a_chunk_walks_one_chunk() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let chunks = 64; - for index in 0..chunks { - let timestamp = i64::try_from(index).unwrap() * 10_000; - let chunk = raw_chunk(&schema, &[timestamp], &[1.0], index + 1 == chunks); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - } - assert_eq!( - source.queued_charge.walked, chunks, - "queueing {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", - source.queued_charge.walked, - ); - assert_eq!( - source.queued_charge.bytes, - source.queued_bytes_recomputed(), - "the running total is not what one pass over the queue counts" - ); - - let mut popped = 0; - while source.pop_source().unwrap().is_some() { - popped += 1; - } - assert_eq!(popped, chunks, "the queue did not hand back every chunk"); - assert_eq!( - source.queued_charge.walked, - 2 * chunks, - "popping {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", - source.queued_charge.walked, - ); - assert_eq!(source.queued_charge.bytes, 0); -} - -/// A mixed sequence of pushes and pulls leaves the queue's figure equal to one pass over what is -/// left in it, and the reservation equal to that figure. -/// -/// The chunks mix ones that share a table with ones that share nothing, so an allocation is -/// referenced by one, two or no queued chunk as the sequence runs. Both the node's own reservation -/// and the pool's are checked, so a total that drifts from the queue is caught by the figure the -/// memory pool actually holds. -#[test] -fn a_queue_figure_survives_a_mixed_push_and_pull_sequence() { +fn releasing_a_node_drops_its_queue() { let pool = pool(); let mut source = source_runtime(&pool); let schema = raw_schema(); let mut builder = HistogramBatchBuilder::new(); let index = push_histogram(&mut builder, 2); let table = builder.finish().unwrap(); - - for round in 0..6i64 { - for step in 0..2 { - let chunk = - raw_shared_histogram_chunk(&schema, &table, index, round * 10_000 + step, false); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - } - let chunk = raw_chunk(&schema, &[round * 10_000 + 2], &[1.0], false); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - let folded = source.queued_charge.bytes; - assert_eq!( - folded, - source.queued_bytes_recomputed(), - "round {round}: the running total is not one pass over the queue" - ); - assert_eq!(source.buffer.held, folded); - assert_eq!(pool.reserved(), folded); - - for _ in 0..2 { - if source.pop_source().unwrap().is_none() { - break; - } - } - let folded = source.queued_charge.bytes; - assert_eq!( - folded, - source.queued_bytes_recomputed(), - "round {round}: the running total is not one pass over what is left" - ); - assert_eq!(source.buffer.held, folded); - assert_eq!(pool.reserved(), folded); + for timestamp in [0, 10_000] { + source + .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( + &schema, &table, index, timestamp, false, + ))) + .unwrap(); } - - while source.pop_source().unwrap().is_some() {} - assert_eq!(source.queued_charge.bytes, 0); - assert!( - source.queued_charge.tables.is_empty(), - "a table outlived the chunks that referenced it" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "a buffer outlived the chunks that referenced it" - ); - assert_eq!(source.buffer.held, 0); - assert_eq!(pool.reserved(), 0); -} - -/// What a source reserves through the executor is the figure one pass over its queue counts. -#[test] -fn the_executor_reserves_what_one_pass_over_the_queue_counts() { - let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 4))).unwrap(); - let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - for step in 0..3 { - let chunk = raw_chunk(&schema, &[step * 10_000], &[1.0], false); - execution.push_raw(chunk).unwrap(); - } - let (folded, walked) = execution - .state() - .queued_charge_pair(&NodePath::root().input()); - assert_eq!( - folded, walked, - "the executor's queue is not charged what one pass over it counts" - ); - assert_eq!( - execution.state().reserved_bytes(), - folded, - "the source's reservation is not its queue's figure" - ); -} - -/// Releasing a node drops the queue's counts with the queue and returns the reservation once. -/// -/// A count left behind would be folded onto by the next chunk the node queues, and the reservation -/// shown as returned while the counts still hold the bytes is the leak this refuses. -#[test] -fn releasing_a_node_drops_the_queue_and_its_counts() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - source - .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( - &schema, &table, index, 0, false, - ))) - .unwrap(); - source - .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( - &schema, &table, index, 10_000, true, - ))) - .unwrap(); - assert_eq!(pool.reserved(), source.queued_charge.bytes); + assert!(pool.reserved() > 0); source.release(); assert!(source.queued.is_empty(), "the queue outlived its release"); - assert!( - source.queued_charge.tables.is_empty(), - "the queue's table counts outlived the queue" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "the queue's buffer counts outlived the queue" - ); - assert_eq!(source.queued_charge.bytes, 0); - assert_eq!(source.buffer.held, 0); + assert_eq!(source.buffer.reservation.size(), 0); assert_eq!(pool.reserved(), 0, "the reservation was not returned"); assert!(source.pop_source().unwrap().is_none()); } @@ -2608,83 +2381,6 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { ); } -/// One entry's figure is the heap it owns, and its `History` header is charged once, by its slot. -/// -/// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the -/// entry's own figure billed one header twice: once here and once in the capacity term beside it. -/// The two assertions below are the definition of the whole figure -- the labels, the vectors and -/// their runs, the owner's name and tags, and one label-set slot plus one history slot per entry -- -/// so either header counted in the wrong place fails them. -#[test] -fn a_history_entry_is_charged_once_for_its_header() { - let grid = grid(0, 10_000, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let metric = named_metric("requests", "job"); - let labels = label_set(&metric); - // Not the closing chunk: a closed label set drops its runs, and the runs are what the entry's - // own figure is. - let chunk = evaluated_chunk_of( - &schema, - metric.clone(), - 0, - vec![Some(1.0), Some(2.0)], - false, - ); - - let mut emitted = Emitted::default(); - emitted - .occupy(&NodePath::root(), Some(&metric), &chunk) - .unwrap(); - - let history = emitted - .sets - .get(&labels) - .expect("the chunk recorded its label set"); - // The owner the entry keeps is the series that filled it, so its name and each tag cost the - // same bytes the label set of the chunk did. - let owner = metric.name().map_or(0, |name| name.len()) - + std::mem::size_of_val(metric.tags()) - + metric - .tags() - .iter() - .map(|tag| tag.name.len() + tag.value.len()) - .sum::(); - let entry = label_bytes(&labels) - .saturating_add(history.fields.capacity() * std::mem::size_of::>()) - .saturating_add( - history - .fields - .iter() - .map(|runs| runs.capacity() * std::mem::size_of::()) - .sum::(), - ) - .saturating_add(owner); - assert_eq!( - history.owner.as_ref(), - Some(&metric), - "the entry does not name the series that filled it" - ); - assert!( - history.fields.iter().any(|runs| !runs.is_empty()), - "the entry kept no run, so it has no heap of its own to charge for" - ); - assert_eq!( - emitted.entries, - entry, - "the entry's own bytes are not its labels, its runs and its owner: a `History` header in \ - the figure would add the {} bytes its slot already charges", - std::mem::size_of::(), - ); - assert_eq!( - emitted.bytes(), - entry.saturating_add( - emitted.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) - ), - "the table's capacity is where a label-set slot and one `History` per entry are charged", - ); -} - /// A sparse series that only ever moves forward is appended to its history, not merged into it again /// chunk after chunk. /// diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 8575c91260a..c6c8fcc3d05 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -192,26 +192,12 @@ impl PendingBatch { /// The bytes this batch's own vectors hold, by capacity. fn bytes(&self) -> usize { - let spans = self - .spans - .iter() - .map(|spans| spans.capacity() * std::mem::size_of::>()) - .fold(0usize, usize::saturating_add); - let columns = self - .columns - .iter() - .map(|column| column.capacity() * std::mem::size_of::>()) - .fold(0usize, usize::saturating_add); - self.indices - .capacity() - .saturating_mul(std::mem::size_of::()) - .saturating_add( - self.eval_ts - .capacity() - .saturating_mul(std::mem::size_of::()), - ) - .saturating_add(spans) - .saturating_add(columns) + let spans: usize = self.spans.iter().map(|spans| spans.capacity()).sum(); + let columns: usize = self.columns.iter().map(|column| column.capacity()).sum(); + self.indices.capacity() * std::mem::size_of::() + + self.eval_ts.capacity() * std::mem::size_of::() + + spans * std::mem::size_of::>() + + columns * std::mem::size_of::>() } /// Drops the accumulated points, keeping the allocations. @@ -303,34 +289,23 @@ struct SeriesState { impl SeriesState { /// The bytes this series' identity holds, which the rows handed out do not cover. fn identity_bytes(&self) -> usize { - // A scan slices the primary key out of a decoded dictionary-values buffer, so the bytes the - // key shows are not the bytes it keeps: a key of a few bytes pins the whole buffer it was - // sliced out of, which `capacity` reports for the allocation behind the slice. Charging - // the key's length instead would show a handful of bytes for an allocation the size of a - // decoded batch. (A buffer that does not own its memory reports no capacity, and then the - // bytes it shows are all there is.) - // - // No dedupe is needed against a second slice of the same allocation: one evaluator holds - // one series at a time, and a window over an evaluated input holds no key at all, so a - // pass over this state charges one slice of one allocation rather than one per slice. + // A scan slices the primary key out of a decoded buffer, so the bytes the key shows are not + // the bytes it keeps: a key of a few bytes pins the allocation it was sliced out of. + // Charging the slice length instead would show a handful of bytes for an allocation the + // size of a decoded batch. One evaluator holds one series at a time, and an evaluated input + // holds no key at all, so there is no second slice of the same allocation to dedupe. let primary_key = self .primary_key .as_ref() .map_or(0, |key| key.capacity().max(key.len())); - let metric: usize = self - .metric - .name() - .map_or(0, |name| name.len()) - .saturating_add( - self.metric - .tags() - .iter() - .map(|tag| tag.name.len() + tag.value.len()) - .fold(0usize, usize::saturating_add), - ); - std::mem::size_of::() - .saturating_add(primary_key) - .saturating_add(metric) + let metric: usize = self.metric.name().map_or(0, |name| name.len()) + + self + .metric + .tags() + .iter() + .map(|tag| tag.name.len() + tag.value.len()) + .sum::(); + std::mem::size_of::() + primary_key + metric } } @@ -356,7 +331,17 @@ struct FieldSamples { head: usize, /// Native histogram samples, kept apart from the floats as Prometheus does. histograms: Vec<(i64, FloatHistogram)>, + /// Histograms before `histogram_head` are behind every remaining window; their payloads are + /// released by [`advance_histograms`](Self::advance_histograms). histogram_head: usize, + /// Estimated payload of the histograms this field still holds: the bucket lists and other + /// buffers the samples own, which no `size_of` of a slot shows. + /// + /// Measured for a histogram when it is admitted and released with it, so a retained sample is + /// not walked again on every push. A histogram is never modified once admitted, so the payload + /// its release subtracts is the one its admission added. Samples already behind every window + /// keep their payload in the figure until the drain releases them. + histogram_bytes: usize, /// Sequence number of `values[0]`. Absolute and monotonic across the series this evaluator /// evaluates, so a reset keeps its position when `head` samples are dropped instead of every /// index being renumbered. An empty field holds the number of samples already dropped, which @@ -392,37 +377,14 @@ fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterRes } impl FieldSamples { - /// The bytes this field's buffers hold, by capacity. - /// - /// The histogram term is the slot of every retained sample plus the payload the histogram in - /// that slot owns: a slot is one `(i64, FloatHistogram)` worth of struct, and the buckets the - /// histogram keeps are on the heap behind it, up to tens of kilobytes per sample. Only the - /// retained slice is walked, which is the storage the windows still read; the samples before - /// `head` are gone, their payloads with them. + /// 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 { - let histograms = self.histograms[self.histogram_head..] - .iter() - .map(|(_, histogram)| histogram.heap_bytes()) - .fold(0usize, usize::saturating_add); - self.timestamps - .capacity() - .saturating_mul(std::mem::size_of::()) - .saturating_add( - self.values - .capacity() - .saturating_mul(std::mem::size_of::()), - ) - .saturating_add( - self.histograms - .capacity() - .saturating_mul(std::mem::size_of::<(i64, FloatHistogram)>()), - ) - .saturating_add(histograms) - .saturating_add( - self.resets - .capacity() - .saturating_mul(std::mem::size_of::()), - ) + self.timestamps.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::() + + self.histogram_bytes } fn new(index_resets: bool) -> Self { @@ -498,6 +460,23 @@ impl FieldSamples { self.resets.drain(..dropped); } + /// Drops the histograms before `histogram_head`, releasing the payload they held. + /// + /// The dropped samples are measured as they go, which costs one measurement per dropped + /// histogram in total: the retained ones are never scanned again. + fn advance_histograms(&mut self) { + let head = std::mem::take(&mut self.histogram_head); + if head == 0 { + return; + } + let dropped: usize = self.histograms[..head] + .iter() + .map(|(_, histogram)| histogram.heap_bytes()) + .sum(); + self.histogram_bytes = self.histogram_bytes.saturating_sub(dropped); + self.histograms.drain(..head); + } + /// The resets inside the window holding `len` samples from `head`. fn resets_in(&self, len: usize) -> &[CounterReset] { let start = self.base + self.head as u64; @@ -507,22 +486,20 @@ impl FieldSamples { /// The bytes the histograms a row holds box, beyond the slots they sit in. /// -/// A slot is an `Option`: a pointer and a tag, which is all -/// `size_of::>()` is. A result that is a native histogram does not live in that -/// slot itself: the slot points at a `FloatHistogram` on the heap, which owns its bucket -/// lists in turn, and both are what the row keeps alive between pushes. Only slots that hold a -/// histogram are counted, and only those the last evaluated point left in place: a push clears the -/// row, so the slots past its length hold nothing. +/// A slot is an `Option`: a pointer and a tag. A result that is a native histogram +/// points at a [`FloatHistogram`] on the heap, which owns its bucket lists in turn, and both stay +/// alive between pushes. Only slots the last evaluated point left in place are counted: a push +/// clears the row. fn boxed_bytes(row: &[Option]) -> usize { row.iter() .flatten() - .filter_map(|sample| match sample { + .map(|sample| match sample { GridSample::Histogram(histogram) => { - Some(std::mem::size_of::().saturating_add(histogram.heap_bytes())) + std::mem::size_of::() + histogram.heap_bytes() } - GridSample::Float(_) => None, + GridSample::Float(_) => 0, }) - .fold(0usize, usize::saturating_add) + .sum() } impl RangeEvaluator { @@ -645,34 +622,30 @@ impl RangeEvaluator { self.batch_calls } - /// An accounted lower bound on the bytes this evaluator keeps between pushes. + /// An estimate of the bytes this evaluator keeps between pushes. /// /// Counted by capacity, so it is what the storage holds rather than what it uses: the retained - /// samples per field (timestamps, values and the native histograms with the payload each of - /// them owns), the reset index, the row a push fills with the histograms it boxes, and the - /// pending batch's own vectors. Left out are the kernel's scratch buffers, this struct's `Vec` - /// headers and the grid, which every chunk addressed on it shares. + /// samples per field (timestamps, values, the reset index and the native histograms with the + /// payload each of them owns), the row a push fills with the histograms it boxes, the identity + /// of the open series and the pending batch's own vectors. Left out are the kernel's scratch + /// buffers, this struct's `Vec` headers and the grid, which every chunk addressed on it shares. + /// + /// The figure is an estimate, not a ledger of every allocation: a histogram's payload is + /// measured once when it is admitted and released with it, so neither the retained samples nor + /// the transient allocations of a push are walked again. /// /// A push is the only caller that also holds the incoming chunk, and it charges that itself for - /// as long as the call runs; vector growth during a push is neither reserved nor bounded by one - /// doubling, so this is the storage's size, not a peak over the push. The figure must not be - /// per-chunk either: charging every chunk consumed would make the charge grow with the chunk - /// count, so a fixed window over a long series would read as an allocation failure even though - /// the window holds no more samples. + /// as long as the call runs. The figure must not be per-chunk either: charging every chunk + /// consumed would make the charge grow with the chunk count, so a fixed window over a long + /// series would read as an allocation failure even though the window holds no more samples. pub(crate) fn retained_bytes(&self) -> usize { - let per_field = self - .fields - .iter() - .map(FieldSamples::bytes) - .fold(0usize, usize::saturating_add); + let fields: usize = self.fields.iter().map(FieldSamples::bytes).sum(); let row = self.row.capacity() * std::mem::size_of::>(); - let boxed = boxed_bytes(&self.row); - let series = self.series.as_ref().map_or(0, SeriesState::identity_bytes); - per_field - .saturating_add(row) - .saturating_add(boxed) - .saturating_add(series) - .saturating_add(self.pending.bytes()) + fields + + row + + boxed_bytes(&self.row) + + self.series.as_ref().map_or(0, SeriesState::identity_bytes) + + self.pending.bytes() } /// Schema of the evaluated series: the input fields on the evaluation grid. @@ -1054,6 +1027,8 @@ impl RangeEvaluator { if !raw && h.reset_hint != CounterResetHint::Gauge { h.reset_hint = CounterResetHint::Unknown; } + field.histogram_bytes = + field.histogram_bytes.saturating_add(h.heap_bytes()); field.histograms.push((shifted, h)); } } @@ -1223,8 +1198,7 @@ impl RangeEvaluator { field.histogram_head = field.histograms.len(); } field.advance(); - field.histograms.drain(..field.histogram_head); - field.histogram_head = 0; + field.advance_histograms(); } Ok(()) } diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index beea2c27a31..183df1c4367 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -831,13 +831,15 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu .unwrap() } -/// A window has to reserve what a native histogram it retains owns, not only the slot it sits in. +/// A window retaining a native histogram is charged for the payload it owns, not only the slot. /// /// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps /// it, and the two runs differ in nothing but the number of buckets on the positive side: 4 and /// 4096. Those buckets are `(index, count)` pairs on the heap, which no `size_of` of the struct -/// shows -- 64 KiB for the wider one -- so the bytes the evaluator reports have to grow by at least -/// that payload between the two. A figure counting slots alone would report one number for both. +/// shows -- about 64 KiB for the wider one. The property is that this payload dominates the +/// estimate, not that it is counted to the byte: the wider histogram alone has to be reported as at +/// least half the physical width of its buckets, and the narrow one has to stay far below that. A +/// figure counting slots alone would report one number for both. #[test] fn a_retained_histogram_is_charged_for_its_buckets() { let retained = |buckets: i32| -> usize { @@ -864,12 +866,114 @@ fn a_retained_histogram_is_charged_for_its_buckets() { evaluator.retained_bytes() }; let (few, many) = (4, 4096); - let payload = usize::try_from(many - few).unwrap() * std::mem::size_of::<(i32, f64)>(); + let physical = usize::try_from(many).unwrap() * std::mem::size_of::<(i32, f64)>(); let (narrow, wide) = (retained(few), retained(many)); assert!( - wide >= narrow + payload, - "a window retaining one histogram of {many} buckets reports {wide} bytes, not the {narrow} \ - it reports for {few} buckets plus the {payload} bytes of bucket payload between them", + wide >= physical / 2, + "a window retaining one histogram of {many} buckets reports {wide} bytes, not at least half \ + the {physical} bytes its buckets occupy", + ); + assert!( + narrow < wide / 2, + "a window retaining one histogram of {few} buckets reports {narrow} bytes, not far below \ + the {wide} bytes it reports for {many} buckets: the bucket payload is not what the \ + estimate follows", + ); +} + +/// The payload a retained histogram is charged for is released with the sample. +/// +/// The histogram below is most of what the evaluator holds, and it stays inside the second grid +/// point's window: a push that only reaches the first point retains it. The chunk at 30 s is beyond +/// the window of every later point, so the evaluation that push triggers drops the histogram while +/// the series is still open. The estimate must come back down by its payload: one that charges at +/// admission and never releases it would keep reporting the history of every histogram the series +/// carried. The closing chunk then drains what is left and ends the series, so the estimate falls +/// back to the field and row buffers' capacity, with no series identity and no histogram payload. +#[test] +fn an_evicted_histogram_releases_its_payload() { + let schema = raw_schema(1); + let buckets = 4096; + let payload = usize::try_from(buckets).unwrap() * std::mem::size_of::<(i32, f64)>(); + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 10_000, 3), + // 20 s of window over 10 s of step: the histogram at 0 is inside the window of the second + // point but outside the third's, so the second push evicts it. + RangeWindow { + range_ms: 20_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::CountOverTime, + ) + .unwrap(); + evaluator + .push(&histogram_chunk(&schema, buckets, 0)) + .unwrap(); + let retained = evaluator.retained_bytes(); + assert!( + retained >= payload, + "a window retaining one histogram of {buckets} buckets reports {retained} bytes, less than \ + the {payload} bytes of buckets it holds", + ); + + // The float chunk keeps the series open, so only the window drops the histogram. + evaluator + .push(&chunk(&[(30_000, vec![Some(1.0)])], 1, 0, false)) + .unwrap(); + let evicted = evaluator.retained_bytes(); + assert!( + retained.saturating_sub(evicted) >= payload / 2, + "dropping one histogram of {payload} bytes left the estimate at {evicted} bytes, down from \ + {retained}: the payload it owned is still counted", + ); + + evaluator + .push(&chunk(&[(40_000, vec![Some(2.0)])], 1, 0, true)) + .unwrap(); + let closed = evaluator.retained_bytes(); + assert!( + closed < payload / 2, + "a closed series still reports {closed} bytes, of which the {payload} bytes of bucket \ + payload were released with their samples", + ); +} + +/// A fixed-size window over a long series of histograms reports a fixed size. +/// +/// Each push adds one histogram and the next point's window drops the one before it, so the +/// payload charged at admission has to come back at eviction. A counter that only grew would make +/// the estimate follow the length of the series instead of the window over it. +#[test] +fn a_fixed_window_over_histograms_keeps_the_estimate_bounded() { + let peak_retained = |chunks: i64| -> usize { + let schema = raw_schema(1); + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 1, 1024), + // One millisecond of window over a one millisecond step: the next point evicts the + // sample of this one. + RangeWindow { + range_ms: 1, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::CountOverTime, + ) + .unwrap(); + let mut peak = 0; + for ts in 0..chunks { + // Left open: the window, not the close, is what releases the sample. + evaluator.push(&histogram_chunk(&schema, 64, ts)).unwrap(); + peak = peak.max(evaluator.retained_bytes()); + } + peak + }; + assert_eq!( + peak_retained(8), + peak_retained(64), + "a fixed-size window over a series of histograms grew with the length of the series" ); } From 975b20cc79ad856f3b8bb8bf191cfb4966ccd332 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:33:10 +0800 Subject: [PATCH 07/10] fix(promql): merge rewritten logical series before window evaluation Accept disjoint closed-source fragments under one output label set. Retain occupancy checks and merge affected window inputs once at EOF using shared typed sample segments. Keep direct input windows and root maps streaming, and release collected fragments on finish or error. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/grid_series.rs | 330 +++++++++--- src/promql/src/grid_series/tests.rs | 332 +++++++++++- src/promql/src/native/execute.rs | 669 +++++++++++++++++++------ src/promql/src/native/execute/tests.rs | 615 +++++++++++++++++++---- 4 files changed, 1597 insertions(+), 349 deletions(-) diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index b5634b259e9..19d2ae2d1dd 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -24,7 +24,7 @@ use datafusion::error::{DataFusionError, Result}; use datatypes::series::MetricName; use datatypes::series::histogram::HistogramBatchBuilder; use datatypes::series::samples::{ - HistogramSamples, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema, + HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridSpan, TimeAxis}; @@ -310,6 +310,13 @@ pub(crate) fn label_set(metric: &MetricName) -> LabelSet { /// Merges series that share a label set into one, as Prometheus does after a function that /// rewrites labels or drops `__name__`; two of them holding one field at one point fail. +/// +/// The merge rearranges the payloads instead of rewriting them: a merged row takes the value its +/// member carries at that position -- a float, a NaN, or a native histogram -- and a field another +/// field's row does not fill keeps a null there. The values keep their storage: a run of rows one +/// member holds in one dense segment is handed out as a [`Samples::slice`] of that segment, so a +/// histogram table is shared rather than copied. The result costs one row per position holding a +/// value, plus the rows the other fields fill, and nothing for a position of the grid holding none. pub fn merge_same_labelset(schema: &Arc, series: Vec) -> Result> { let mut groups: HashMap> = HashMap::with_capacity(series.len()); let mut collided = false; @@ -328,111 +335,272 @@ pub fn merge_same_labelset(schema: &Arc, series: Vec) -> R return Ok(series); } + // The merged axis and the fields placed on it are the schema's grid: a member of another grid + // would land its rows at positions naming other timestamps. + let grid = schema.eval_grid.clone().ok_or_else(|| { + DataFusionError::Execution("grid series schema requires an evaluation grid".into()) + })?; let mut series: Vec> = series.into_iter().map(Some).collect(); let mut output = Vec::with_capacity(groups.len()); - let mut builder = GridSeriesBuilder::try_new(schema.clone())?; - // `(absolute position, member slot, compact row)`, sorted by position before merging. The - // slot indexes `members`, so the merge below picks the member's cursor directly instead of - // searching for the member per row. + // `(absolute position, member slot, compact row)`, sorted by position before merging. The slot + // indexes the group's fragments, so a row names its member without a search. let mut rows: Vec<(usize, usize, usize)> = Vec::new(); - let mut values = vec![None; schema.fields.len()]; - let mut merged = vec![None; schema.fields.len()]; + // The position of each merged row, ascending, with the positions several fragments share held + // once. + let mut positions: Vec = Vec::new(); for (labels, members) in groups { if let [member] = members[..] { output.extend(series[member].take()); continue; } - builder.begin_series(); - rows.clear(); - for (member_slot, &member) in members.iter().enumerate() { - let member_series = series[member] - .as_ref() - .expect("each series is in one group"); - if member_series.time.grid().is_none() { + // Validate every fragment before indexing it: the merge reads its fields and places its + // rows on the schema's grid. + let mut fragments: Vec<&Series> = Vec::with_capacity(members.len()); + for &member in &members { + let fragment = series[member].as_ref().ok_or_else(|| { + DataFusionError::Execution("each series is in exactly one label set".into()) + })?; + let Some(fragment_grid) = fragment.time.grid() else { return Err(DataFusionError::Execution( "merging requires evaluated series".into(), )); + }; + if fragment_grid.spec() != grid.spec() { + return Err(DataFusionError::Execution( + "merging requires one evaluation grid".into(), + )); } - // The axis names the positions this member holds, and one cursor per field reads its - // values in the same order, so a member of several runs costs its rows. - let mut cursors: Vec> = member_series + if fragment.fields.len() != schema.fields.len() { + return Err(DataFusionError::Execution(format!( + "merging requires {} fields, a fragment holds {}", + schema.fields.len(), + fragment.fields.len() + ))); + } + // The alignment is checked before a row is read: a field of another length would either + // run off the axis or leave values the axis never reaches. + let time_len = fragment.time.len(); + if let Some((field, samples)) = fragment .fields .iter() - .map(|field| field.cursor()) - .collect(); - for (point, row) in member_series.time.positions() { - if read_row(&mut cursors, row, &mut values)? { - rows.push((point, member_slot, row)); + .enumerate() + .find(|(_, samples)| samples.len() != time_len) + { + return Err(DataFusionError::Execution(format!( + "merging requires every field to hold the {time_len} rows of its axis, field \ + {field} holds {}", + samples.len() + ))); + } + fragments.push(fragment); + } + rows.clear(); + for (member_slot, fragment) in fragments.iter().enumerate() { + // One forward reader per field: the axis names the rows that exist, and a row holding + // no value in any field is not a merged row. + let mut readers: Vec> = + fragment.fields.iter().map(FieldReader::new).collect(); + for (position, row) in fragment.time.positions() { + let mut present = false; + for reader in &mut readers { + let (segment, offset) = reader.locate(row)?; + present |= !matches!(segment.sample(offset), SampleRef::Missing); + } + if present { + rows.push((position, member_slot, row)); } } } - // By position, then by member slot: the slots follow the order `members` was built in, so - // the merge below still walks each member's rows forward and its cursors never go back. + // By position, then by member slot: the slots follow the order the fragments were collected + // in, so a member's rows only go forward and its readers never go back. rows.sort_unstable(); - // One forward cursor per member and field, so re-reading a row costs neither a chunk scan - // nor an allocation. - let mut cursors: Vec>> = members - .iter() - .map(|&member| { - let member_series = series[member] - .as_ref() - .expect("each series is in one group"); - member_series - .fields - .iter() - .map(|field| field.cursor()) - .collect() - }) - .collect(); - let mut start = 0; - while start < rows.len() { - let point = rows[start].0; - let end = start + rows[start..].partition_point(|&(p, _, _)| p == point); - // Rows of one point merge field by field; only a field present twice collides. - merged.iter_mut().for_each(|value| *value = None); - for &(_, member_slot, row) in &rows[start..end] { - read_row(&mut cursors[member_slot], row, &mut values)?; - for (slot, value) in merged.iter_mut().zip(&values) { - if value.is_some() { - if slot.is_some() { - let labels: Vec<_> = labels - .iter() - .map(|(name, value)| format!("{name}=\"{value}\"")) - .collect(); - return Err(DataFusionError::Execution(format!( - "vector cannot contain metrics with the same labelset {{{}}}", - labels.join(", ") - ))); - } - *slot = *value; - } - } - } - builder.push(point, &merged)?; - start = end; + positions.clear(); + positions.extend(rows.iter().map(|&(position, _, _)| position)); + positions.dedup(); + let mut fields = Vec::with_capacity(schema.fields.len()); + for field in 0..schema.fields.len() { + let mut readers: Vec> = fragments + .iter() + .map(|fragment| FieldReader::new(&fragment.fields.as_slice()[field])) + .collect(); + fields.push(merge_field(&mut readers, &rows, &labels)?); } - let metric = series[members[0]].as_ref().unwrap().metric.clone(); - output.extend(builder.finish(metric)?); + // The runs are all the axis remembers about the holes, so a sparse merge stores one span + // per run and no row for the positions between them. + let time = + TimeAxis::from_grid_spans(grid.clone(), spans_of(&positions)).map_err(external)?; + let fields = SeriesFields::try_from_vec(fields).map_err(external)?; + // The first fragment names the output, as it always has: a label set ignores empty values, + // so the metric of the first member is the one the merged series keeps. + let metric = fragments[0].metric.clone(); + output.push(Series::try_new(schema, metric, time, fields).map_err(external)?); } Ok(output) } -/// Reads the float fields of `row` through the member's cursors; returns whether any is present. -fn read_row(cursors: &mut [RowCursor<'_>], row: usize, values: &mut [Option]) -> Result { - let mut present = false; - for (value, cursor) in values.iter_mut().zip(cursors) { - *value = match cursor.at(row).expect("the axis and the fields are aligned") { - SampleRef::Missing => None, - SampleRef::Float(value) => Some(value), - SampleRef::Histogram(_) => { - return Err(DataFusionError::NotImplemented( - "merging histogram series with the same label set".into(), - )); +/// Builds one field of the merged series, one sample per merged row. +/// +/// The rows are walked in output order. A row holding a value of this field in one member continues +/// the run of rows that member holds in one dense segment, and a run is handed out as one +/// [`Samples::slice`]; the rows another field fills become one null run, so the field stays aligned +/// with the merged axis while sharing the values it carries. +fn merge_field( + readers: &mut [FieldReader<'_>], + rows: &[(usize, usize, usize)], + labels: &LabelSet, +) -> Result { + let mut chunks: Vec = Vec::new(); + // The run of values the last merged row continued, if any. + let mut run: Option> = None; + // Merged rows this field leaves empty, waiting for the null run that carries them. + let mut missing = 0; + let mut start = 0; + while start < rows.len() { + let position = rows[start].0; + let mut end = start; + // At most one member may hold this field here; the second value is the collision Prometheus + // rejects, since the two label sets became one. + let mut value: Option<(usize, &Samples, usize)> = None; + while end < rows.len() && rows[end].0 == position { + let (_, member, row) = rows[end]; + let (segment, offset) = readers[member].locate(row)?; + if !matches!(segment.sample(offset), SampleRef::Missing) { + if value.is_some() { + let labels: Vec<_> = labels + .iter() + .map(|(name, value)| format!("{name}=\"{value}\"")) + .collect(); + return Err(DataFusionError::Execution(format!( + "vector cannot contain metrics with the same labelset {{{}}}", + labels.join(", ") + ))); + } + value = Some((member, segment, offset)); } - }; - present |= value.is_some(); + end += 1; + } + match value { + Some((member, segment, offset)) => { + if let Some(run) = &mut run + && run.continues(member, segment, offset) + { + run.len += 1; + } else { + if let Some(run) = run.take() { + run.push(&mut chunks)?; + } + push_missing(&mut chunks, &mut missing); + run = Some(FieldRun { + member, + segment, + offset, + len: 1, + }); + } + } + None => { + if let Some(run) = run.take() { + run.push(&mut chunks)?; + } + missing += 1; + } + } + start = end; + } + if let Some(run) = run { + run.push(&mut chunks)?; + } + push_missing(&mut chunks, &mut missing); + Samples::try_from_chunks(chunks).map_err(external) +} + +/// A run of merged rows one member field fills out of one dense segment, without copying values. +/// +/// The run grows only while the next merged row is the same member's next row in the same segment, +/// so handing it out is one [`Samples::slice`] of that segment: the payload stays where it is, and +/// the rows a hole skipped are not part of the run. +struct FieldRun<'a> { + /// The member slot the run reads, which indexes the [`FieldReader`]s of the field. + member: usize, + /// The dense segment holding the run's values. + segment: &'a Samples, + /// Offset of the run's first row inside `segment`. + offset: usize, + /// How many rows of `segment` the run covers. + len: usize, +} + +impl FieldRun<'_> { + /// Returns whether the value at `offset` of `segment` continues the run: the same member's next + /// row in the same dense segment. + fn continues(&self, member: usize, segment: &Samples, offset: usize) -> bool { + self.member == member + && std::ptr::eq(self.segment, segment) + && self.offset + self.len == offset + } + + /// Pushes the run as one slice of its dense segment. + fn push(self, chunks: &mut Vec) -> Result<()> { + chunks.push( + self.segment + .slice(self.offset, self.len) + .map_err(external)?, + ); + Ok(()) + } +} + +/// Reads one field's rows by locating the dense segment each row sits in. +/// +/// [`Samples::sample`] rescans a chunked field from its first segment on every row, so reading a +/// field row by row would cost a scan over the segments before it. The rows a merge reads only go +/// forward, so this walks the segments once and returns the segment with the offset of the row +/// inside it, which is what a [`FieldRun`] slices. +struct FieldReader<'a> { + segments: &'a [Samples], + /// Index of the segment `start` belongs to. + segment: usize, + /// Logical row the current segment starts at. + start: usize, +} + +impl<'a> FieldReader<'a> { + /// Creates a reader at the first row of `samples`. + fn new(samples: &'a Samples) -> Self { + Self { + segments: samples.segments(), + segment: 0, + start: 0, + } + } + + /// Returns the dense segment holding `row` and the offset of `row` inside it. + /// + /// Rows must not go backwards. A row past the field is an error rather than a panic: a member is + /// only read after its fields are validated to align with its axis. + fn locate(&mut self, row: usize) -> Result<(&'a Samples, usize)> { + while let Some(segment) = self.segments.get(self.segment) { + if let Some(offset) = row + .checked_sub(self.start) + .filter(|offset| *offset < segment.len()) + { + return Ok((segment, offset)); + } + self.segment += 1; + self.start += segment.len(); + } + Err(DataFusionError::Execution( + "merging requires each field to be row-aligned with its time axis".into(), + )) + } +} + +/// Pushes the merged rows a field leaves empty as one null run. +fn push_missing(chunks: &mut Vec, missing: &mut usize) { + if *missing != 0 { + chunks.push(Samples::from_float(Float64Array::new_null(*missing))); + *missing = 0; } - Ok(present) } pub(crate) fn external(error: datatypes::error::Error) -> DataFusionError { diff --git a/src/promql/src/grid_series/tests.rs b/src/promql/src/grid_series/tests.rs index 59e833e3fd3..a64ce8a94e6 100644 --- a/src/promql/src/grid_series/tests.rs +++ b/src/promql/src/grid_series/tests.rs @@ -15,15 +15,20 @@ use std::mem::size_of; use std::sync::Arc; -use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridSpec}; +use datafusion::arrow::array::{Float64Array, UInt32Array}; +use datatypes::series::histogram::{HistogramBatch, HistogramBatchBuilder}; +use datatypes::series::samples::{ + DenseSamplesRef, FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, + SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, MetricName}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use super::reference::{ - Labels, Points, assert_pieces_eq, assert_result_eq, points_of, random_dense, run_ranges, - series_of, stitch, + Labels, OwnedHistogram, Points, assert_pieces_eq, assert_result_eq, metric_of, points_of, + random_dense, run_ranges, series_of, stitch, }; use super::{GridSeriesBuilder, merge_same_labelset}; @@ -479,6 +484,325 @@ fn finish_hands_out_only_the_rows_pushed_after_a_prefix_flush() { assert!(!builder.has_pending()); } +// --------------------------------------------------------------------------------------------- +// Merging: one label set handed over in several fragments. +// +// A runtime hands one label set over as fragments, and the merge is the only place that puts them +// back into one series. What these tests pin is that the values move without being rebuilt: the +// merged series shares the fragments' payloads, keeps native histograms and NaNs, and still costs +// one row per position holding a value. +// --------------------------------------------------------------------------------------------- + +/// The start of the float buffer a dense float segment reads, to show a merge shared the buffer +/// instead of copying it. +fn float_ptr(segment: &Samples) -> *const f64 { + match segment.dense() { + Some(DenseSamplesRef::Float(values)) => values.values().as_ptr(), + _ => panic!("expected a dense float segment"), + } +} + +type FragmentRow<'a> = (usize, Option, Option<&'a str>, Option); + +/// A two-field fragment: field 0 holds a float or a native histogram, field 1 a float. +/// +/// `rows` holds `(position, field 0 float, field 0 histogram, field 1 float)` in ascending position +/// order; a row holds a value when some field has one at that position. +fn fragment_with_histograms( + schema: &Arc, + labels: &Labels, + rows: &[FragmentRow<'_>], +) -> (Series, Arc) { + let mut batch = HistogramBatchBuilder::new(); + let mut spans: Vec = Vec::new(); + let mut floats = Vec::with_capacity(rows.len()); + let mut indices = Vec::with_capacity(rows.len()); + let mut seconds = Vec::with_capacity(rows.len()); + for &(position, float, histogram, second) in rows { + match spans.last_mut() { + Some(span) if span.start() + span.len() == position => { + *span = GridSpan::new(span.start(), span.len() + 1); + } + _ => spans.push(GridSpan::new(position, 1)), + } + floats.push(float); + indices.push(histogram.map(|text| { + batch + .push(OwnedHistogram::parse(text).view()) + .expect("the fixture histogram is valid") + })); + seconds.push(second); + } + let batch = batch.finish().expect("an empty histogram table is valid"); + let histograms = HistogramSamples::try_new(UInt32Array::from(indices), batch.clone()).unwrap(); + let mixed = Samples::try_from_mixed(Float64Array::from(floats), histograms).unwrap(); + let fields = SeriesFields::try_from_vec(vec![ + mixed, + Samples::from_float(Float64Array::from(seconds)), + ]) + .unwrap(); + let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap(); + ( + Series::try_new(schema, metric_of(labels), time, fields).unwrap(), + batch, + ) +} + +/// Two fragments a boundary kept apart -- the first holding position 0, the second positions 1 and +/// 2 -- become one series of one run, each fragment's rows at its own positions. +#[test] +fn merge_of_adjacent_fragments_is_one_run() { + let schema = grid_schema(1, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let first = series_of(&schema, &labels, &Points::from([(0, 1f64.to_bits())])).unwrap(); + let second = series_of( + &schema, + &labels, + &Points::from([(1, 2f64.to_bits()), (2, 3f64.to_bits())]), + ) + .unwrap(); + let first_ptr = float_ptr(&first.fields.as_slice()[0].segments()[0]); + let second_ptr = float_ptr(&second.fields.as_slice()[0].segments()[0]); + + let merged = merge_same_labelset(&schema, vec![first, second]).unwrap(); + assert_eq!(merged.len(), 1, "one label set, one merged series"); + assert_eq!(merged[0].time.len(), 3, "one row per value"); + assert_eq!( + run_ranges(&merged[0]), + vec![(0, 3)], + "fragments holding adjacent positions share one run" + ); + assert_eq!( + points_of(&merged[0]), + Points::from([ + (0, 1f64.to_bits()), + (1, 2f64.to_bits()), + (2, 3f64.to_bits()), + ]) + ); + // One slice per fragment: the second fragment's two rows are one slice of its own buffer, and + // neither slice copies a value. + let chunks = merged[0].fields.as_slice()[0].segments(); + assert_eq!(chunks.len(), 2, "one slice per fragment"); + assert_eq!(float_ptr(&chunks[0]), first_ptr); + assert_eq!(float_ptr(&chunks[1]), second_ptr); + assert_eq!(chunks[1].len(), 2, "the fragment's two rows are one slice"); +} + +/// Native histograms, floats, NaNs and complementary fields merge into one aligned series, and +/// every value keeps the storage it already had: the histogram table and the float buffers are +/// shared, not rebuilt. +#[test] +fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them() { + let schema = grid_schema(2, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let histogram = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"; + // The first fragment holds a native histogram in field 0 and a float in field 1 at position 0. + let (first, first_batch) = + fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), Some(1.0))]); + // The second holds field 0's float at position 1 and field 1's NaN at position 2, leaving the + // other field missing at each. + let (second, _) = fragment_with_histograms( + &schema, + &labels, + &[(1, Some(2.0), None, None), (2, None, None, Some(f64::NAN))], + ); + let second_field1 = float_ptr(&second.fields.as_slice()[1].segments()[0]); + + let merged = merge_same_labelset(&schema, vec![first, second]).unwrap(); + assert_eq!(merged.len(), 1); + assert_eq!( + run_ranges(&merged[0]), + vec![(0, 3)], + "positions 0, 1 and 2 are one run" + ); + assert_eq!(merged[0].time.len(), 3); + assert_eq!(merged[0].fields.len(), 2); + + // Field 0: the histogram, the float, and a null at the position only field 1 fills. + let field0 = merged[0].fields.as_slice()[0].segments(); + assert_eq!(field0.len(), 3, "a histogram, a float, and one null run"); + let DenseSamplesRef::Mixed(mixed) = field0[0].dense().unwrap() else { + panic!("the histogram lost its mixed column") + }; + assert!( + Arc::ptr_eq(mixed.histograms().batch(), &first_batch), + "the histogram table was rebuilt" + ); + assert!( + matches!(field0[0].sample(0), SampleRef::Histogram(view) if view.count == 1.0), + "the histogram did not survive as a histogram" + ); + assert!( + matches!(field0[1].sample(0), SampleRef::Float(value) if value.to_bits() == 2f64.to_bits()), + "field 0 lost the other fragment's float" + ); + assert!( + matches!(field0[2].sample(0), SampleRef::Missing), + "field 0 filled a position only field 1 holds" + ); + + // Field 1: its value, the null field 0 fills, and the NaN, which is a value like any other. + let field1 = merged[0].fields.as_slice()[1].segments(); + assert_eq!(field1.len(), 3, "a float, one null run, and a NaN"); + assert!( + matches!(field1[0].sample(0), SampleRef::Float(value) if value.to_bits() == 1f64.to_bits()) + ); + assert!(matches!(field1[1].sample(0), SampleRef::Missing)); + assert!( + matches!(field1[2].sample(0), SampleRef::Float(value) if value.is_nan()), + "the NaN was dropped" + ); + // The NaN came out as a slice of the second fragment's buffer, one row in. + assert_eq!( + float_ptr(&field1[2]), + second_field1.wrapping_add(1), + "the NaN was copied instead of sliced" + ); + + // Two fragments holding one field at one position still collide, histograms included. + let at_zero = + || fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), None)]).0; + assert!( + merge_same_labelset(&schema, vec![at_zero(), at_zero()]).is_err(), + "two histograms of one field at one position merged" + ); +} + +/// A merge over many fragments of many segments keeps one row per value: a million-position grid +/// costs a span per run and a sample per value, and locating a row never rescans the segments +/// before it. +#[test] +fn merge_of_many_segments_keeps_one_row_per_value() { + const GRID: usize = 1_000_000; + const SEGMENTS: usize = 1_000; + let schema = grid_schema(1, GRID as u64); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + // A fragment of one value per segment, one chunk per value, the segments a thousand positions + // apart. + let fragment = |offset: usize| { + let mut chunks = Vec::with_capacity(SEGMENTS); + let mut spans = Vec::with_capacity(SEGMENTS); + for segment in 0..SEGMENTS { + let position = offset + segment * (GRID / SEGMENTS); + chunks.push(Samples::from_float(Float64Array::from(vec![ + position as f64, + ]))); + spans.push(GridSpan::new(position, 1)); + } + let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap(); + let fields = SeriesFields::one(Samples::try_from_chunks(chunks).unwrap()); + Series::try_new(&schema, metric_of(&labels), time, fields).unwrap() + }; + + let merged = merge_same_labelset(&schema, vec![fragment(0), fragment(1)]).unwrap(); + assert_eq!(merged.len(), 1); + let series = &merged[0]; + assert_eq!( + series.time.grid().unwrap().timestamps().len(), + GRID, + "the grid really holds a million positions" + ); + assert_eq!(series.time.len(), 2 * SEGMENTS, "one row per value"); + assert_eq!( + series.time.runs().count(), + SEGMENTS, + "two adjacent values per segment are one run, and the holes between are spans" + ); + assert_eq!(run_ranges(series)[0], (0, 2)); + let field = &series.fields.as_slice()[0]; + assert_eq!( + field.len(), + 2 * SEGMENTS, + "the field holds one sample per merged row" + ); + assert_eq!( + field.segments().len(), + 2 * SEGMENTS, + "one chunk per value: no hole was densified into the payload" + ); + assert!(field.segments().iter().all(|chunk| chunk.len() == 1)); + assert_eq!( + points_of(series).len(), + 2 * SEGMENTS, + "every value survived and no hole became one" + ); +} + +/// A label set whose fragments all closed without a value still yields one series: a runtime that +/// closes a label set needs one answer per set, and an empty grid series is the legal one. +#[test] +fn merge_of_empty_fragments_yields_one_empty_series() { + let schema = grid_schema(2, 4); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + let empty = || { + let time = + TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), Vec::new()).unwrap(); + let fields = SeriesFields::try_from_vec(vec![ + Samples::from_float(Float64Array::new_null(0)), + Samples::from_float(Float64Array::new_null(0)), + ]) + .unwrap(); + Series::try_new(&schema, metric_of(&labels), time, fields).unwrap() + }; + + let merged = merge_same_labelset(&schema, vec![empty(), empty()]).unwrap(); + assert_eq!(merged.len(), 1, "the label set vanished"); + assert_eq!(merged[0].metric, metric_of(&labels)); + assert_eq!(merged[0].time.len(), 0); + assert!( + merged[0].time.grid().is_some(), + "an empty series keeps its grid" + ); + assert!( + run_ranges(&merged[0]).is_empty(), + "an empty series has no run" + ); + assert_eq!(merged[0].fields.len(), 2); + for field in merged[0].fields.iter() { + assert!(field.is_empty(), "an empty fragment contributed a row"); + } +} + +/// A `Series` built as a struct literal can carry fields that do not line up with its axis; the +/// merge checks the alignment before it reads a row, so it reports such a fragment instead of +/// reading past a field or dropping the values the axis never reaches. +#[test] +fn merge_rejects_fragments_whose_fields_do_not_fill_their_axis() { + let schema = grid_schema(1, 8); + let grid = schema.eval_grid.clone().unwrap(); + let labels = Labels::from([("job".to_string(), "x".to_string())]); + // A well-formed fragment gives the malformed one a label set to merge into. + let partner = || series_of(&schema, &labels, &Points::from([(1, 7f64.to_bits())])).unwrap(); + // `(axis rows, field rows)`: a field shorter than its axis, one longer than it, and a value on + // an axis of no rows at all. The last two leave every axis row self-consistent, so only the + // merge's alignment check catches them. + for (axis_rows, field_rows) in [(2, 1), (1, 2), (0, 1)] { + let spans = if axis_rows == 0 { + Vec::new() + } else { + vec![GridSpan::new(1, axis_rows)] + }; + let time = TimeAxis::from_grid_spans(grid.clone(), spans).unwrap(); + let values = Float64Array::from( + (0..field_rows) + .map(|row| row as f64 + 1.0) + .collect::>(), + ); + let malformed = Series { + metric: metric_of(&labels), + time, + fields: SeriesFields::one(Samples::from_float(values)), + }; + let error = merge_same_labelset(&schema, vec![partner(), malformed]) + .expect_err("a fragment whose fields do not fill its axis merged"); + assert!( + error.to_string().contains("rows of its axis"), + "{axis_rows} axis rows with a {field_rows}-row field: {error}" + ); + } +} + // --------------------------------------------------------------------------------------------- // Acceptance: the builder's observable shape. // diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index ada6cbe323c..3aeb9b16470 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -35,12 +35,30 @@ //! half a query or panicking halfway through one. //! //! A node that rewrites labels — a window drops the metric name and the empty-valued labels, a map -//! drops the name — can turn two distinct series into one label set, and each of them still closes -//! on its own chunk. The node that did the rewriting is where the second one is refused, before the -//! node above evaluates it: a label set that has closed cannot be produced again, and a chunk that -//! holds a value where the same field already holds one cannot be merged without holding whole -//! series. A chunk that continues a label set where it ended, or that fills positions the set has -//! not occupied, is handed on. +//! drops the name — can turn two distinct input series into one output label set. That pair is +//! legal when the two hold values at disjoint positions, which is exactly what +//! [`crate::grid_series::merge_same_labelset`] merges: `is_last` closes the source series whose +//! data the chunk carries, not the label set it shares with another series, so a second series may +//! fill the positions the first one left empty. The node that rewrote the labels keeps which +//! positions each output label set already occupies; a second series that puts a value where the +//! same field already holds one is refused there — before a node above reads it — while a chunk +//! that continues a set where it ended, or fills positions the set has not occupied, is handed on. +//! +//! A label set reachable by more than one series needs one more guarantee: a window reads one +//! series to its `is_last` before the next one, so the per-series state of its evaluator ends +//! before a second series onto the same set arrives. The window immediately above such a rewriting +//! node therefore collects its whole input, merges each canonical label set once with +//! [`crate::grid_series::merge_same_labelset`], and only then evaluates it: every logical series +//! reaches its evaluator once and whole, and the pieces that would have been separate streams +//! become one. Such a window reports at the end of its input instead of as its input arrives. A +//! window directly over a source, and a map at the root, are not affected and keep streaming their +//! chunks on as they produce them. +//! +//! What leaves the tree is therefore a piece stream, not a series collection: a chunk's `is_last` +//! says the source series it carries ended. [`NativeExecutor::finish`] performs the merge for every +//! affected window inside the tree. A caller that needs one series per canonical label set from the +//! root itself — a downstream window outside this runtime, or a protocol that reports one series — +//! collects the root's chunks and merges them with the same helper. use std::collections::hash_map::Entry; use std::collections::{HashMap, VecDeque}; @@ -59,7 +77,7 @@ use datatypes::series::samples::{ use datatypes::series::time::{GridRange, TimeAxis}; use datatypes::series::{MetricName, SeriesOrdering}; -use crate::grid_series::{LabelSet, label_set}; +use crate::grid_series::{LabelSet, label_set, merge_same_labelset}; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; use crate::native::metrics::{NodeMetrics, NodePath}; @@ -91,7 +109,10 @@ impl NativeChunk { } } - /// Whether this chunk closes its series. + /// Whether this chunk closes the source series whose data it carries. + /// + /// A chunk never closes the label set it holds: two source series can share one output label + /// set when the positions they fill are disjoint, and each of them ends on its own chunk. fn is_last(&self) -> bool { match self { Self::Raw(chunk) => chunk.is_last, @@ -99,17 +120,6 @@ impl NativeChunk { } } - /// The identity of the series this chunk belongs to, when the chunk names it. - /// - /// A raw chunk in bound-label mode carries its identity in its key and no metric name, so there - /// is nothing to compare; an evaluated chunk always names the series it holds. - fn metric(&self) -> Option<&MetricName> { - match self { - Self::Raw(chunk) => chunk.metric.as_ref(), - Self::Evaluated(chunk) => Some(&chunk.series.metric), - } - } - /// An estimate of the bytes this chunk holds. /// /// It is what the chunk alone stands for, so a buffer or a histogram table two chunks share is @@ -144,6 +154,70 @@ fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { std::mem::size_of::().saturating_add(fields_bytes(&chunk.series.fields)) } +/// The bytes one evaluated series holds: its header, the axis that addresses it, the identity it +/// carries and the sample buffers behind its fields. +/// +/// It is the figure a fragment of an affected window is charged with as it arrives. The axis's runs +/// and the segments of its fields are counted in one pass over the series, so the estimate costs +/// the fragment rather than a walk over everything the node holds. A payload a fragment shares with +/// another — a histogram table behind two slices of it, the grid behind every axis — is counted +/// once per fragment: that over-count is accepted here rather than a deduplication that would have +/// to keep state across fragments. +fn series_bytes(series: &Series) -> usize { + let runs = series.time.runs().count(); + let segments: usize = series + .fields + .iter() + .map(|field| field.segments().len()) + .sum(); + std::mem::size_of::() + .saturating_add(std::mem::size_of::()) + .saturating_add(runs.saturating_mul(std::mem::size_of::<(usize, usize)>())) + .saturating_add( + segments.saturating_mul(std::mem::size_of::() + std::mem::size_of::()), + ) + .saturating_add(fields_bytes(&series.fields)) + .saturating_add(metric_bytes(&series.metric)) +} + +/// An estimate of the workspace [`crate::grid_series::merge_same_labelset`] needs for fragments +/// that hold `rows` rows between them. +/// +/// The helper sorts one `(position, member, row)` triple per fragment row and keeps the distinct +/// positions beside it, so the figure charges those vectors at their widest. Every field of every +/// fragment gets a reader, and every merged field is built as a vector of run descriptors -- one +/// slice of a fragment's segment or one run of missing rows -- before it becomes one field again, +/// so a row is charged the descriptors it can become in the worst case, several `Samples` headers +/// and their `Arc` conversions, rather than one. The output side keeps one series and one field +/// header per merged series, which is as many as there are fragments. +/// +/// The sample payload is not charged: a merged run is a slice of the fragment's own segment, so the +/// merge copies no values and the fragments are what hold them. A histogram table behind several +/// fragments is likewise left to the fragments' own estimates, which count it once per fragment. +fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize { + let sorted_rows = rows.saturating_mul( + std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::(), + ); + let readers = fragments.saturating_mul( + fields.saturating_mul(std::mem::size_of::() + 4 * std::mem::size_of::()), + ); + // What one merged field can hold while it is built: one descriptor per row at the very worst + // (alternating missing rows and values from different fragments), kept once as the run vector + // and once as the flattened field that is made from it. + let merged_field_per_row = + 2 * std::mem::size_of::() + 3 * std::mem::size_of::(); + let merged_fields = rows + .saturating_mul(fields) + .saturating_mul(merged_field_per_row); + let output = fragments.saturating_mul( + std::mem::size_of::() + fields.saturating_mul(std::mem::size_of::()), + ); + sorted_rows + .saturating_add(readers) + .saturating_add(merged_fields) + .saturating_add(output) +} + /// The bytes the fields of a chunk hold: the sample buffers of every segment, and the histogram /// tables those segments reference. fn fields_bytes(fields: &SeriesFields) -> usize { @@ -219,6 +293,51 @@ struct NodeSpec { input: Option, } +/// The input a window with a [`NodeRuntime::merge`] collects until its input ends. +/// +/// Such a window cannot evaluate the series under one canonical label set one after another: its +/// evaluator closes a series on the chunk carrying `is_last`, and the points a window across the +/// boundary needs are exactly the ones that closed series held. The fragments are therefore kept +/// whole, merged into one series per label set with +/// [`crate::grid_series::merge_same_labelset`], and only then evaluated. +struct MergeInput { + /// The schema the fragments are addressed on: their grid and their field count. + schema: Arc, + /// The series received so far, in the order they arrived. + fragments: Vec, + /// An estimate of the bytes the fragments and the merge that follows them stand for. + /// + /// A fragment is measured once as it arrives; the merge's workspace is added once, before the + /// helper runs, from the rows, segments and fields of the fragments as they were collected. + /// Neither figure walks the buffer again, and the space the fragments' payload shares is + /// counted once per fragment rather than deduplicated. + bytes: usize, +} + +impl MergeInput { + /// A buffer for the fragments of one window's input, which are addressed on `schema`. + fn new(schema: Arc) -> Self { + Self { + schema, + fragments: Vec::new(), + bytes: 0, + } + } + + /// The bytes of the fragments and of the workspace merging them needs. + /// + /// The workspace is what the helper allocates for the rows the fragments hold; the sample + /// payload is shared with them, so it is not counted twice here. + fn workspace_bytes(&self) -> usize { + let rows: usize = self + .fragments + .iter() + .map(|fragment| fragment.time.len()) + .sum(); + merge_workspace_bytes(rows, self.fragments.len(), self.schema.fields.len()) + } +} + /// What every node holds: its metric handles and the bytes it reserves. /// /// The reservation is the pool's, so a node that buffers input competes with every other operator @@ -301,7 +420,13 @@ impl Run { /// /// Occupancy is per field and per position, not per chunk range: a chunk reports the positions it /// decided, which include the ones holding no value, and series that share a decided range while -/// sharing no sample merge cleanly, as they do in [`crate::grid_series::merge_same_labelset`]. +/// sharing no sample merge cleanly, as they do in [`crate::grid_series::merge_same_labelset`]. A +/// chunk holding no value occupies nothing and changes nothing. +/// +/// A set is never retired: `is_last` closes the source series whose data the chunk carries, and a +/// later series may still fill the positions the closed one left empty. Every run handed out stays +/// charged until the node is released, which is what lets a later chunk be refused against the +/// positions an earlier series already occupied. /// /// The table is one node's own: a node knows what it has handed out itself and sees nothing of what /// the node below kept, so a label set costs its bytes again in every node that keeps a table, and @@ -316,8 +441,7 @@ struct Emitted { /// figure is read after every output; walking the table there would cost a pass over every entry /// recorded so far for each output. Folding one entry's change in as it happens keeps the read /// constant, and the update is the shape of the change itself: a vector's length before and - /// after [`absorb`], one vector per field a history gains, and one terminal pass over a closing - /// history's vector lengths. + /// after [`absorb`], and one vector per field a history gains. counts: Counts, } @@ -328,8 +452,7 @@ struct Counts { vectors: usize, /// The occupied runs in every vector. runs: usize, - /// The payload of every label set and of every owner: the bytes of their names and values with - /// one row per label. + /// The payload of every label set: the bytes of its names and values with one row per label. payload: usize, } @@ -338,31 +461,6 @@ struct Counts { struct History { /// The occupied runs of each field, in position order and disjoint. fields: Vec>, - /// The source series that filled this label set, when the chunk that did named it. - /// - /// A chunk holding no value is handed over to close a series, never to fill a label set, so it - /// closes this one only when it belongs to the series that filled it: a second series that - /// produced nothing here is a series this label set never saw, and closing on its `is_last` - /// would leave the series that did produce the values unable to finish. `None` is a set filled - /// by chunks that named no series, where there is nothing to compare a closing chunk against. - owner: Option, - /// Whether the series on this label set closed. A second series cannot close it again. - closed: bool, -} - -impl History { - /// Whether a chunk of `source` holding no value is the one that closes this label set. - /// - /// Only the series that filled it can: a series that produced nothing here is one this label - /// set never saw, so closing on its `is_last` would take the close away from the series that - /// did fill it. A chunk naming no series is compared with nothing and closes the set, which is - /// what every chunk did before the owner was kept. - fn closed_by(&self, source: Option<&MetricName>) -> bool { - match (self.owner.as_ref(), source) { - (Some(owner), Some(source)) => owner == source, - _ => true, - } - } } /// The bytes a label set holds: each label's name and value with the pair that refers to them. @@ -377,8 +475,7 @@ fn label_bytes(labels: &LabelSet) -> usize { /// to them. /// /// This is the convention [`label_bytes`] keeps: the payload of the shared strings and one row per -/// label. The `Option` a [`History`] keeps its owner in is not counted here, being part -/// of the header that entry's slot is charged for. +/// label. fn metric_bytes(metric: &MetricName) -> usize { metric.name().map_or(0, |name| name.len()) + std::mem::size_of_val(metric.tags()) @@ -392,23 +489,13 @@ fn metric_bytes(metric: &MetricName) -> usize { impl Emitted { /// Records what `chunk` occupies, rejecting it against what this node already handed out. /// - /// `source` is the identity of the input series `chunk` came from, when the chunk names one: a - /// label set is filled by the series that contributes its values, and it is that series whose - /// closing chunk closes it (see [`History::owner`]). - /// - /// A label set that has closed cannot be reached by a second series: the node would hand on two - /// chunks that its consumer cannot tell apart, and the merge the caller wants spans the first - /// series, whose state the evaluator above has already closed. Such a pair does merge in - /// Prometheus, so this is a limitation of the streaming evaluator rather than a collision; it is - /// refused instead of being answered wrongly (see [`closed_label_set`]). A chunk of a set still - /// open is refused only where it holds a value at a position that same field already holds one - /// at, which is the case no merge can resolve. - fn occupy( - &mut self, - path: &NodePath, - source: Option<&MetricName>, - chunk: &EvaluatedChunk, - ) -> Result<()> { + /// A second series onto a label set is legal when it holds its values where the first one held + /// none: the two merge into one series, which is what + /// [`crate::grid_series::merge_same_labelset`] does. What no merge resolves is two values of one + /// field at one position, so that is the only thing refused here. `is_last` is not consulted: it + /// closes the source series the chunk carries, not the label set, and a later series may still + /// fill the positions that one left empty. + fn occupy(&mut self, path: &NodePath, chunk: &EvaluatedChunk) -> Result<()> { let labels = label_set(&chunk.series.metric); let occupied: Vec> = chunk .series @@ -418,18 +505,7 @@ impl Emitted { .map(|(index, field)| occupied_runs(path, index, field, &chunk.series.time)) .collect::>()?; let empty = occupied.iter().all(Vec::is_empty); - let recorded = self.sets.get(&labels); - if let Some(history) = recorded { - if history.closed { - // A series that produced nothing under a closed label set contributes no sample, so - // there is nothing to report, nothing to merge and nothing to refuse. One that did - // produce values is the second series this set cannot take. - return if empty { - Ok(()) - } else { - Err(closed_label_set(path, &labels)) - }; - } + if let Some(history) = self.sets.get(&labels) { for (index, runs) in occupied.iter().enumerate() { let stored = history.fields.get(index).map_or(&[][..], Vec::as_slice); for run in runs { @@ -444,16 +520,10 @@ impl Emitted { } } } - // A chunk holding no value records nothing. Past a closed set the same series is the - // one that answered empty, and on an open set it is the close of the series that filled - // it -- but only of that series: a different one closes a label set it never wrote to, - // which would leave the series that did write to it unable to finish. - if empty && !(chunk.is_last && history.closed_by(source)) { - return Ok(()); - } - } else if empty { - // The first chunk onto a label set holds no value: a series that answered empty, with - // nothing to record, nothing to close and nothing to merge. + } + if empty { + // A chunk holding no value records nothing and closes nothing: a series that answered + // empty leaves every earlier series on this label set exactly where it was. return Ok(()); } let fields = chunk.series.fields.len(); @@ -464,19 +534,6 @@ impl Emitted { entry.insert(History::default()) } }; - // The series that contributes the values is the one that owns the label set, so a chunk of - // another one cannot close it later on. - if !empty - && let Some(source) = source - && history.owner.as_ref() != Some(source) - { - self.counts.payload = self - .counts - .payload - .saturating_sub(history.owner.as_ref().map_or(0, metric_bytes)) - .saturating_add(metric_bytes(source)); - history.owner = Some(source.clone()); - } if history.fields.len() < fields { self.counts.vectors += fields - history.fields.len(); history.fields.resize_with(fields, Vec::new); @@ -487,24 +544,16 @@ impl Emitted { absorb(stored, &runs); self.counts.runs = self.counts.runs - before + stored.len(); } - if chunk.is_last { - history.closed = true; - // No later chunk reads these runs: a closed label set refuses every series that would - // use them. Keeping them charges the pool for a series that has already been answered. - self.counts.runs -= history.fields.iter().map(Vec::len).sum::(); - self.counts.vectors -= history.fields.len(); - history.fields = Vec::new(); - } Ok(()) } /// An estimate of the bytes this table holds, which the node reserves for. /// /// It counts one label-set slot and one history header per entry, one vector per field of a - /// history, the runs in those vectors, and the payload of every label set and owner. Each of - /// those is a running total, so the figure is read in constant time however many series the node - /// has handed out; it leaves out the map's buckets, the slack of a vector's capacity and the - /// `Arc` headers of the strings it shares, so it is an approximation rather than a measurement. + /// history, the runs in those vectors, and the payload of every label set. Each of those is a + /// running total, so the figure is read in constant time however many series the node has + /// handed out; it leaves out the map's buckets, the slack of a vector's capacity and the `Arc` + /// headers of the strings it shares, so it is an approximation rather than a measurement. fn bytes(&self) -> usize { let slots = self.sets.len() * (std::mem::size_of::() + std::mem::size_of::()); @@ -708,8 +757,12 @@ struct MapRuntime { /// The per-node run-time state of a node. struct NodeRuntime { buffer: NodeBuffer, - /// Source chunks queued by the caller, for an input node, each with the estimate it was queued - /// with: what a chunk is worth is read once, as it enters, and given back as it leaves. + /// The chunks this node holds for its consumer, each with the estimate it was queued with. + /// + /// An input node's queue is filled by the caller, and a window's by the chunks it computed while + /// flushing its collected input; no node uses it for both. A chunk is measured once, as it + /// enters, and the figure it was queued with is given back as it leaves, so neither the queue + /// nor the handover walks it. queued: VecDeque<(NativeChunk, usize)>, /// A window node's evaluator, with its own input and output grid; `None` before it is built and /// once it is closed. @@ -719,6 +772,10 @@ struct NodeRuntime { /// What this node has already handed out under each output label set, for a node that rewrites /// labels: a window drops the metric name and the empty-valued labels, a map drops the name. emitted: Option, + /// The input a window collects until its input ends, for a window whose input can hold two + /// series under one label set; `None` for a window that evaluates its chunks as they arrive, + /// and once the flush that merges the collected input has taken it. + merge: Option, /// Whether the series the last chunk handed over belongs to is still open. /// /// Only an input node ever sets this, because its queue is the one the caller fills; the flag is @@ -814,10 +871,10 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); - // What it handed out is what the label sets of this node now hold. The identity is the - // input's: `map_chunk` has already rewritten the output's label set, and a series is - // the one that arrived. - self.track(path, Some(&chunk.series.metric), output)?; + // What it handed out is what the label sets of this node now hold: `map_chunk` has + // already rewritten the output's label set, so the label set of the output is the one + // two input series can share. + self.track(path, output)?; } // The chunk is gone and the label sets this node has handed out are what is left. let emitted = self.emitted_bytes(); @@ -826,14 +883,23 @@ impl NodeRuntime { } /// Feeds one chunk to this node's window. + /// + /// A window that collects its input keeps the whole series of every chunk it is handed and + /// evaluates nothing yet: the label sets of those fragments are only canonical once the input + /// has ended, and reading them as separate series would close the state of the one before in + /// the evaluator. Every other window evaluates what it is handed as it arrives, which is what + /// lets it answer before its input series ends. fn window(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { + if self.merge.is_some() { + let NativeChunk::Evaluated(chunk) = chunk else { + return Err(DataFusionError::Execution(format!( + "the window at {path} collects evaluated fragments, but it was handed raw \ + samples" + ))); + }; + return self.collect(path, chunk); + } let (positions, closing) = (chunk.positions(), chunk.is_last()); - // Which series this chunk came from, for the label-set table below. A window consumes one - // series to its `is_last` before the next, so the chunk that closes an output label set is - // the one of the series that produced its values, which is what lets the table accept a - // closing chunk of a series that wrote to it. A raw chunk in bound-label mode names no - // series, so there is nothing to pass on. - let source = chunk.metric(); // The chunk is held for as long as the evaluator consumes it. self.buffer.grow(chunk.bytes())?; let metrics = Arc::clone(&self.buffer.metrics); @@ -864,9 +930,7 @@ impl NodeRuntime { if let Some(output) = &output { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); - // What it handed out is what the label sets of this node now hold, and the series that - // filled one is the series its chunks came from. - self.track(path, source, output)?; + self.track(path, output)?; } // The chunk has been consumed: what this node still holds is what the evaluator kept of it // and the label sets it has already handed out. Both are charged whether or not this chunk @@ -883,22 +947,84 @@ impl NodeRuntime { Ok(output) } - /// Records what this node hands out under its output label set. + /// Keeps one fragment of this node's collected input, charged for as it arrives. /// - /// `source` is the identity of the input series the chunk came from, when there is one: a node - /// that rewrites labels is where two input series become indistinguishable, so this is where - /// the second one is refused, and it is also the only place that knows which series filled the - /// label set a chunk closes. A node above reads what this one hands over, and a window above - /// would evaluate the two as two series and report both. Checking at the root would be too late - /// for that — the answer would already have been computed. - fn track( + /// The fragment is measured once, here, and its estimate stands until the flush that merges it + /// is over: a later chunk adds its own estimate rather than walking the buffer again. What is + /// estimated is what the fragment keeps alive, so a sample payload two fragments share is + /// counted once per fragment; the merge itself copies no values, and its workspace is charged + /// separately before it runs. + fn collect( &mut self, path: &NodePath, - source: Option<&MetricName>, - output: &EvaluatedChunk, - ) -> Result<()> { + chunk: EvaluatedChunk, + ) -> Result> { + let Some(merge) = self.merge.as_mut() else { + return Err(DataFusionError::Execution(format!( + "the window at {path} holds no collected input" + ))); + }; + let EvaluatedChunk { series, is_last } = chunk; + let positions = series.time.len(); + let bytes = series_bytes(&series); + // The fragment is held from here on, so the pool admits it before this node keeps it: a + // rejected fragment leaves nothing behind. + self.buffer.grow(bytes)?; + merge.bytes = merge.bytes.saturating_add(bytes); + merge.fragments.push(series); + let metrics = Arc::clone(&self.buffer.metrics); + metrics.record_input(1, positions); + if is_last { + // The source series whose data this fragment carries ended, which is what `is_last` + // says; the label set it shares with another series is not closed by it. + metrics.record_completed_series(1); + } + // What this node holds is the fragments and the label sets it has already handed out; its + // evaluator has read none of them yet. + let retained = self + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = self.emitted_bytes(); + let pending = self.merge.as_ref().map_or(0, |merge| merge.bytes); + self.buffer + .resize(retained.saturating_add(emitted).saturating_add(pending))?; + Ok(None) + } + + /// Queues one output this node computed while flushing its collected input. + /// + /// The chunk waits for the pull that hands it up the tree, and its estimate is added as it is + /// queued and given back as it leaves, so the queue costs the sum of what it holds. + fn enqueue_output(&mut self, chunk: EvaluatedChunk) -> Result<()> { + let bytes = evaluated_bytes(&chunk); + self.buffer.grow(bytes)?; + self.queued + .push_back((NativeChunk::Evaluated(chunk), bytes)); + Ok(()) + } + + /// Hands over the next output this node computed while flushing, if there is one. + /// + /// This is not a source handover: [`Self::open_source_series`] and the input metrics follow the + /// chunks the caller queued, and a chunk this node produced itself is neither. + fn take_output(&mut self) -> Result> { + let Some((chunk, bytes)) = self.queued.pop_front() else { + return Ok(None); + }; + self.buffer.shrink(bytes)?; + Ok(Some(chunk)) + } + + /// Records what this node hands out under its output label set. + /// + /// A node that rewrites labels is where two input series become indistinguishable, so this is + /// where a second one is refused: a node above reads what this one hands over, and a window + /// above would evaluate the two as two series and report both. Checking at the root would be + /// too late for that — the answer would already have been computed. + fn track(&mut self, path: &NodePath, output: &EvaluatedChunk) -> Result<()> { match self.emitted.as_mut() { - Some(emitted) => emitted.occupy(path, source, output), + Some(emitted) => emitted.occupy(path, output), // A node that keeps its input's labels cannot make two series one. None => Ok(()), } @@ -916,9 +1042,11 @@ impl NodeRuntime { // The window goes first: dropping the evaluator is what gives back the memory its // reservation was taken for. Returning the reservation while the evaluator still held the // samples would let the pool admit memory the process has not released, for as long as the - // caller keeps the stopped executor alive. The label sets this node handed out go with it. + // caller keeps the stopped executor alive. The label sets this node handed out and the + // fragments it collected go with it. self.window = None; self.emitted = None; + self.merge = None; // A node that holds no chunk holds no series either, so nothing it handed over is still // open for it: the flag is what closing the execution reads, and it must not survive the // state that could have kept a series alive. @@ -968,6 +1096,9 @@ impl NativeExecutionState { let mut nodes: Vec = Vec::new(); let mut paths: Vec = Vec::new(); let mut runtimes: Vec = Vec::new(); + // The bound expression of each node, in the same order: the pass below reads the node it + // configures from here, so nothing about an operation is copied onto the node's spec. + let mut exprs: Vec<&NativeExpr> = Vec::new(); let mut source: Option<(usize, Arc)> = None; let mut node = tree.root(); let mut path = NodePath::root(); @@ -1015,6 +1146,7 @@ impl NativeExecutionState { window: None, map: None, emitted: None, + merge: None, open_source_series: false, }; match &node.expr { @@ -1066,6 +1198,7 @@ impl NativeExecutionState { tag, input: child.map(|_| index + 1), }); + exprs.push(&node.expr); paths.push(path.clone()); runtimes.push(runtime); let Some(child) = child else { @@ -1075,6 +1208,66 @@ impl NativeExecutionState { path = path.input(); } + // One reverse pass sets where a merge has to happen, from the input upwards: the pass above + // walked the root first, so a node's input is the node after it and has been decided by the + // time the node itself is. + // + // A source is a stream of series, each with its own label set, so its output needs no merge: + // that is what keeps `Input -> Window` streaming and reporting as its input arrives. A map + // drops the metric name, so its output can hold two input series under one label set, and + // every node above it needs the merge. A window collects its input and merges it when its + // input can hold two series under one label set: reading them as series one after another + // would end the first in the evaluator before the second arrives, and a window across the + // boundary needs both. + // + // A window's own output needs the same when it rewrites labels -- `rate` drops the name, so + // two input series can become one label set -- or when it did not merge its input: + // `last_over_time` keeps the name, but a tag holding an empty value and an absent tag are + // two input series and one canonical label set, so the pair only becomes one series if it + // was merged before the window read it. + // + // The flags this needs are the pass's own: one per node, filled from the input upwards, and + // they and the expressions go when the pass ends. A node's spec therefore stays what the + // tree said, and nothing about an operation is kept once the state is built. + { + let mut holds_shared: Vec = vec![false; nodes.len()]; + for (index, expr) in exprs.into_iter().enumerate().rev() { + let input_holds_shared = + nodes[index].input.is_some_and(|child| holds_shared[child]); + match nodes[index].tag { + NodeTag::Input => {} + NodeTag::Map => holds_shared[index] = true, + NodeTag::Window => { + let (drops_metric_name, input_schema) = match expr { + NativeExpr::Window { input, op } => ( + op.function.drops_metric_name(), + input.output.samples().cloned(), + ), + _ => { + return Err(DataFusionError::Execution(format!( + "the node at {} is a window without a bound window operation", + paths[index] + ))); + } + }; + if input_holds_shared { + let schema = input_schema.ok_or_else(|| { + DataFusionError::Execution(format!( + "the window at {} merges its input, but its input produces no \ + samples", + paths[index] + )) + })?; + runtimes[index].merge = Some(MergeInput::new(schema)); + } + // A window's own output can hold two series under one label set when it drops + // the name, or when it did not merge its input and so never joined the two. + holds_shared[index] = drops_metric_name || !input_holds_shared; + } + } + } + } + // The runtime's output is an evaluated chunk. Raw samples have no grid, and a scalar or // aggregate state is not a query value, so neither can be the tree's answer. match tree.root().output.samples() { @@ -1146,6 +1339,19 @@ impl NativeExecutionState { .count() } + /// The input that ended before its last chunk, if there is one. + /// + /// It is read before anything is merged: a window that collects its input closes every series + /// it merges with a synthetic `is_last`, so a series the caller never ended would be + /// indistinguishable from one that ended afterwards. + fn truncated(&self) -> Option { + self.paths + .iter() + .zip(self.runtimes.iter()) + .find(|(_, runtime)| runtime.open_source_series) + .map(|(path, _)| truncated_input(path)) + } + /// Closes every node, reporting an input that ended mid-series. /// /// A drain finds nothing left to emit: a window reports its results on the chunk that closes @@ -1177,6 +1383,11 @@ impl NativeExecutionState { /// /// The driver owns the state and nothing else: every decision a node makes was bound before the /// tree existed, so a pull only reads the position and runs the bound operation. +/// +/// A window directly over a source evaluates its chunks as they arrive, and a map at the root hands +/// its chunks on as it produces them: both stream. A window whose input can hold two series under +/// one canonical label set collects that input instead, merges each set once and evaluates it, so +/// it reports at [`Self::finish`] rather than as its input arrives. pub struct NativeExecutor { state: NativeExecutionState, phase: Phase, @@ -1220,7 +1431,15 @@ impl NativeExecutor { /// The next chunk the root produces, or `None` when nothing has settled yet. /// /// Every node takes whole chunks from its input, so a caller that keeps pushing and pulling - /// materialises nothing beyond the chunk in hand. + /// materialises nothing beyond the chunk in hand -- except below a window that collects its + /// input, which holds that input until [`Self::finish`]. + /// + /// A chunk's `is_last` says the series whose data it carries ended. It does not say its label + /// set is finished: two source series whose labels were rewritten into one set are two pieces + /// of one logical series, and the merge that makes them one is + /// [`crate::grid_series::merge_same_labelset`]'s. Every window that collects its input performs + /// that merge itself, so a root below such a window hands over one series per label set; a map + /// at the root hands over pieces, and a caller that needs one series per label set merges them. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; // The root is the node the state was built from, which the pass puts first. @@ -1240,12 +1459,21 @@ impl NativeExecutor { result } - /// Ends the input: drains what has settled, closes every node and releases every reservation. + /// Ends the input: drains what has settled, merges what the windows that collect their input + /// hold, closes every node and releases every reservation. /// /// Every series must have closed by now, in every tree: a window's evaluator reports the series /// it is still holding, and a tree with no window has its input node report one it handed over /// without the chunk that ends it. An input that ends mid-series is an error here rather than a - /// series the caller never sees close. + /// series the caller never sees close, and it is refused before any collected input is merged: + /// merging closes what it merges. + /// + /// The merge comes next, deepest window first, and what it hands up is drained as it is + /// produced. What the root hands over is therefore a piece stream: a chunk's `is_last` says the + /// source series it carries ended, and two of them can share one label set. A caller that needs + /// one series per label set from the root merges them with + /// [`crate::grid_series::merge_same_labelset`] as well, exactly as this runtime merges the input + /// of the windows it collects for. pub fn finish(&mut self) -> Result> { let mut drained = Vec::new(); loop { @@ -1255,6 +1483,16 @@ impl NativeExecutor { Err(error) => return Err(error), } } + // A source series that never ended is refused before anything is merged: the close a merge + // synthesises would make it look like one that did. + if let Some(error) = self.state.truncated() { + self.stop(&error); + return Err(error); + } + if let Err(error) = self.flush_merges(&mut drained) { + self.stop(&error); + return Err(error); + } match self.state.close() { Ok(()) => { self.phase = Phase::Finished; @@ -1267,6 +1505,117 @@ impl NativeExecutor { } } + /// Merges the collected input of every window that collects it, and drains the root after each + /// merged series. + /// + /// Deeper windows go first: a window above one of them collects the chunks the one below hands + /// up, so flushing the shallow one first would merge an input it has not received yet. The + /// queue of a flushed node is emptied by the root drain that follows each of its merged series, + /// so a chunk it produced never stands beside the fragments it was computed from. + fn flush_merges(&mut self, drained: &mut Vec) -> Result<()> { + for index in (0..self.state.runtimes.len()).rev() { + // A window that collects its input is the one node holding a [`MergeInput`], and the + // flush takes it: the same node is not visited twice. + if self.state.runtimes[index].merge.is_none() { + continue; + } + self.flush_merge(index, drained)?; + } + Ok(()) + } + + /// Merges the collected input of the node at `index` and evaluates it, one merged series at a + /// time. + /// + /// Each merged series is a whole series: it is handed to the evaluator as one closing series, so + /// the window reports on it once, and its chunk is queued and drained up the tree before the + /// next one is evaluated. That is what keeps the reservation honest: the fragments and the + /// merge's workspace stay charged while the flush runs, and the queue of a node never holds an + /// earlier series beside the fragments of a later one. + fn flush_merge(&mut self, index: usize, drained: &mut Vec) -> Result<()> { + let path = self.state.paths[index].clone(); + let Some(merge) = self.state.runtimes[index].merge.take() else { + return Ok(()); + }; + if merge.fragments.is_empty() { + // Nothing arrived, so there is nothing to merge and nothing to answer: the window's + // evaluator never read a series and the charge goes back. + return self.settle_merge(index); + } + // The workspace the merge allocates is charged before it runs, from the rows, segments and + // fields of the fragments as they were collected. + let workspace = merge.workspace_bytes(); + let held = merge.bytes.saturating_add(workspace); + let schema = Arc::clone(&merge.schema); + self.state.runtimes[index].buffer.grow(workspace)?; + // The fragments' charge stands for the merged series too -- a merged run is a slice of a + // fragment's own segment, so no value is copied -- and the workspace stays charged until + // the flush is over. + let merged = merge_same_labelset(&schema, merge.fragments)?; + for series in merged { + let output = { + let runtime = &mut self.state.runtimes[index]; + let Some(evaluator) = runtime.window.as_mut() else { + return Err(closed(&path)); + }; + let metrics = Arc::clone(&runtime.buffer.metrics); + let _timer = metrics.timer(); + evaluator.push_series(&series, true)? + }; + if let Some(output) = output { + let runtime = &mut self.state.runtimes[index]; + runtime + .buffer + .metrics + .record_grid_points(output.series.time.len()); + runtime + .buffer + .metrics + .record_output(1, valid_values(&output)); + runtime.track(&path, &output)?; + let retained = runtime + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = runtime.emitted_bytes(); + runtime + .buffer + .resize(retained.saturating_add(emitted).saturating_add(held))?; + runtime.enqueue_output(output)?; + } + self.drain_root(drained)?; + } + self.settle_merge(index) + } + + /// Sets the reservation of the node at `index` to what it holds once its flush is over. + fn settle_merge(&mut self, index: usize) -> Result<()> { + let runtime = &mut self.state.runtimes[index]; + let retained = runtime + .window + .as_ref() + .map_or(0, RangeEvaluator::retained_bytes); + let emitted = runtime.emitted_bytes(); + runtime.buffer.resize(retained.saturating_add(emitted)) + } + + /// Hands the root's outputs to `drained` until the tree has nothing settled. + fn drain_root(&mut self, drained: &mut Vec) -> Result<()> { + loop { + match self.pull(0)? { + Some(NativeChunk::Evaluated(chunk)) => drained.push(chunk), + Some(NativeChunk::Raw(_)) => { + return Err(DataFusionError::Execution( + "the native runtime produces evaluated chunks, but its root produced raw \ + samples" + .to_string(), + )); + } + None => return Ok(()), + } + } + } + /// The next chunk of the node at `index`. fn pull(&mut self, index: usize) -> Result> { let tag = self.state.nodes[index].tag; @@ -1287,6 +1636,12 @@ impl NativeExecutor { } } NodeTag::Window => { + // A chunk this window computed while flushing its collected input leaves first: it + // was produced before the window was drained, and the pull that hands it up is the + // one that empties the queue. + if let Some(chunk) = self.state.runtimes[index].take_output()? { + return Ok(Some(chunk)); + } let child = input.ok_or_else(|| missing_input(tag))?; // A window reports on the chunk that closes a series, so a chunk that decides // nothing yields nothing and the window asks its input again. @@ -1463,26 +1818,6 @@ fn unsupported_ordering(ordering: SeriesOrdering, input: &NodePath) -> DataFusio )) } -/// The rejection of a second series onto a label set the node already closed. -/// -/// This is a limitation of this streaming evaluator, not a PromQL collision. Two series whose -/// distinct label sets were rewritten into one do merge when they hold values in different places: -/// [`crate::grid_series::merge_same_labelset`] accepts exactly that, rejecting only two values of -/// one field at one position. What this runtime cannot do is merge across a series that has already -/// closed, because the evaluator closes its per-series state on the chunk carrying `is_last`: -/// nothing is left to merge the second series into, and the node hands chunks on as it produces -/// them, so it cannot hold the first series back until it knows whether a second one follows. -/// -/// The case is therefore refused rather than answered wrongly: reporting the two as one series, or -/// the first series twice, would both be a claim this layer cannot stand behind. -fn closed_label_set(path: &NodePath, labels: &LabelSet) -> DataFusionError { - DataFusionError::Execution(format!( - "the node at {path} already closed the label set {labels:?}, and a second input series \ - produces it: answering would report one series twice, and merging the two would need \ - whole series" - )) -} - /// The rejection of a chunk holding a value where the same field already holds one. /// /// No merge resolves this one: at `position`, field `field` of the label set `labels` would carry @@ -1497,7 +1832,7 @@ fn occupied_position( DataFusionError::Execution(format!( "the node at {path} produces two series under the label set {labels:?} that both hold a \ value of field {field} at position {position}: one occupies {previous:?} and another \ - {run:?}. Merging them would need whole series, which this layer does not hold", + {run:?}, and no merge resolves two values of one field at one position", position = run.start.max(previous.start), )) } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index c424ebda404..925b9cffcec 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -35,9 +35,10 @@ use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, NodeRuntime, - absorb_rebuilds, map_chunk, raw_bytes, + absorb_rebuilds, evaluated_bytes, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; +use crate::grid_series::merge_same_labelset; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ @@ -356,6 +357,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { window: None, map: None, emitted: None, + merge: None, open_source_series: false, } } @@ -905,9 +907,10 @@ fn an_unimplemented_node_is_reported_not_panicked() { /// Each node reports its own chunks, grid points and closed series, at its own position. /// /// The two windows decide different traffic — the inner one four grid points of its own grid, the -/// outer one two of its own — so a single total for the tree cannot produce both numbers. They take -/// and hand over the same number of chunks, which is what streaming means here: a node passes on one -/// chunk per chunk it took in, instead of holding its input until a whole series is available. +/// outer one two of its own — so a single total for the tree cannot produce both numbers. The inner +/// window reads the source as it arrives and hands over one chunk per chunk it took in; the outer +/// one collects those chunks, because the inner one keeps the metric name and its output can hold +/// two source series under one label set, and reports the one merged series its input ended with. #[test] fn each_node_records_its_own_metrics() { let inner_grid = grid(0, 60_000, 4); @@ -939,26 +942,23 @@ fn each_node_records_its_own_metrics() { .push_raw(raw_chunk(&schema, &[180_000], &[4.0], true)) .unwrap(); let out = run(&mut execution); - // The outer window reports each point as the inner one settles it: one chunk per inner chunk, - // and an empty chunk that closes the series. - assert_eq!( - addressed(&out), - vec![(0, vec![Some(1.0)]), (1, vec![Some(3.0)]), (2, Vec::new()),] - ); + // The outer window reports the two points of its grid once its input ended, in the one chunk of + // the series it merged from the inner window's pieces. + assert_eq!(addressed(&out), vec![(0, vec![Some(1.0), Some(3.0)])]); assert!(out.last().unwrap().is_last); let outer = NodePath::root(); let inner = outer.input(); let source = inner.input(); - // Three source chunks reach the inner window, and the chunks it hands over reach the outer one - // one for one, because neither window buffers. + // Three source chunks reach the inner window, which hands one chunk on per chunk it took in. + // The outer window takes those three pieces in and reports the one series they merge into. assert_eq!(count(&set, &source, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &source, NodeMetric::OUTPUT_BATCHES), 3); assert_eq!(count(&set, &inner, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &outer, NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&set, &inner, NodeMetric::OUTPUT_BATCHES), 3); - assert_eq!(count(&set, &outer, NodeMetric::OUTPUT_BATCHES), 3); + assert_eq!(count(&set, &outer, NodeMetric::OUTPUT_BATCHES), 1); // The grid points each window decided, which is its own output range: four on the inner grid // and two on the outer one, which is the figure that tells the two nodes apart. assert_eq!(count(&set, &inner, NodeMetric::EVALUATED_GRID_POINTS), 4); @@ -1098,13 +1098,110 @@ fn a_pool_that_cannot_admit_a_chunk_releases_what_it_held() { ); } -/// A map that drops the metric name cannot hand two series on under one label set. +/// Two series that a map turns into one label set are merged before the window above reads them. /// -/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own series, -/// and `abs` drops the name, so both become `{job="x"}`. A window above the map reads chunks as -/// they arrive, so it would take them for two series and answer once per series; the only answer -/// the data has is the merged series, which this layer does not hold. The map refuses the second -/// one before the window above evaluates it. +/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own source +/// series, and `abs` drops the name, so both become `{job="x"}`. The two hold their values at +/// different positions, so they are one series with a hole each and the answer is the window over +/// the merged series: `sum_over_time` sees 1 and 3 and answers 4, `count_over_time` answers 2. A +/// window that read the two as two series would answer twice, once per source series, and close +/// twice. +/// +/// The window above the map is the node that merges: its input can hold two series under one label +/// set, so it collects the whole input, merges each label set once with +/// [`crate::grid_series::merge_same_labelset`], and only then evaluates. Nothing comes out of it +/// while the pieces arrive, which is the price of merging; what comes out is one series. +#[test] +fn two_series_onto_one_label_set_after_a_map_are_merged_into_one_series() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + // One map and two maps: the label set is rewritten at the first one either way, and the second + // only rewrites it again, so both shapes are one affected window over one rewritten set. + let shapes = |function: RangeFunction| { + [ + ( + "a map", + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + function, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(), + ), + ( + "two maps", + NativeTree::try_new(window_with( + map( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + vec![MathOp::Abs], + ), + function, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(), + ), + ] + }; + + for (function, expected) in [ + // The two values at inner positions 0 and 1 both fall in the one window of the outer grid. + (RangeFunction::SumOverTime, 4.0), + (RangeFunction::CountOverTime, 2.0), + ] { + for (shape, tree) in shapes(function) { + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + // Each source series is closed properly, and each holds its value where the other holds + // none, so the pair is one logical series and one answer. + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(1.0), None], + true, + )) + .unwrap(); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 0, + vec![None, Some(3.0)], + true, + )) + .unwrap(); + // Nothing settles while the pieces arrive: the merged series is what the window evaluates, + // and it does not exist before the input ends. + assert!( + execution.next_chunk().unwrap().is_none(), + "{shape} with {function:?} reported a piece it had not merged yet" + ); + let out = execution.finish().expect("the merged series evaluates"); + assert_eq!( + decided(&out), + vec![(0, Some(expected))], + "{shape} with {function:?} did not answer over the merged series" + ); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "{shape} with {function:?} closed the one merged series more than once" + ); + } + } +} + +/// Two closed series that hold a value at the same position are still refused under one label set. +/// +/// The pair below maps into one label set and both hold a value at position 0 of the field, which +/// no merge resolves and Prometheus rejects for two series whose label sets became equal. The +/// refusal is the map's own, before the window above evaluates anything, and it names the position +/// rather than a closed label set: a closed source series is not a closed label set. #[test] fn two_series_onto_one_label_set_after_a_map_are_rejected() { let inner_grid = grid(0, 60_000, 2); @@ -1121,7 +1218,6 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { }; let schema = evaluated_schema(Arc::clone(&inner_grid)); - // The first series closes, so its window answer comes out on its own. let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); execution .push_evaluated(evaluated_chunk_of( @@ -1132,28 +1228,24 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { true, )) .unwrap(); - let first = execution - .next_chunk() - .unwrap() - .expect("the first series settles the outer point"); - assert_eq!(sample_values(&first), vec![Some(1.0)]); - assert!(first.is_last); - - // The second one maps onto the label set the first one closed. Answering would produce a second - // chunk with the same labels at the same point. + // The first series closed, and the window above collects it rather than reporting it. + assert!( + execution.next_chunk().unwrap().is_none(), + "the window above the map reported a piece before its input ended" + ); execution .push_evaluated(evaluated_chunk_of( &schema, named_metric("b", "x"), 0, - vec![None, Some(3.0)], + vec![Some(3.0), Some(4.0)], true, )) .unwrap(); let error = match execution.next_chunk() { - Ok(None) => panic!("the second series settled nothing at all"), + Ok(None) => panic!("the second series was accepted at a position the first one holds"), Ok(Some(chunk)) => panic!( - "the map handed a second series on at the label set the first one closed: {:?}", + "two values at one position were handed on: {:?}", decided(&[chunk]) ), Err(error) => error, @@ -1164,27 +1256,301 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { "the rejection does not name the label set: {message}" ); assert!( - message.contains("closed"), - "the rejection does not say the label set was already closed: {message}" + message.contains("position 0"), + "the rejection does not name the shared position: {message}" + ); +} + +/// An empty tag and an absent one are two source series and one canonical label set. +/// +/// `requests{host="web-1", zone=""}` and `requests{host="web-1"}` are distinct series to a scan: an +/// empty tag value is a present label, an absent one is not. `last_over_time` keeps the metric name +/// and every tag, so the inner window hands both on as two pieces, each closing its own source +/// series, and the two pieces carry different metrics. The outer window is the node that merges +/// them: a consumer compares label sets without the empty value, so the two are one series there. +/// Merging first is what makes the outer `sum_over_time` answer 4 at the second point -- the two +/// pieces hold 1 at the first point and 3 at the second -- where evaluating each piece on its own +/// would answer 3. +#[test] +fn an_empty_tag_and_an_absent_one_are_one_label_set_to_the_window_above() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(0, 60_000, 2); + let inner = || { + // A one-millisecond window on a 60 s grid, so every point reads only the sample at its own + // timestamp and each source series decides one point. + window_with( + input(), + RangeFunction::LastOverTime, + 1, + None, + Arc::clone(&inner_grid), + ) + }; + let chain = || { + window_with( + inner(), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + ) + }; + let schema = raw_schema(); + let push_both = |execution: &mut NativeExecutor| { + execution + .push_raw(raw_chunk_of( + &schema, + b"series-a", + host_metric(Some("")), + &[0], + &[1.0], + true, + )) + .unwrap(); + execution + .push_raw(raw_chunk_of( + &schema, + b"series-b", + host_metric(None), + &[60_000], + &[3.0], + true, + )) + .unwrap(); + }; + + // The inner window alone hands both series on, and they are two series: the empty tag survives + // `last_over_time`, which keeps the name and every tag. + let inner_tree = NativeTree::try_new(inner()).unwrap(); + let mut inner_execution = executor(&inner_tree, pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut inner_execution); + let pieces = run(&mut inner_execution); + assert_eq!( + pieces.len(), + 2, + "the inner window did not hand both series on" + ); + assert_ne!( + pieces[0].series.metric, pieces[1].series.metric, + "the two source series were not two series to `last_over_time`" ); - // What the rejection protects: one series carrying both samples averages to 2 at that point, - // which is the answer neither of the two separate series can produce. - let mut merged = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); - merged - .push_evaluated(evaluated_chunk_of( - &schema, - named_metric("c", "x"), - 0, - vec![Some(1.0), Some(3.0)], - true, - )) - .unwrap(); - let answer = merged + // The chain merges them before the outer window reads them. + let tree = NativeTree::try_new(chain()).unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut execution); + let out = run(&mut execution); + assert_eq!( + decided(&out), + vec![(0, Some(1.0)), (1, Some(4.0))], + "the outer window did not answer over the merged label set" + ); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "the merged label set closed more than once" + ); +} + +/// A window that collects its whole input gives every byte back when the execution closes. +/// +/// The fragments it holds, the workspace it merges them with and the chunks it queued while +/// flushing are all charged while they live, so the pool never admits memory the node still owns. +/// The close releases all of them, and the figures read zero while the executor is still alive. +#[test] +fn a_window_that_merges_its_input_releases_what_it_collected() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let set = ExecutionPlanMetricsSet::new(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + for (name, values) in [("a", vec![Some(1.0), None]), ("b", vec![None, Some(3.0)])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + // Pulling takes both fragments out of the queue and into the window, which charges them. + assert!( + execution.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let held = execution.state().reserved_bytes(); + let window_held = execution.state().runtimes[0].buffer.reservation.size(); + assert!(held > 0, "the collected input is not charged for"); + assert_eq!( + held, + pool.reserved(), + "the state and the pool disagree on what the collected input holds" + ); + + let out = execution.finish().expect("the merged series evaluates"); + assert_eq!(decided(&out), vec![(0, Some(4.0))]); + // The fragments, the workspace, the queue and the evaluator are all gone. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().nodes_holding_windows(), 0); + let current = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); + assert_eq!(gauge(&set, ¤t), 0); + let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); + assert!( + gauge(&set, &peak) >= window_held, + "the peak does not cover the input the window collected" + ); +} + +/// A pool that cannot admit what a collecting chain holds fails the execution and gives everything +/// back. +/// +/// The window collects its whole input, so the fragment it keeps costs more than the chunk it was +/// made from: the pool below holds room for the chunk and no more, so one of the charges the chain +/// makes fails. Whichever it is, the failure hands every reservation back while the executor is +/// still alive, and the evaluators and the collected fragments go with it. +#[test] +fn a_pool_that_cannot_admit_a_collected_fragment_releases_what_it_held() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let chunk = evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(1.0), None], + true, + ); + // Room for the chunk the source queue holds, which is what the pool admits first, and nothing + // for the label sets the map records or the fragment the window collects. + let pool = bounded_pool(evaluated_bytes(&chunk) + 1); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(chunk) + .expect("the source queue holds the chunk"); + + let error = execution .next_chunk() + .expect_err("the chain was admitted by a pool that cannot hold what it makes of the chunk"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples" + ); +} + +/// A merge whose workspace the pool cannot admit stops the execution and gives everything back. +/// +/// The fragments are admitted one by one as they arrive, so their charge is not what fails here: +/// what fails is the workspace the merge needs, taken in `finish` before the helper runs. The first +/// run measures what the collected input holds where the pool admits it; the second is given that +/// much and a little over -- enough for every fragment, not for the workspace, which charges at +/// least one `(position, member, row)` triple and one position per row. The failure releases the +/// fragments, the evaluators and the queues while the executor is still alive. +#[test] +fn a_pool_that_cannot_admit_the_merge_workspace_releases_what_it_held() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = || { + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) .unwrap() - .expect("the merged series settles the outer point"); - assert_eq!(sample_values(&answer), vec![Some(2.0)]); + }; + let schema = evaluated_schema(Arc::clone(&inner_grid)); + // Two closed source series, each holding its value where the other holds none, so the fragments + // do merge and the merge is what needs the workspace. + let push_both = |execution: &mut NativeExecutor| { + for (name, values) in [("a", vec![Some(-1.0), None]), ("b", vec![None, Some(-3.0)])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + }; + + // What the chain holds once its input is collected, measured where the pool admits it. + let mut reference = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + push_both(&mut reference); + assert!( + reference.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let measured = reference.state().reserved_bytes(); + assert!(measured > 0, "the collected input is not charged for"); + drop(reference); + + // Room for exactly what the collected input holds, and not for the merge's workspace. + let pool = bounded_pool(measured + 64); + let mut execution = executor(&tree(), Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + push_both(&mut execution); + assert!( + execution.next_chunk().unwrap().is_none(), + "the collecting window reported a piece" + ); + let collected = execution.state().reserved_bytes(); + assert_eq!( + collected, measured, + "the collected input was charged differently the second time, so the pool is not sized for it" + ); + assert_eq!(collected, pool.reserved()); + + let error = execution + .finish() + .expect_err("the merge ran without its workspace admitted"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + // Everything the chain held went back while the executor is alive: the fragments, the + // evaluator and both queues. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples" + ); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); } /// A window that drops empty-valued labels cannot hand two series on under one label set either. @@ -1195,6 +1561,12 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { /// grid out twice under the same labels and the same timestamps. No map is involved, so the /// rejection has to be the node's own — a check at the root would be too late, because the window /// above would already have evaluated the two as two series. +/// +/// The two cover the same positions of the same field, which is the collision no merge resolves: +/// the refusal names the position, not a closed label set, because closing a source series says +/// nothing about the label set it shared with another one. `rate` needs two samples, so neither +/// series decides position 0 -- it holds the single sample at its own timestamp -- and both decide +/// positions 1 to 4. The first position both occupy is therefore 1. #[test] fn two_series_onto_one_label_set_after_a_window_are_rejected() { let out_grid = grid(0, 60_000, 5); @@ -1224,7 +1596,17 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { .next_chunk() .unwrap() .expect("the first series settles the grid"); - assert!(!first.series.time.is_empty()); + // The decided positions of the first series, which are the ones the second one has to share. + assert_eq!( + first.series.time.runs().count(), + 1, + "the first series decided more than one run" + ); + assert_eq!( + first.series.time.first_position(), + Some(1), + "`rate` decided a position the single sample at 0 cannot settle" + ); assert!(first.is_last); // The second series is a different one to the scan and the same one to `rate`. @@ -1249,7 +1631,10 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { let message = error.to_string(); assert!(message.contains("host"), "{message}"); assert!(message.contains("web-1"), "{message}"); - assert!(message.contains("closed"), "{message}"); + assert!( + message.contains("position 1"), + "the rejection does not name the first position both series hold: {message}" + ); // Two series carrying different hosts stay distinct, which is what a rate over a label that // survives the rewrite looks like. @@ -1287,9 +1672,9 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { /// A chunk that holds a value where the same field already holds one is rejected. /// -/// Neither piece closes its series, so this is not a closed label set: the refusal is about the -/// positions themselves. `v0` would carry two values at position 0 under one label set, which no -/// merge can resolve, so the node refuses rather than picking one. +/// Neither piece closes its series, and neither needs to: the refusal is about the positions +/// themselves. `v0` would carry two values at position 0 under one label set, which no merge can +/// resolve, so the node refuses rather than picking one. #[test] fn two_series_holding_a_value_at_one_position_are_rejected() { let map_grid = grid(0, 60_000, 2); @@ -1336,18 +1721,16 @@ fn two_series_holding_a_value_at_one_position_are_rejected() { assert!(message.contains("position 0"), "{message}"); } -/// Two closed series that hold no position of the same field in common still cannot be handed on: -/// merging across a closed series is not implemented by this streaming evaluator, so the pair is -/// refused rather than answered wrongly. +/// Two closed series under one label set are two pieces of one logical series. /// -/// Neither piece holds a value where the other does — each has a missing value where the other holds -/// one — so the two do merge in Prometheus, and [`crate::grid_series::merge_same_labelset`] accepts -/// exactly this. What refuses it is the label set having closed on the piece carrying `is_last`: the -/// evaluator above has already closed its per-series state for it, so the node cannot hold the first -/// series back until it knows whether a second one follows. The refusal has to say so; a test that -/// passed both pieces as open chunks would be proving a merge the runtime never performs. +/// `a{job="x"}` and `b{job="x"}` are two series to the input and one label set to `abs`, which drops +/// the name. Each holds a value where the other holds none, and each says it is the last chunk of +/// its own source series — which is what `is_last` means here: the source series ended, not the +/// label set. The map hands both pieces on, and merging the two pieces with +/// [`crate::grid_series::merge_same_labelset`] gives the one series the data has, which is what a +/// caller holding the root's pieces does. #[test] -fn a_merge_across_a_closed_series_is_not_implemented() { +fn a_merge_across_two_closed_series_is_the_root_piece_stream() { let map_grid = grid(0, 60_000, 2); let tree = NativeTree::try_new(map( evaluated_input(Arc::clone(&map_grid)), @@ -1370,25 +1753,60 @@ fn a_merge_across_a_closed_series_is_not_implemented() { )) .unwrap(); } - let first = execution - .next_chunk() - .unwrap() - .expect("the first closed series is handed on before the second one arrives"); - assert_eq!(sample_values(&first), vec![Some(1.0), None]); - // The second one would merge with it, which this runtime does not do across a closed series. - let error = match execution.next_chunk() { - Ok(None) => panic!("the map produced no chunk for the closed label set"), - Ok(Some(chunk)) => panic!( - "a merge across a closed series was handed on instead of refused: {:?}", - decided(&[chunk]) - ), - Err(error) => error, - }; - let message = error.to_string(); - assert!(message.contains("job"), "{message}"); + // Both pieces come out of the root, one per source series, and neither is refused. + let mut pieces = Vec::new(); + loop { + match execution.next_chunk() { + Ok(Some(chunk)) => pieces.push(chunk), + Ok(None) => break, + Err(error) => panic!("a closed source series was refused: {error}"), + } + } + pieces.extend( + execution + .finish() + .expect("the map holds no collected input"), + ); + assert_eq!(pieces.len(), 2, "the root did not hand over both pieces"); assert!( - message.contains("already closed the label set"), - "{message}" + pieces.iter().all(|piece| piece.is_last), + "a piece of a closed source series did not close it" + ); + + // The one series the two pieces are, merged the way a consumer of the root's pieces merges + // them: positions 0 and 1 of field 0, holding 1 and 3. + let merged = merge_same_labelset( + &evaluated_schema(Arc::clone(&map_grid)), + pieces.into_iter().map(|piece| piece.series).collect(), + ) + .expect("the two pieces hold disjoint positions"); + assert_eq!( + merged.len(), + 1, + "the two pieces did not merge into one logical series" + ); + assert_eq!( + merged[0].metric, + { + let mut mapped = named_metric("a", "x"); + mapped.remove("__name__"); + mapped + }, + "the merged series does not carry the label set both pieces produced" + ); + assert_eq!( + merged[0] + .fields + .get(0) + .expect("one field") + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Some(value), + _ => None, + }) + .collect::>(), + vec![Some(1.0), Some(3.0)], + "the merged series does not hold both pieces' values at their positions" ); } @@ -1484,8 +1902,8 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { (vec![Some(1.0)], vec![None], true), (vec![None], vec![Some(f64::NAN)], true), ]; - // Both chunks are open, so the label set is still open when the second series arrives: a closed - // set refuses every second series, and this test is about what occupies a position. + // Both chunks are open and neither needs to close: what the check reads is which positions a + // chunk occupies, and that does not depend on `is_last`. let drain = |execution: &mut NativeExecutor| -> Result<(), DataFusionError> { while execution.next_chunk()?.is_some() {} Ok(()) @@ -1522,11 +1940,13 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { } } -/// One series arriving in pieces is not two series: a chunk that continues where its label set -/// ended is handed on. +/// One series arriving in pieces is not two series: the pieces are merged into the one series they +/// are, and the window above reports it once. /// -/// The map is passed twice for one label set, and the window above it reports the whole series once -/// the piece carrying `is_last` arrives. +/// The map is passed twice for one label set, so the window above collects both pieces and merges +/// them with [`crate::grid_series::merge_same_labelset`] before it evaluates: the two pieces hold +/// one position each, the window across them needs both, and answering per piece would close the +/// first series in the evaluator before the second arrived. #[test] fn a_series_that_continues_where_it_ended_is_not_a_second_series() { let inner_grid = grid(0, 60_000, 4); @@ -1551,6 +1971,8 @@ fn a_series_that_continues_where_it_ended_is_not_a_second_series() { false, )) .unwrap(); + // Nothing comes out of the collecting window before its input ended, and the piece here does + // not end it. while let Some(chunk) = execution.next_chunk().unwrap() { assert!( !chunk.is_last, @@ -1819,14 +2241,13 @@ fn an_interleaved_input_is_refused_without_a_window() { /// same label set, is not a collision: the second contributes no sample, so the answer is just the /// first one's values. /// -/// This is the other order of [`two_series_with_no_result_do_not_collide`], and the one that used to -/// fail: by the time the empty series arrives the label set is already closed, and refusing it -/// failed an execution whose answer was never in doubt. +/// This is the other order of [`two_series_with_no_result_do_not_collide`]: a series that produced +/// values under a label set, followed by one that produced none. The empty one occupies no +/// position, so it records nothing and changes nothing, and the answer is the first one's values. /// -/// The set is closed here, which is what makes the empty series a later one that also answers -/// empty. Its mirror image -- an empty closing chunk that arrives while the set is still open -- is -/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`], where the same series -/// is not a harmless extra but would take the close away from the series that filled the set. +/// The first series closed, which closes the source series and not the label set: the empty series +/// is a later one that also answers empty, and +/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`] is its mirror image. #[test] fn a_series_with_no_result_after_a_closed_one_is_passed_over() { let map_grid = grid(0, 60_000, 1); @@ -2370,7 +2791,7 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { let mut emitted = Emitted::default(); let error = emitted - .occupy(&NodePath::root(), Some(&chunk.series.metric), &chunk) + .occupy(&NodePath::root(), &chunk) .expect_err("a field with fewer samples than the axis places rows was accepted"); let message = error.to_string(); assert!( @@ -2414,7 +2835,7 @@ fn a_sparse_series_that_moves_forward_is_appended_to_its_history() { false, ); emitted - .occupy(&path, Some(&chunk.series.metric), &chunk) + .occupy(&path, &chunk) .unwrap_or_else(|error| panic!("position {position} was refused: {error}")); }; // The runs stored under the one label set, which is what `absorb` keeps in position order. From c38cf315dc97de78658227f3c9ebd7421aa7fc41 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:38:49 +0800 Subject: [PATCH 08/10] docs(promql): clarify approximate merge workspace estimate Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 3aeb9b16470..8f8113bf5da 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -180,20 +180,14 @@ fn series_bytes(series: &Series) -> usize { .saturating_add(metric_bytes(&series.metric)) } -/// An estimate of the workspace [`crate::grid_series::merge_same_labelset`] needs for fragments -/// that hold `rows` rows between them. +/// A rough workspace estimate for merging fragments that hold `rows` rows between them. /// -/// The helper sorts one `(position, member, row)` triple per fragment row and keeps the distinct -/// positions beside it, so the figure charges those vectors at their widest. Every field of every -/// fragment gets a reader, and every merged field is built as a vector of run descriptors -- one -/// slice of a fragment's segment or one run of missing rows -- before it becomes one field again, -/// so a row is charged the descriptors it can become in the worst case, several `Samples` headers -/// and their `Arc` conversions, rather than one. The output side keeps one series and one field -/// header per merged series, which is as many as there are fragments. +/// It allows for sorted row indices, readers, sample descriptors and output headers. Like the +/// retained-state estimates, it is not an allocation bound: vector slack, temporary conversions +/// and null arrays for complementary fields are not measured individually. /// -/// The sample payload is not charged: a merged run is a slice of the fragment's own segment, so the -/// merge copies no values and the fragments are what hold them. A histogram table behind several -/// fragments is likewise left to the fragments' own estimates, which count it once per fragment. +/// Existing values and histogram tables remain shared with the fragments, whose estimates already +/// account for their payloads. fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize { let sorted_rows = rows.saturating_mul( std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::(), @@ -201,9 +195,8 @@ fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize let readers = fragments.saturating_mul( fields.saturating_mul(std::mem::size_of::() + 4 * std::mem::size_of::()), ); - // What one merged field can hold while it is built: one descriptor per row at the very worst - // (alternating missing rows and values from different fragments), kept once as the run vector - // and once as the flattened field that is made from it. + // Allow for run and flattened-field descriptors when rows alternate between fragments or + // missing values; this is an estimate rather than a count of the allocations made. let merged_field_per_row = 2 * std::mem::size_of::() + 3 * std::mem::size_of::(); let merged_fields = rows From 16f18d975f8489b7dfd7592376923a49f3e6100c Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:56:31 +0800 Subject: [PATCH 09/10] fix(promql): validate series boundaries before collected input merges Keep each collecting window's open metric and last position so EOF grouping cannot hide reversed runs or identity changes before closing. Preserve source and root-map piece semantics, and test malformed input release, empty closing chunks, and EOF truncation. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute.rs | 92 ++++++++++ src/promql/src/native/execute/tests.rs | 223 +++++++++++++++++++++++++ 2 files changed, 315 insertions(+) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 8f8113bf5da..3e1fab49ade 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -286,6 +286,19 @@ struct NodeSpec { input: Option, } +/// The series whose first chunk this buffer received and whose closing chunk it has not seen. +/// +/// A window reads one series at a time, to the chunk carrying `is_last`, so the chunks of one series +/// arrive together and each of them continues the one before. What is kept here is the identity of +/// the open series and the last position it decided, which is what says whether the next chunk still +/// belongs to it and still moves forward. +struct OpenSeries { + /// The identity of the open series, as the chunk that opened it named it. + metric: MetricName, + /// The last absolute position the open series decided, when it decided any. + last_position: Option, +} + /// The input a window with a [`NodeRuntime::merge`] collects until its input ends. /// /// Such a window cannot evaluate the series under one canonical label set one after another: its @@ -293,6 +306,14 @@ struct NodeSpec { /// boundary needs are exactly the ones that closed series held. The fragments are therefore kept /// whole, merged into one series per label set with /// [`crate::grid_series::merge_same_labelset`], and only then evaluated. +/// +/// Collecting is also where the contract a series keeps is checked, because the merge that follows +/// would hide a stream that broke it: it sorts the rows by position and groups them by label set, so +/// runs that went backwards inside one series and an identity that changed inside one series both +/// come out as a plausible merged series. A streaming window refuses such a stream on the chunk that +/// breaks it, and so does [`MergeInput::check`] before the chunk is kept. An input that ends inside +/// a series is the one thing left to the executor's own check: it is reported before anything is +/// flushed, because the close a merge synthesises would make such a series look like one that ended. struct MergeInput { /// The schema the fragments are addressed on: their grid and their field count. schema: Arc, @@ -305,6 +326,9 @@ struct MergeInput { /// Neither figure walks the buffer again, and the space the fragments' payload shares is /// counted once per fragment rather than deduplicated. bytes: usize, + /// The series the next chunk has to continue, if the last chunk this buffer took did not close + /// one. Nothing is kept once a series closed: the next chunk, if any, starts another series. + open: Option, } impl MergeInput { @@ -314,9 +338,74 @@ impl MergeInput { schema, fragments: Vec::new(), bytes: 0, + open: None, } } + /// Checks one received chunk against the contract a series keeps, and follows the open series. + /// + /// The checks are the ones a streaming window makes on every delivery it reads: the chunk is + /// addressed on this window's input grid, carries one sample per row in every field, holds a + /// position unless it closes its series, continues the identity of the series it belongs to, and + /// only ever moves forward within it. They cost a constant number of reads of the chunk's own + /// axis -- its first and last positions, not its rows, which the merge then copies nothing of -- + /// and they are what keeps the sort below honest: a stream that broke one of them is refused + /// here, on the chunk that broke it, rather than merged into an answer. + /// + /// A chunk carrying `is_last` closes the open series, whether it holds rows or none at all, and + /// nothing is remembered of it: the next chunk starts a series whose identity is its own. + fn check(&mut self, path: &NodePath, series: &Series, is_last: bool) -> Result<()> { + let on_grid = match (&self.schema.eval_grid, series.time.grid()) { + (Some(input), Some(grid)) => input.spec() == grid.spec(), + _ => false, + }; + if !on_grid + || series.fields.len() != self.schema.fields.len() + || series + .fields + .iter() + .any(|field| field.len() != series.time.len()) + { + return Err(DataFusionError::Execution(format!( + "the window at {path} was handed an evaluated series that does not match its input \ + schema" + ))); + } + let (first, last) = (series.time.first_position(), series.time.last_position()); + if !is_last && first.is_none() { + return Err(DataFusionError::Execution(format!( + "the window at {path} was handed an evaluated series that holds no position before \ + the last run of its series" + ))); + } + if let Some(open) = &self.open + && open.metric != series.metric + { + return Err(DataFusionError::Execution(format!( + "the window at {path} was handed an evaluated series that changed identity before \ + its last run" + ))); + } + if let Some(previous) = self.open.as_ref().and_then(|open| open.last_position) + && let Some(first) = first + && first <= previous + { + return Err(DataFusionError::Execution(format!( + "the window at {path} was handed evaluated series runs that are not increasing: \ + {first} after {previous}" + ))); + } + self.open = if is_last { + None + } else { + Some(OpenSeries { + metric: series.metric.clone(), + last_position: last, + }) + }; + Ok(()) + } + /// The bytes of the fragments and of the workspace merging them needs. /// /// The workspace is what the helper allocates for the rows the fragments hold; the sample @@ -958,6 +1047,9 @@ impl NodeRuntime { ))); }; let EvaluatedChunk { series, is_last } = chunk; + // The chunk is checked before it is charged for or kept, so a stream that breaks the + // contract leaves nothing behind. + merge.check(path, &series, is_last)?; let positions = series.time.len(); let bytes = series_bytes(&series); // The fragment is held from here on, so the pool admits it before this node keeps it: a diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 925b9cffcec..1f2b962fd0b 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -1098,6 +1098,229 @@ fn a_pool_that_cannot_admit_a_chunk_releases_what_it_held() { ); } +/// The malformed streams a streaming window refuses are refused by the collector too. +/// +/// The window below the map collects the whole fragment stream and hands it to +/// [`crate::grid_series::merge_same_labelset`], which sorts the rows by position and groups them by +/// label set. That is what makes two closed series that share a label set one series, and it is also +/// what would hide a stream that never was one series: runs that went backwards inside a series, and +/// an identity that changed inside a series, both come out as a plausible merged series with a +/// peaceful answer. A window that read the same stream as it arrived refuses it on the chunk that +/// breaks it, and so does the collector, before the chunk is kept. +/// +/// The stream below is a single series per case and the answer it would have produced is the one +/// nothing asked for: `3` for the first (the merge would sort 1 and 2 onto positions 0 and 1), and +/// two answers for the second. +#[test] +fn a_collector_refuses_the_malformed_streams_a_streaming_window_refuses() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let tree = || { + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap() + }; + + let cases = [ + ( + "runs going backwards inside one series", + evaluated_chunk_of(&schema, named_metric("a", "x"), 1, vec![Some(1.0)], false), + evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(2.0)], true), + "not increasing", + ), + ( + "an identity changing inside one series", + evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(1.0)], false), + evaluated_chunk_of(&schema, named_metric("b", "y"), 1, vec![Some(2.0)], true), + "changed identity", + ), + ]; + for (what, first, second, phrase) in cases { + let pool = pool(); + let mut execution = executor(&tree(), Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + // The chunk that only opens the series is what a stream hands over first, and it is legal: + // the collector keeps it and reports nothing. + execution.push_evaluated(first).unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "{what}: the collector reported a piece before its input ended" + ); + execution.push_evaluated(second).unwrap(); + let error = match execution.next_chunk() { + Ok(None) => panic!("{what} was collected as if it were one series"), + Ok(Some(chunk)) => panic!("{what} reached the evaluator as {:?}", decided(&[chunk])), + Err(error) => error, + }; + let message = error.to_string(); + assert!( + message.contains(phrase), + "{what} was refused for another reason: {message}" + ); + // The failure released everything the chain held while the executor is still alive. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "{what}: the stopped execution still holds a window's samples" + ); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); + } +} + +/// The streams a streaming window accepts are accepted by the collector too. +/// +/// One series arriving in chunks that move forward is what a scan hands over, and the chunk that +/// closes a series may carry no row at all. Both are legal to a streaming window, so both are legal +/// to the collector, which merges them into the one series they are and answers over it. The values +/// are the ones the audit's counterexamples would have produced had they been legal: the two forward +/// chunks hold 1 and 3 and sum to 4, and the close that carries no row leaves the 1 it follows. +#[test] +fn a_collector_accepts_forward_runs_and_a_close_without_a_row() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let tree = || { + NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap() + }; + + let cases = [ + ( + "two chunks moving forward", + vec![ + evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(-1.0)], false), + evaluated_chunk_of(&schema, named_metric("a", "x"), 1, vec![Some(-3.0)], true), + ], + vec![(0, Some(4.0))], + ), + ( + "a close that carries no row", + vec![ + evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(-1.0)], false), + evaluated_chunk_of(&schema, named_metric("a", "x"), 2, Vec::new(), true), + ], + vec![(0, Some(1.0))], + ), + ]; + for (what, chunks, expected) in cases { + let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + for chunk in chunks { + execution.push_evaluated(chunk).unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "{what}: the collector reported a piece before its input ended" + ); + } + let out = execution + .finish() + .unwrap_or_else(|error| panic!("{what} was refused: {error}")); + assert_eq!(decided(&out), expected, "{what}"); + assert_eq!( + out.iter().filter(|chunk| chunk.is_last).count(), + 1, + "{what}: the one merged series closed more than once" + ); + } +} + +/// An input that ends inside a series is reported by a window that collects its input too. +/// +/// The collector holds the fragments until the input ends and closes every series it merges with a +/// synthetic `is_last`, so a series the caller never closed would look exactly like one that closed +/// afterwards: the merge would answer it and the barrier would hide the truncation. Nothing is +/// merged here, because the executor refuses the truncation before the flush runs. The check is the +/// input node's own, which follows what it handed over, and it is the only one needed: every closing +/// chunk the caller sent has already reached the collector, which wrote down the series it left open. +/// +/// A root map reports the same truncation, and +/// [`an_input_that_ends_mid_series_is_reported_without_a_window`] is that case on its own; this one +/// is the barrier's, where the flush would have run before the report if the check came later. +#[test] +fn an_input_that_ends_inside_a_collected_series_is_reported() { + let inner_grid = grid(0, 60_000, 2); + let outer_grid = grid(60_000, 60_000, 1); + let tree = NativeTree::try_new(window_with( + map(evaluated_input(Arc::clone(&inner_grid)), vec![MathOp::Abs]), + RangeFunction::SumOverTime, + 120_000, + Some(Arc::clone(&inner_grid)), + Arc::clone(&outer_grid), + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&inner_grid)); + let pool = pool(); + let set = ExecutionPlanMetricsSet::new(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + + // One piece of a series that never says it ended: the collector keeps it and reports nothing. + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + vec![Some(-1.0)], + false, + )) + .unwrap(); + assert!( + execution + .next_chunk() + .expect("the fragment is legal") + .is_none(), + "the collector reported a piece before its input ended" + ); + assert!( + execution.state().reserved_bytes() > 0, + "the collected fragment is not charged for" + ); + + let error = execution + .finish() + .expect_err("an input that ended inside a collected series was accepted"); + assert!( + error + .to_string() + .contains("ended before the last chunk of a series"), + "the truncation was reported as {error}" + ); + // Nothing was merged and nothing was answered, and everything went back while the executor is + // alive. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + assert_eq!( + execution.state().nodes_holding_windows(), + 0, + "the stopped execution still holds a window's samples" + ); + // The window's own gauge, which is the node that collected the fragment, reads zero. + let current = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); + assert_eq!(gauge(&set, ¤t), 0); + // A stopped execution is not resumed. + let again = execution.next_chunk().unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + /// Two series that a map turns into one label set are merged before the window above reads them. /// /// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own source From e1a631018c2961e2404357cca89626fff6e4ad80 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:22:26 +0800 Subject: [PATCH 10/10] test(promql): supply the default binary fill in the unimplemented-node fixture Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/execute/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 1f2b962fd0b..58f1b310c38 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -46,7 +46,7 @@ use crate::native::plan::{ BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) @@ -870,6 +870,7 @@ fn an_unimplemented_node_is_reported_not_panicked() { return_bool: false, labels: MatchingLabels::Ignoring(Vec::new()), cardinality: Cardinality::OneToOne, + fill: FillValues::default(), }, }, output: NativeType::Samples(evaluated_schema(out)),