diff --git a/src/datatypes/src/series/raw.rs b/src/datatypes/src/series/raw.rs index 6d4e492b951..2605eb7d0af 100644 --- a/src/datatypes/src/series/raw.rs +++ b/src/datatypes/src/series/raw.rs @@ -94,9 +94,9 @@ impl RawTimestamps { /// [`RawSeriesChunk::try_new`]; callers crossing a trust boundary must validate input. #[derive(Clone, Debug)] pub struct RawSeriesChunk { - /// Complete identity of the source series, not a TSID or hash alone. - /// With explicit labels this may be an opaque domain-qualified identity; only - /// a stream declaring a label decode specification requires a label-bearing key. + /// Complete identity of the source series, not a TSID or hash alone. Fragments of one + /// series read from different regions carry the same identity; only a stream declaring a + /// label decode specification requires a label-bearing key. pub primary_key: Buffer, /// `None` denotes an encoded key under bound-label mode; `Some` contains complete /// explicit labels and retains their identity. diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 08a6a4e41a2..ad0ac150475 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -111,7 +111,7 @@ pending. DDL cancellation retains its existing scheduling fence and priority. including nullable Float64 and native histogram fields and preserved sequence/delete rows. Its wire contract is `docs/formats/mito-samples.md`; time/ID bounds may overlap across leaves and parts. Both columnar backends share cancellation-safe output ownership - in `series_index/artifact_writer.rs`. Format readers do not apply query visibility; the prepared-source adapter applies visibility and the existing merge/dedup pipeline. Eligible sample merges use identity-only keys and omit tag columns; candidates retain memory-accounted series batch/row labels, and the raw adapter attaches explicit labels with region-qualified identities. Scanner preflight declares that representation so lazy streams and planned frames agree. Non-separable tag/sample residuals retain the full flat schema. Manual reconciliation covers all snapshot SSTs regardless of maintenance eligibility, but retains the soft disk limit. Manual builds validate columnar sample and tag schemas before reuse. Columnar reconciliation consolidates snapshot SSTs into UTC-day sample generations; catalogs record all source IDs. Grouped reads require complete daily coverage and all sources still visible, open each artifact once, and fall back for source-sequence-pruned scans. SST replacement invalidates a whole affected generation; catalog publication and reader handles govern retirement. + in `series_index/artifact_writer.rs`. Format readers do not apply query visibility; the prepared-source adapter applies visibility and the existing merge/dedup pipeline. Eligible sample merges use identity-only keys and omit tag columns; candidates retain memory-accounted series batch/row labels, and the raw adapter attaches explicit labels to exact-key identities that are not region-qualified, so fragments of one series from different regions share an identity. Scanner preflight declares that representation so lazy streams and planned frames agree. Non-separable tag/sample residuals retain the full flat schema. Manual reconciliation covers all snapshot SSTs regardless of maintenance eligibility, but retains the soft disk limit. Manual builds validate columnar sample and tag schemas before reuse. Columnar reconciliation consolidates snapshot SSTs into UTC-day sample generations; catalogs record all source IDs. Grouped reads require complete daily coverage and all sources still visible, open each artifact once, and fall back for source-sequence-pruned scans. SST replacement invalidates a whole affected generation; catalog publication and reader handles govern retirement. - **Request types** (`request.rs`): usually tied to proto definitions consumed by `datanode`. - **WAL/memtable encoding** (`wal/`, `memtable/`): breaks replay if changed incompatibly. diff --git a/src/mito2/src/read/series_scan/prepared.rs b/src/mito2/src/read/series_scan/prepared.rs index 2dcdccd554e..ed6130a9d9a 100644 --- a/src/mito2/src/read/series_scan/prepared.rs +++ b/src/mito2/src/read/series_scan/prepared.rs @@ -363,12 +363,11 @@ fn predicate_conjuncts(predicate: Option<&Predicate>) -> Vec<&Expr> { struct Candidate { /// Coarse prefix of the exact key; only a hash, never identity. id: MetricSeriesId, - /// The one owned key allocation: the region-qualified exact key. + /// The canonical sparse key: the identity every comparison, sample attribution and output + /// chunk uses. It must not be qualified by region: every region holding a fragment of one + /// series has to report the same identity, or the fragments never meet in one owner above + /// the regions. key: Buffer, - /// The canonical sparse key, a view of `key`'s bytes. This is the identity every - /// comparison and sample attribution uses, so it is stored once rather than once per - /// representation. - merge_key: Buffer, tags: HashMap>, metric: Option, } @@ -381,6 +380,7 @@ pub(crate) struct ColumnarPreparedSource { merge_field_start: usize, // Append-mode Narthex raw reads still require one row per series/timestamp. dedup_append_raw: bool, + sample_partition: Option>, candidates: Arc>, samples: Arc>>, metrics: PartitionMetrics, @@ -534,6 +534,18 @@ impl ColumnarPreparedSource { preparation_metrics.counts.insert("prepare_batch_series", 0); let direct_labels = !batch_output && sample_schema.is_some(); let conjuncts = predicate_conjuncts(input.predicate_group().predicate()); + let partition = if input.requires_narthex_preparation() { + narthex_partition_filter(metadata.partition_expr.as_deref(), None)? + } else { + None + }; + // Series rows carry tags only, so a rule over any other column, such as the time index, + // filters sample rows instead. + let (series_partition, sample_partition) = match partition { + Some(rule) if partition_on_tags_only(&rule, metadata) => (Some(rule), None), + Some(rule) => (None, Some(SamplePartitionFilter::try_new(&rule, metadata)?)), + None => (None, None), + }; let mut retained_rows = 0_usize; let mut candidates = BTreeMap::::new(); while let Some((reader, window)) = series.readers.pop_front() { @@ -577,10 +589,7 @@ impl ColumnarPreparedSource { .map_err(|e| invalid(e.to_string()))?, ); } - if context.input.requires_narthex_preparation() - && let Some(partition) = - narthex_partition_filter(metadata.partition_expr.as_deref(), None)? - { + if let Some(partition) = &series_partition { filters.push( partition .try_as_physical_expr(&projected_schema) @@ -752,26 +761,21 @@ impl ColumnarPreparedSource { (!strings.is_null(row)).then(|| strings.value(row).to_owned()), ); } + } else if let Some(filter) = &sample_partition { + for column_id in filter.tag_ids() { + let (_, strings) = + tag_arrays + .iter() + .find(|(id, _)| *id == column_id) + .ok_or_else(|| invalid("missing partition tag column"))?; + values.insert( + column_id, + (!strings.is_null(row)).then(|| strings.value(row).to_owned()), + ); + } } tag_values += values.len() as u64; - // `merge_key` is always the exact key bytes. Explicit-label chunks keep - // the region-qualified form as their `key`, so `primary_key` stays - // region-scoped while identity and ordering stay exact. - let key = if direct_labels { - let mut buffer = Vec::with_capacity(8 + exact.bytes().len()); - buffer.extend_from_slice(&metadata.region_id.as_u64().to_be_bytes()); - buffer.extend_from_slice(exact.bytes()); - Buffer::from(buffer) - } else { - Buffer::from(exact.bytes().to_vec()) - }; - let merge_key = if direct_labels { - key.slice_with_length(8, exact.bytes().len()) - } else { - key.clone() - }; - // The exact key is stored once: `merge_key` is a view of `key`, so the - // reservation charges the single key allocation the candidate retains. + let key = Buffer::from(exact.bytes().to_vec()); let bytes = key.len() + values.values().flatten().map(String::len).sum::() + values.capacity() * (std::mem::size_of::<(u32, Option)>() + 16) @@ -802,7 +806,6 @@ impl ColumnarPreparedSource { Candidate { id, key, - merge_key, tags: values, metric, }, @@ -844,6 +847,7 @@ impl ColumnarPreparedSource { sample_schema, merge_field_start, dedup_append_raw, + sample_partition: sample_partition.map(Arc::new), candidates: Arc::new(candidates), samples: Arc::new(samples), metrics, @@ -867,6 +871,7 @@ impl ColumnarPreparedSource { let scan_pool = self.scan_pool.clone(); let field_column_start = self.merge_field_start; let dedup_append_raw = self.dedup_append_raw; + let sample_partition = self.sample_partition.clone(); // Time-only conjuncts drop every version of a (series, time) key alike, so they // commute with dedup and must run before the merge: a row selector inside the // merge would otherwise pick a row they reject. Other conjuncts may depend on @@ -909,6 +914,7 @@ impl ColumnarPreparedSource { let reader = reader.clone(); let sample_schema = sample_schema.clone(); let scan_pool = scan_pool.clone(); + let sample_partition = sample_partition.clone(); let time_filters = time_filters.clone(); sources.push(Box::pin(async_stream::try_stream! { let reservation = MemoryConsumer::new("ColumnarSamplesRead").register(&scan_pool); @@ -920,7 +926,7 @@ impl ColumnarPreparedSource { .iter() .map(|candidate| { std::mem::size_of::() - + candidate.merge_key.len() + + candidate.key.len() + std::mem::size_of::() + 64 }) @@ -935,7 +941,7 @@ impl ColumnarPreparedSource { let mut offsets = mito_codec::row_converter::SparseOffsetsCache::new(); let keys = candidates[range.clone()] .iter() - .map(|c| ExactSeriesKey::from_sparse_key(c.merge_key.as_slice(), &mut offsets)) + .map(|c| ExactSeriesKey::from_sparse_key(c.key.as_slice(), &mut offsets)) .collect::>>()?; let mut stage_metrics = crate::metrics::ColumnarReadMetrics::default(); let schema = reader.schema(); @@ -963,12 +969,16 @@ impl ColumnarPreparedSource { let SamplesBatch { batch, key } = samples; let ordinal = candidates[range.clone()] .binary_search_by(|candidate| { - candidate.merge_key.as_slice().cmp(key.bytes()) + candidate.key.as_slice().cmp(key.bytes()) }) .map_err(|_| invalid("sample contains an unselected series"))? + range.start; let started = std::time::Instant::now(); let flat = sample_to_flat(batch, &candidates[ordinal], &context, sample_schema.as_ref())?; + let flat = match &sample_partition { + Some(filter) => filter.filter(flat, &candidates[ordinal])?, + None => flat, + }; let mut flat = filter_visibility(flat, &context)?; for filter in time_filters.iter() { flat = common_recordbatch::filter::batch_filter(&flat, filter) @@ -1057,7 +1067,7 @@ impl PreparedSeriesSource for ColumnarPreparedSource { // The resolver can outlive the exhausted sample stream. let _reservation = &reservation; let ordinal = candidates - .binary_search_by(|candidate| candidate.merge_key.as_slice().cmp(key.as_slice())) + .binary_search_by(|candidate| candidate.key.as_slice().cmp(key.as_slice())) .map_err(|_| BoxedError::new(invalid("unknown merged series identity")))?; Ok(( candidates[ordinal].key.clone(), @@ -1139,11 +1149,7 @@ fn sample_to_flat( let schema = sample_schema .cloned() .unwrap_or_else(|| context.input.mapper.input_arrow_schema(false)); - let key = if sample_schema.is_some() { - &candidate.merge_key - } else { - &candidate.key - }; + let key = &candidate.key; let metadata = context.input.region_metadata(); let mut arrays = Vec::::new(); for field in schema.fields() { @@ -1341,6 +1347,137 @@ fn narthex_partition_filter( .filter(|partition| file_partition != Some(partition))) } +fn partition_on_tags_only( + rule: &partition::expr::PartitionExpr, + metadata: &store_api::metadata::RegionMetadata, +) -> bool { + let mut columns = HashSet::new(); + rule.collect_column_names(&mut columns); + columns.iter().all(|name| { + metadata + .column_by_name(name) + .is_some_and(|column| column.semantic_type == SemanticType::Tag) + }) +} + +/// A region partition rule that references a column other than a tag, applied to sample rows. +/// +/// Files shared after repartition can hold rows of other partitions, so the rule has to drop them +/// row by row; a series may own rows on both sides of the rule. +struct SamplePartitionFilter { + /// The columns the rule references, typed as the region declares them. + schema: SchemaRef, + /// Where each schema field's values come from. + inputs: Vec, + expr: Arc, +} + +enum PartitionInput { + /// Logical table ID of the series. Repartitioning a metric table may route on it, and the + /// series index keeps it outside the tag columns. + TableId, + /// A tag column, by column ID, valued from the series. + Tag(u32), + /// A column the sample rows carry. + Sample, +} + +impl SamplePartitionFilter { + fn try_new( + rule: &partition::expr::PartitionExpr, + metadata: &store_api::metadata::RegionMetadata, + ) -> Result { + let mut names = HashSet::new(); + rule.collect_column_names(&mut names); + let mut names = names.into_iter().collect::>(); + names.sort_unstable(); + let mut fields = Vec::with_capacity(names.len()); + let mut inputs = Vec::with_capacity(names.len()); + for name in names { + let column = metadata + .column_by_name(&name) + .ok_or_else(|| invalid(format!("unknown partition column {name}")))?; + fields.push(datatypes::arrow::datatypes::Field::new( + name, + datatypes::data_type::DataType::as_arrow_type(&column.column_schema.data_type), + true, + )); + inputs.push(if column.column_id == ReservedColumnId::table_id() { + PartitionInput::TableId + } else if column.semantic_type == SemanticType::Tag { + PartitionInput::Tag(column.column_id) + } else { + PartitionInput::Sample + }); + } + let schema = Arc::new(Schema::new(fields)); + let expr = rule + .try_as_physical_expr(&schema) + .map_err(|error| invalid(error.to_string()))?; + Ok(Self { + schema, + inputs, + expr, + }) + } + + fn tag_ids(&self) -> impl Iterator + '_ { + self.inputs.iter().filter_map(|input| match input { + PartitionInput::Tag(column_id) => Some(*column_id), + _ => None, + }) + } + + /// Keeps the rows of `flat`, all of `candidate`, that the rule assigns to this region. + fn filter(&self, flat: RecordBatch, candidate: &Candidate) -> Result { + let rows = flat.num_rows(); + let columns = self + .schema + .fields() + .iter() + .zip(&self.inputs) + .map(|(field, input)| match input { + PartitionInput::TableId => { + Ok(Arc::new(UInt32Array::from(vec![candidate.id.table_id; rows])) as ArrayRef) + } + PartitionInput::Tag(column_id) => { + let value = candidate + .tags + .get(column_id) + .ok_or_else(|| invalid("missing partition tag"))?; + Ok(Arc::new(StringArray::from(vec![value.as_deref(); rows])) as ArrayRef) + } + PartitionInput::Sample => { + let array = flat + .column_by_name(field.name()) + .ok_or_else(|| invalid("missing partition column in samples"))?; + if array.data_type() == field.data_type() { + Ok(array.clone()) + } else { + cast(array, field.data_type()).context(ComputeArrowSnafu) + } + } + }) + .collect::>>()?; + let columns = RecordBatch::try_new_with_options( + self.schema.clone(), + columns, + &datatypes::arrow::record_batch::RecordBatchOptions::new().with_row_count(Some(rows)), + ) + .context(NewRecordBatchSnafu)?; + let mask = self + .expr + .evaluate(&columns) + .and_then(|value| value.into_array(rows)) + .map_err(|error| invalid(error.to_string()))?; + let mask = mask + .as_any() + .downcast_ref::() + .ok_or_else(|| invalid("partition rule must evaluate to booleans"))?; + filter_record_batch(&flat, mask).context(ComputeArrowSnafu) + } +} + /// Shares narthex discovery across partitions and assigns disjoint exact-series ranges. pub(crate) fn scan_batches( preparation: Arc, diff --git a/src/mito2/src/read/series_scan/prepared/tests.rs b/src/mito2/src/read/series_scan/prepared/tests.rs index c654095f49a..a9e04f8657a 100644 --- a/src/mito2/src/read/series_scan/prepared/tests.rs +++ b/src/mito2/src/read/series_scan/prepared/tests.rs @@ -338,14 +338,9 @@ fn rows(chunks: &[RawSeriesChunk]) -> Vec<(Vec, i64, f64)> { }; ( { - let key = if chunk.metric.is_some() { - &chunk.primary_key.as_slice()[8..] - } else { - chunk.primary_key.as_slice() - }; let (table, tsid) = mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless() - .decode_ids(key) + .decode_ids(chunk.primary_key.as_slice()) .unwrap(); [ table.to_be_bytes().as_slice(), @@ -1150,6 +1145,7 @@ async fn ordinal_range_batches_sample_requests_and_pushes_time_bounds() { let requests = Arc::new(Mutex::new(Vec::new())); let source = ColumnarPreparedSource { dedup_append_raw: false, + sample_partition: None, scan_pool: source.scan_pool.clone(), merge_field_start: 0, context: source.context.clone(), @@ -1192,7 +1188,7 @@ async fn ordinal_range_batches_sample_requests_and_pushes_time_bounds() { let keys = source .candidates .iter() - .map(|c| c.merge_key.to_vec()) + .map(|c| c.key.to_vec()) .collect::>(); for request in requests.iter() { let requested = request @@ -2463,7 +2459,7 @@ async fn overlapping_buckets_keep_colliding_physical_tags(#[case] mixed: bool) { let identities: HashSet> = source .candidates .iter() - .map(|candidate| candidate.merge_key.to_vec()) + .map(|candidate| candidate.key.to_vec()) .collect(); assert_eq!(2, identities.len(), "colliding series keep distinct keys"); if !mixed { @@ -2642,13 +2638,11 @@ async fn long_keys_prepare_and_read() { .unwrap(); let source = scan.prepared.source.get().unwrap().as_ref().unwrap(); // The fixture's own series prepare beside this one; the long key must survive preparation - // byte for byte and own its samples. Served samples make `primary_key` region-qualified. - let mut expected = metadata.region_id.as_u64().to_be_bytes().to_vec(); - expected.extend_from_slice(&key); + // byte for byte and own its samples. The identity is the stored key itself, not a + // region-qualified form, so fragments of a series in other regions report the same one. let ordinal = (0..source.num_series()) .find(|ordinal| { - source.series_info(*ordinal).unwrap().primary_key.as_ref() as &[u8] - == expected.as_slice() + source.series_info(*ordinal).unwrap().primary_key.as_ref() as &[u8] == key.as_slice() }) .expect("preparation must keep the series whose key is longer than 8 KiB"); let chunks = source @@ -3105,6 +3099,13 @@ async fn authoritative_narthex_preparation_without_sidecars( } async fn authoritative_fixture(merge_mode: &str) -> (TestEnv, MitoEngine, MitoRegionRef) { + authoritative_fixture_with(merge_mode, None).await +} + +async fn authoritative_fixture_with( + merge_mode: &str, + partition_expr: Option, +) -> (TestEnv, MitoEngine, MitoRegionRef) { let mut env = TestEnv::with_prefix("narthex-review").await; let engine = env .create_engine(MitoConfig { @@ -3124,6 +3125,7 @@ async fn authoritative_fixture(merge_mode: &str) -> (TestEnv, MitoEngine, MitoRe .insert_option("primary_key_encoding", "sparse") .insert_option("sst_format", "narthex") .insert_option("merge_mode", merge_mode) + .partition_expr_json(partition_expr) .build(); create.column_metadatas = metadata.column_metadatas; create.primary_key = metadata.primary_key; @@ -3136,6 +3138,73 @@ async fn authoritative_fixture(merge_mode: &str) -> (TestEnv, MitoEngine, MitoRe (env, engine, region) } +/// A time-partitioned region keeps only its own rows, though a file shared after repartition +/// holds rows of both partitions and series rows carry no time index to filter on. Key columns +/// a mixed rule references take the series' values, `__table_id` included. +#[rstest::rstest] +#[case::time(None)] +#[case::tag_and_time(Some(partition::expr::col("tag_0").eq(Value::from("a"))))] +#[case::table_id_and_time(Some( + partition::expr::col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME).eq(Value::UInt32(10)) +))] +#[tokio::test] +async fn authoritative_time_partition_filters_sample_rows( + #[case] key_rule: Option, +) { + let time_rule = partition::expr::col("ts").lt(Value::Timestamp( + common_time::Timestamp::new_millisecond(60_000), + )); + let rule = match key_rule { + Some(key_rule) => key_rule.and(time_rule), + None => time_rule, + }; + let (_env, engine, region) = + authoritative_fixture_with("last_row", Some(rule.as_json_str().unwrap())).await; + // 61_000 belongs to the other partition, as rows of a shared file do. + for timestamp in [1000, 61_000] { + write(&engine, ®ion, 7, timestamp, Some(7.0)).await; + } + flush_region(&engine, region.region_id, None).await; + + let stream = engine + .scan_to_stream(region.region_id, ScanRequest::default()) + .await + .unwrap(); + let batches = common_recordbatch::RecordBatches::try_collect(stream) + .await + .unwrap(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 1 + ); + + // Compaction reads without the region predicate, so only the rule keeps the other + // partition's row out of the output. + engine + .handle_request( + region.region_id, + RegionRequest::Compact(store_api::region_request::RegionCompactRequest { + options: api::v1::region::compact_request::Options::StrictWindow( + api::v1::region::StrictWindow { window_seconds: 60 }, + ), + parallelism: None, + time_range: None, + }), + ) + .await + .unwrap(); + let version = region.version(); + let rows = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .map(|file| file.meta_ref().num_rows) + .sum::(); + assert_eq!(rows, 1); + engine.stop().await.unwrap(); +} + #[tokio::test] async fn authoritative_strict_windows_preserve_rows() { let (_env, engine, region) = authoritative_fixture("last_row").await; diff --git a/src/promql/AGENTS.md b/src/promql/AGENTS.md index 437c58b1315..03804148b72 100644 --- a/src/promql/AGENTS.md +++ b/src/promql/AGENTS.md @@ -22,12 +22,13 @@ functions, vector matching and extension operators. Statement planning lives in ## Native execution boundary Native PromQL is an experimental, standalone evaluation route alongside the -existing DataFusion PromQL path. It operates on one storage region, which may -supply multiple scan partitions. Where a boundary must answer one logical -series once, `SeriesRepartitionExec` merges that identity's fragments across -scan partitions and recomputes a single close for it. Cross-region -`SeriesMerge`/`Exchange` are still not implemented, so a logical series split -across regions is not merged. Do not describe partition-local work as a global +existing DataFusion PromQL path. A region may supply multiple scan partitions. +Where a boundary must answer one logical series once, `SeriesRepartitionExec` +merges that identity's fragments and recomputes a single close for it. A table +partitioned on a non-tag column splits series across regions; the planner reads +such a selector through `RawSeriesSource` and merges the fragments above the +regions, keyed by the raw primary key, which every region must report +identically for one series. Do not describe partition-local work as a global series merge. Vector operations use the existing vector-matching semantics; do not describe diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs index 2bfb6084728..4000bc20290 100644 --- a/src/promql/src/extension_plan/series_repartition/tests.rs +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -8425,7 +8425,7 @@ async fn a_raw_merge_conflict_fails_the_execution() { assert!( error .to_string() - .contains("duplicate raw timestamp has conflicting samples") + .contains("has two different samples at timestamp 1 ms") ); } diff --git a/src/promql/src/source/merge.rs b/src/promql/src/source/merge.rs index 3bf0057fc04..42a4ca434b6 100644 --- a/src/promql/src/source/merge.rs +++ b/src/promql/src/source/merge.rs @@ -18,10 +18,13 @@ mod tests; use datafusion::arrow::buffer::ScalarBuffer; use datafusion_common::DataFusionError; use datatypes::error::InvalidSeriesSnafu; +use datatypes::series::SeriesLabels; use datatypes::series::histogram::HistogramView; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{SampleRef, Samples, SeriesFields, SeriesSchema}; +use crate::grid_series::{label_set, render_label_set}; + /// Rebuilds one raw series from every piece of one complete physical identity, reporting each /// allocation before it happens. /// @@ -151,7 +154,7 @@ pub(crate) fn merge_raw_identity_charging( .ok_or_else(|| invalid("field index out of bounds"))? .sample(duplicate.2), ) { - return Err(invalid("duplicate raw timestamp has conflicting samples")); + return Err(invalid(&conflicting_samples(&labels, rows[index].0))); } } } @@ -211,6 +214,20 @@ pub(crate) fn merge_raw_identity_charging( Ok(result) } +/// Raw timestamps strictly increase within a chunk, so the two samples come from two chunks of +/// one identity: normally two regions of a table partitioned on a non-tag column, each holding +/// one side of an overwrite. Two chunks of one region should never disagree, so the cause is +/// stated as likely. +fn conflicting_samples(labels: &SeriesLabels, timestamp: i64) -> String { + format!( + "series {} has two different samples at timestamp {timestamp} ms, read from different \ + regions or scan partitions. Likely cause: the table is partitioned on a non-tag column \ + and this sample was written with values on both sides of a partition bound, so each \ + region kept one version", + render_label_set(&label_set(labels)) + ) +} + fn samples_equal(left: SampleRef<'_>, right: SampleRef<'_>) -> bool { match (left, right) { (SampleRef::Missing, SampleRef::Missing) => true, diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 8f89f2866a7..47f590a618f 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -595,8 +595,8 @@ pub type SendableRawSeriesStream = Pin>; /// Stable identity metadata for one ordinal in a prepared series source. #[derive(Clone, Debug)] pub struct SeriesInfo { - /// Complete source identity, not a TSID or hash alone. Explicit-label sources - /// may use an opaque domain-qualified identity instead of a label-bearing key. + /// Complete source identity, not a TSID or hash alone. Every region holding a fragment of + /// one series reports the same identity, so it must not be qualified by region. pub primary_key: datatypes::arrow::buffer::Buffer, /// Complete explicit metric name and labels, not a partial label projection; or `None` for /// primary-key label binding (undecoded, not nameless). The metric name itself may be absent. diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index a3a28adb38a..eadd76f2fce 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -18367,6 +18367,272 @@ async fn native_promql_matrix_root_matches_legacy() { assert_eq!(native, legacy); } +/// Creates `split_a` and `split_b` in `db` on one physical metric table. With `narthex`, the +/// physical table uses narthex storage and is partitioned on the time index at 300s, so every +/// series is split across two regions; otherwise it is a default-storage, unpartitioned +/// reference. The rows are flushed twice and the last sample stays in the memtable. +async fn setup_time_split_database(instance: &Arc, db: &str, narthex: bool) { + execute_all( + instance, + &format!("CREATE DATABASE {db}"), + QueryContext::arc(), + ) + .await; + let ctx = Arc::new(QueryContext::with_db_name(Some(db))); + let (partition, storage) = if narthex { + ( + "PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:05:00', ts >= '1970-01-01 00:05:00') ", + ", 'sst_format'='narthex'", + ) + } else { + ("", "") + }; + execute_all( + instance, + &format!( + "CREATE TABLE phy (job STRING, instance STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, \ + PRIMARY KEY(job, instance)) {partition}ENGINE=metric \ + WITH ('physical_metric_table'='true'{storage})" + ), + ctx.clone(), + ) + .await; + for metric in ["split_a", "split_b"] { + execute_all( + instance, + &format!( + "CREATE TABLE {metric} (job STRING, instance STRING, ts TIMESTAMP TIME INDEX, \ + val DOUBLE, PRIMARY KEY(job, instance)) ENGINE=metric \ + WITH ('on_physical_table'='phy')" + ), + ctx.clone(), + ) + .await; + } + // Counters growing by `k` per 30s step (`2k` for `split_b`); `db/1` resets at 330s. + for (times, flush) in [(0..=300, true), (330..=570, true), (600..=600, false)] { + for (metric, scale) in [("split_a", 1), ("split_b", 2)] { + let rows = [("api", "0"), ("api", "1"), ("db", "0"), ("db", "1")] + .into_iter() + .zip(1u32..) + .flat_map(|((job, instance), k)| { + times.clone().step_by(30).map(move |t: u32| { + let steps = if (job, instance) == ("db", "1") && t >= 330 { + (t - 330) / 30 + } else { + t / 30 + }; + format!( + "('{job}', '{instance}', {}, {})", + u64::from(t) * 1000, + scale * k * steps + 1 + ) + }) + }) + .collect::>() + .join(", "); + execute_all( + instance, + &format!("INSERT INTO {metric} (job, instance, ts, val) VALUES {rows}"), + ctx.clone(), + ) + .await; + } + if flush { + execute_all(instance, "ADMIN FLUSH_TABLE('phy')", ctx.clone()).await; + } + } +} + +/// `(time, labels without __name__, value)` of `query` over `[60s, 600s]` in `db`, and whether +/// the plan ran on the native route. +async fn time_split_rows( + instance: &Arc, + db: &str, + native: bool, + query: &str, +) -> ( + Vec<(i64, std::collections::BTreeMap, f64)>, + bool, +) { + let mut ctx = QueryContext::with_db_name(Some(db)); + ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); + ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, native.to_string()); + let query = PromQuery { + query: query.to_string(), + start: "60".to_string(), + end: "600".to_string(), + step: "60s".to_string(), + ..PromQuery::default() + }; + let output = instance + .do_promql_query(&query, Arc::new(ctx)) + .await + .remove(0) + .unwrap_or_else(|error| panic!("{}: {error:?}", query.query)); + let ran_natively = output.meta.plan.as_ref().is_some_and(|plan| { + native_plan_nodes(plan) + .iter() + .any(|node| node.name() == "FusedSeriesExec") + }); + let (_, mut rows) = native_labelled_rows(output).await; + for (_, labels, _) in &mut rows { + labels.remove("__name__"); + } + rows.sort_by(|left, right| (&left.1, left.0).cmp(&(&right.1, right.0))); + (rows, ran_natively) +} + +/// Native PromQL and SQL over a narthex table partitioned on the time index answer like the same +/// rows held whole in one default-storage region. +/// +/// Such a partition splits every series across regions. Reading it needs the region's partition +/// rule applied to sample rows, since series rows have no time index, and the fragments of a +/// series from both regions must carry one identity so the frontend merges them. +async fn assert_time_split_narthex_matches_reference(instance: &Arc) { + setup_time_split_database(instance, "narthex_split", true).await; + setup_time_split_database(instance, "narthex_ref", false).await; + + let sql = "SELECT job, instance, ts, val FROM split_a ORDER BY job, instance, ts"; + let mut answers = Vec::new(); + for db in ["narthex_split", "narthex_ref"] { + let ctx = Arc::new(QueryContext::with_db_name(Some(db))); + let output = instance.do_query(sql, ctx).await.remove(0).unwrap(); + answers.push(native_output_text(output).await); + } + assert_eq!(answers[0], answers[1], "{sql}"); + + for query in [ + "split_a", + "rate(split_a[2m])", + "increase(split_a[3m])", + "resets(split_a[5m])", + "sum_over_time(split_a[2m])", + "max_over_time(split_a[2m])", + "count_over_time(split_a[2m])", + "quantile_over_time(0.5, split_a[3m])", + "sum by (job) (rate(split_a[2m]))", + "topk(2, split_a)", + "split_a + on(job, instance) split_b", + "split_a / ignoring(instance) group_left sum by (job) (split_b)", + "split_a{job=\"api\"} or split_b", + "split_a unless on(job) split_b{job=\"api\"}", + "max_over_time(rate(split_a[2m])[5m:1m])", + "rate(split_a[2m] offset 2m)", + "split_a @ 300", + "label_replace(split_a, \"svc\", \"$1\", \"job\", \"(.*)\")", + ] { + let (expected, _) = time_split_rows(instance, "narthex_ref", false, query).await; + assert!( + !expected.is_empty(), + "{query}: the reference answered nothing" + ); + let (rows, ran_natively) = time_split_rows(instance, "narthex_split", true, query).await; + assert!(ran_natively, "{query}: the native route must run"); + assert_eq!(rows.len(), expected.len(), "{query}: {rows:?}"); + for (actual, expected) in rows.iter().zip(&expected) { + assert_eq!((actual.0, &actual.1), (expected.0, &expected.1), "{query}"); + assert!( + (actual.2 - expected.2).abs() <= 1e-9 * actual.2.abs().max(expected.2.abs()), + "{query}: {actual:?} != {expected:?}" + ); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_over_a_time_partitioned_narthex_table_matches_reference() { + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("native_promql_narthex_time_split") + .with_query_options(QueryOptions { + experimental_native_promql: true, + ..Default::default() + }) + .build() + .await; + assert_time_split_narthex_matches_reference(standalone.fe_instance()).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn distributed_native_promql_over_a_time_partitioned_narthex_table_matches_reference() { + common_telemetry::init_default_ut_logging(); + let cluster = GreptimeDbClusterBuilder::new("distributed_native_promql_narthex_time_split") + .await + .with_datanodes(2) + .with_query_options(QueryOptions { + experimental_native_promql: true, + ..Default::default() + }) + .build(false) + .await; + assert_time_split_narthex_matches_reference(cluster.fe_instance()).await; +} + +/// A narthex table partitioned on its sample value keeps both versions of a sample overwritten +/// across the partition bound, one per region. Regions do not order writes against each other, so +/// the native route refuses the series, and the error has to say which sample and why. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_reports_an_overwrite_across_a_value_partition() { + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("native_promql_value_partition_overwrite") + .with_query_options(QueryOptions { + experimental_native_promql: true, + ..Default::default() + }) + .build() + .await; + let instance = standalone.fe_instance(); + let ctx = QueryContext::arc(); + for sql in [ + "CREATE TABLE phy (job STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, PRIMARY KEY(job)) \ + PARTITION ON COLUMNS (val) (val < 0, val >= 0) ENGINE=metric \ + WITH ('physical_metric_table'='true', 'sst_format'='narthex')", + "CREATE TABLE value_split (job STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, \ + PRIMARY KEY(job)) ENGINE=metric WITH ('on_physical_table'='phy')", + "INSERT INTO value_split (job, ts, val) VALUES ('api', 0, 5), ('api', 60000, -1)", + "INSERT INTO value_split (job, ts, val) VALUES ('api', 60000, 1)", + ] { + execute_all(instance, sql, ctx.clone()).await; + } + let mut ctx = QueryContext::with_db_name(None); + ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); + let query = PromQuery { + query: "value_split".to_string(), + start: "60".to_string(), + end: "60".to_string(), + step: "1".to_string(), + ..PromQuery::default() + }; + let output = instance + .do_promql_query(&query, Arc::new(ctx)) + .await + .remove(0) + .unwrap(); + assert!( + output + .meta + .plan + .as_ref() + .is_some_and(|plan| native_plan_nodes(plan) + .iter() + .any(|node| node.name() == "FusedSeriesExec")), + "the native route must run" + ); + let OutputData::Stream(stream) = output.data else { + unreachable!("a native PromQL query streams its answer") + }; + let error = collect_batches(stream).await.unwrap_err().to_string(); + assert!( + error.contains( + "series {__name__=\"value_split\", job=\"api\"} has two different samples at \ + timestamp 60000 ms, read from different regions or scan partitions. Likely cause: the \ + table is partitioned on a non-tag column and this sample was written with values on \ + both sides of a partition bound, so each region kept one version" + ), + "{error}" + ); +} + /// Native histograms in a Narthex physical table, and in a Parquet one served by a columnar /// series-index sidecar, answer what the same samples answer in a plain Parquet table: PromQL on /// both routes and remote read, from the memtable, after flushes, after a compaction and after a