diff --git a/src/client/src/region.rs b/src/client/src/region.rs index 2c13d75e6fd..d446706d45e 100644 --- a/src/client/src/region.rs +++ b/src/client/src/region.rs @@ -35,14 +35,13 @@ use common_meta::error::{self as meta_error, Result as MetaResult}; use common_meta::node_manager::Datanode; use common_query::error::Error as CommonQueryError; use common_query::request::{QueryRequest, RAW_SERIES_REQUEST_EXTENSION_KEY, RawSeriesRequest}; -use common_query::series_frame::unpack_raw_series; +use common_query::series_frame::{raw_series_frame_ordering, unpack_raw_series}; use common_recordbatch::adapter::DfRecordBatchStreamAdapter; use common_recordbatch::error::ExternalSnafu; use common_recordbatch::{RecordBatch, RecordBatchStreamWrapper, SendableRecordBatchStream}; use common_telemetry::error; use common_telemetry::tracing::Span; use common_telemetry::tracing_context::TracingContext; -use datatypes::series::raw::RawSeriesOrdering; use futures_util::Stream; use prost::Message; use query::query_engine::DefaultSerializer; @@ -165,20 +164,17 @@ impl RegionRequester { .extensions .insert(RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(), extension); let stream = Datanode::handle_query(self, request).await?; + let ordering = raw_series_frame_ordering(stream.schema().arrow_schema().as_ref()); let stream = Box::pin(DfRecordBatchStreamAdapter::new(stream)); - unpack_raw_series( - stream, - expected_schema, - label_source, - RawSeriesOrdering::Contiguous, - ) - .map_err(|error| { - BoxedError::new(CommonQueryError::GeneralDataFusion { - error, - location: location!(), + ordering + .and_then(|ordering| unpack_raw_series(stream, expected_schema, label_source, ordering)) + .map_err(|error| { + BoxedError::new(CommonQueryError::GeneralDataFusion { + error, + location: location!(), + }) }) - }) - .context(meta_error::ExternalSnafu) + .context(meta_error::ExternalSnafu) } pub async fn do_get_inner(&self, ticket: Ticket) -> Result { diff --git a/src/common/query/src/series_frame.rs b/src/common/query/src/series_frame.rs index 8ade66f1940..3de1ab0e26d 100644 --- a/src/common/query/src/series_frame.rs +++ b/src/common/query/src/series_frame.rs @@ -27,6 +27,7 @@ use std::task::{Context, Poll}; use common_error::ext::BoxedError; use common_recordbatch::{DfRecordBatch, DfSendableRecordBatchStream}; use datafusion_common::DataFusionError; +use datatypes::arrow::datatypes::{Schema as ArrowSchema, SchemaRef as ArrowSchemaRef}; use datatypes::error::InvalidSeriesSnafu; use datatypes::series::MetricName; use datatypes::series::frame::{ @@ -44,6 +45,43 @@ pub use record_batches::{InputMapping, record_batches_to_raw_series}; #[cfg(test)] mod tests; +const ORDERING_KEY: &str = "greptime.series.ordering"; + +/// Builds the canonical raw frame schema with the producer's guaranteed ordering. +/// +/// Ordering records a producer guarantee; it is not inferred from frame contents. +pub fn raw_series_frame_schema_with_ordering( + schema: &SeriesSchema, + mode: RawLabelMode, + ordering: RawSeriesOrdering, +) -> datafusion_common::Result { + let schema = raw_series_frame_schema(schema, mode).map_err(codec_error)?; + let mut metadata = schema.metadata().clone(); + metadata.insert( + ORDERING_KEY.to_string(), + match ordering { + RawSeriesOrdering::Contiguous => "contiguous", + RawSeriesOrdering::ReadKeyThenTime => "read_key_then_time", + } + .to_string(), + ); + Ok(Arc::new(ArrowSchema::new_with_metadata( + schema.fields().clone(), + metadata, + ))) +} + +/// Reads the declared producer ordering, conservatively treating legacy frames as contiguous. +pub fn raw_series_frame_ordering( + schema: &ArrowSchema, +) -> datafusion_common::Result { + match schema.metadata().get(ORDERING_KEY).map(String::as_str) { + None | Some("contiguous") => Ok(RawSeriesOrdering::Contiguous), + Some("read_key_then_time") => Ok(RawSeriesOrdering::ReadKeyThenTime), + Some(_) => Err(invalid("unknown raw series ordering")), + } +} + /// Packs a storage raw-series stream into DataFusion record batches incrementally. /// /// Producers must keep each read key's chunks contiguous. Validation checks adjacent chunk @@ -55,7 +93,7 @@ pub fn pack_raw_series( let label_source = source.label_source().clone(); let ordering = source.ordering(); let mode = label_mode(&label_source); - let frame_schema = raw_series_frame_schema(&schema, mode).map_err(codec_error)?; + let frame_schema = raw_series_frame_schema_with_ordering(&schema, mode, ordering)?; Ok(Box::pin(PackStream { source: Some(source), schema, @@ -238,7 +276,14 @@ impl Stream for PackStream { let batches = pack_raw_series_chunk(&this.schema, this.mode, &chunk) .map_err(codec_error)?; this.validator.validate(&chunk)?; - Ok(batches) + batches + .into_iter() + .map(|batch| { + batch + .with_schema(this.frame_schema.clone()) + .map_err(DataFusionError::from) + }) + .collect::>>() })(); match result { Ok(batches) => this.pending = batches.into_iter(), diff --git a/src/common/query/src/series_frame/tests.rs b/src/common/query/src/series_frame/tests.rs index c282a546e7c..ce955494b0c 100644 --- a/src/common/query/src/series_frame/tests.rs +++ b/src/common/query/src/series_frame/tests.rs @@ -14,7 +14,7 @@ mod lifecycle; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::io::Cursor; use std::pin::Pin; use std::sync::Arc; @@ -33,6 +33,7 @@ use datatypes::arrow::ipc::{reader::StreamReader, writer::StreamWriter}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::series::Label; use datatypes::series::MetricName; +use datatypes::series::frame::{RawLabelMode, raw_series_frame_schema}; use datatypes::series::raw::{RawSeriesChunk, RawSeriesOrdering, RawTimeAxis}; use datatypes::series::samples::{DenseSamplesRef, FieldSpec, Samples, SeriesFields, SeriesSchema}; use futures_util::{Stream, StreamExt}; @@ -40,7 +41,7 @@ use store_api::region_engine::{ BoundTag, RawLabelSource, RawSeriesStream, SendableRawSeriesStream, }; -use super::{pack_raw_series, unpack_raw_series}; +use super::{pack_raw_series, raw_series_frame_ordering, unpack_raw_series}; fn schema() -> Arc { Arc::new(SeriesSchema { @@ -1538,3 +1539,121 @@ async fn named_frame_fields_roundtrip_and_reject_wrong_bindings_before_polling() assert_eq!(drops.load(Ordering::SeqCst), 1); } } + +#[test] +fn raw_series_ordering_metadata_fixture() { + #[derive(serde::Deserialize)] + struct Case { + name: String, + metadata: HashMap, + ordering: Option, + } + + let cases: Vec = serde_json::from_str(include_str!( + "../../../../../tests/compatibility/wire/raw_series_ordering/v1_metadata.json" + )) + .unwrap(); + for case in cases { + let literal_ordering = match case.ordering.as_deref() { + Some("contiguous") => Some(RawSeriesOrdering::Contiguous), + Some("read_key_then_time") => Some(RawSeriesOrdering::ReadKeyThenTime), + Some(value) => panic!("{} has invalid fixture ordering {value}", case.name), + None => None, + }; + let frame_schema = raw_series_frame_schema(&schema(), RawLabelMode::Explicit).unwrap(); + let frame_schema = frame_schema.as_ref().clone().with_metadata(case.metadata); + match literal_ordering { + Some(expected) => assert_eq!( + raw_series_frame_ordering(&frame_schema) + .unwrap_or_else(|error| panic!("{}: {error}", case.name)), + expected, + "{}", + case.name + ), + None => assert!( + raw_series_frame_ordering(&frame_schema).is_err(), + "{}", + case.name + ), + } + } +} + +#[tokio::test] +async fn pack_declares_ordering_on_every_batch_and_ipc_roundtrips_it() { + for ordering in [ + RawSeriesOrdering::Contiguous, + RawSeriesOrdering::ReadKeyThenTime, + ] { + for chunks in [ + vec![ + chunk_with(b"a", &[1], vec![Some(1.0)], Some(metric()), false), + chunk_with(b"a", &[2], vec![None], Some(metric()), true), + chunk_with(b"b", &[3], vec![Some(3.0)], Some(metric()), true), + ], + vec![], + ] { + let is_empty = chunks.is_empty(); + let expected_batch_count = if is_empty { 0 } else { 3 }; + let canonical_schema = + raw_series_frame_schema(&schema(), RawLabelMode::Explicit).unwrap(); + let mut expected_metadata = canonical_schema.metadata().clone(); + expected_metadata.insert( + "greptime.series.ordering".to_string(), + match ordering { + RawSeriesOrdering::Contiguous => "contiguous", + RawSeriesOrdering::ReadKeyThenTime => "read_key_then_time", + } + .to_string(), + ); + let (input, _, _) = raw(chunks, ordering); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + assert_eq!(declared.fields(), canonical_schema.fields()); + assert_eq!(declared.metadata(), &expected_metadata); + assert_eq!(raw_series_frame_ordering(&declared).unwrap(), ordering); + let mut batches = Vec::new(); + while let Some(batch) = packed.next().await { + let batch = batch.unwrap(); + assert_eq!(batch.schema(), declared); + batches.push(batch); + } + + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &declared).unwrap(); + for batch in &batches { + writer.write(batch).unwrap(); + } + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(Cursor::new(ipc), None).unwrap(); + assert_eq!(reader.schema(), declared); + assert_eq!( + raw_series_frame_ordering(&reader.schema()).unwrap(), + ordering + ); + let ipc_batches = reader.map(Result::unwrap).collect::>(); + assert_eq!(ipc_batches.len(), batches.len()); + assert_eq!(ipc_batches.len(), expected_batch_count); + assert!(ipc_batches.iter().all(|batch| batch.schema() == declared)); + let (source, _, _) = df_source(ipc_batches, declared, false); + let mut decoded = + unpack_raw_series(source, schema(), RawLabelSource::Explicit, ordering).unwrap(); + if is_empty { + assert!(decoded.next().await.is_none()); + } else { + for (key, time, value, last) in [ + (b"a".as_slice(), 1, Some(1.0), false), + (b"a".as_slice(), 2, None, true), + (b"b".as_slice(), 3, Some(3.0), true), + ] { + let actual = decoded.next().await.unwrap().unwrap(); + assert_chunk(&actual, key, &[time], &[value], last); + assert_metric(&actual, None); + } + assert!(decoded.next().await.is_none()); + } + } + } +} diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index b2bc5a716ba..9098f207260 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -5350,6 +5350,10 @@ async fn test_mito_regional_raw_merge_preserves_global_key_order_and_labels() { } _ => panic!("PerSeries request must select a series scanner"), }; + assert_eq!( + RawSeriesOrdering::ReadKeyThenTime, + scanner.raw_series_ordering() + ); let metadata = scanner.metadata(); metadata_for_codec.get_or_insert_with(|| metadata.clone()); let source = RawLabelSource::PrimaryKey { @@ -5404,6 +5408,7 @@ async fn test_mito_regional_raw_merge_preserves_global_key_order_and_labels() { .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) .unwrap() .expect("native raw input"); + assert_eq!(scanner.raw_series_ordering(), stream.ordering()); assert_eq!(RawSeriesOrdering::ReadKeyThenTime, stream.ordering()); assert_eq!( vec!["field_1", "field_0"], @@ -5772,6 +5777,7 @@ async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { }; assert_eq!("two_phase", series.mode()); let mut scanner = engine.handle_query(region_id, request).await.unwrap(); + assert_eq!(RawSeriesOrdering::Contiguous, scanner.raw_series_ordering()); let metadata = scanner.metadata(); let source = RawLabelSource::PrimaryKey { metric_name: Arc::from("fixture_metric"), @@ -5808,6 +5814,7 @@ async fn test_two_phase_native_raw_stream_is_rejected_by_ordered_merge() { .scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source) .unwrap() .unwrap(); + assert_eq!(scanner.raw_series_ordering(), stream.ordering()); assert_eq!(RawSeriesOrdering::Contiguous, stream.ordering()); streams.push(stream); } diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index 1f304a2535a..d83fdf6ee44 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -769,6 +769,13 @@ impl RegionScanner for SeriesScan { .map_err(BoxedError::new) } + fn raw_series_ordering(&self) -> RawSeriesOrdering { + match self.mode { + SeriesScanMode::Legacy => RawSeriesOrdering::ReadKeyThenTime, + SeriesScanMode::TwoPhase => RawSeriesOrdering::Contiguous, + } + } + fn raw_series_schema( &self, label_source: &RawLabelSource, @@ -798,10 +805,7 @@ impl RegionScanner for SeriesScan { let batches = self .scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set) .map_err(BoxedError::new)?; - let ordering = match self.mode { - SeriesScanMode::Legacy => RawSeriesOrdering::ReadKeyThenTime, - SeriesScanMode::TwoPhase => RawSeriesOrdering::Contiguous, - }; + let ordering = self.raw_series_ordering(); Ok(Some(raw::make_stream( batches, preparation.schema, diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 1529859b420..811f05828ed 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -563,6 +563,11 @@ pub trait RegionScanner: Debug + DisplayAs + Send { Ok(None) } + /// Returns the guarantee for subsequent raw scans without consuming scanner state. + fn raw_series_ordering(&self) -> RawSeriesOrdering { + RawSeriesOrdering::Contiguous + } + /// Scans a partition as raw series when this source supports that path. /// /// `None` means raw capability is absent before execution and permits a legacy scan instead. diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 416e2f25d63..1228d94fc65 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -20,7 +20,7 @@ use std::time::Instant; use api::v1::SemanticType; use common_error::ext::BoxedError; use common_query::request::RawSeriesRequest; -use common_query::series_frame::pack_raw_series; +use common_query::series_frame::{pack_raw_series, raw_series_frame_schema_with_ordering}; use common_recordbatch::adapter::{ RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME, }; @@ -55,7 +55,7 @@ use datafusion_physical_expr::{ }; use datatypes::arrow::datatypes::SchemaRef as ArrowSchemaRef; use datatypes::compute::SortOptions; -use datatypes::series::frame::{RawLabelMode, raw_series_frame_schema}; +use datatypes::series::frame::RawLabelMode; use datatypes::series::samples::SeriesSchema; use futures::{Stream, StreamExt}; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; @@ -474,8 +474,11 @@ impl RegionScanExec { else { return Ok(None); }; - let arrow_schema = raw_series_frame_schema(&schema, raw_label_mode(&label_source)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; + let arrow_schema = raw_series_frame_schema_with_ordering( + &schema, + raw_label_mode(&label_source), + scanner.raw_series_ordering(), + )?; let partition_count = scanner.properties().num_partitions().max(1); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(arrow_schema.clone()), @@ -655,8 +658,12 @@ impl ExecutionPlan for SeriesScanExec { .ok_or_else(|| { DataFusionError::Execution("raw series capability changed after planning".into()) })?; - let current_frame = raw_series_frame_schema(¤t, raw_label_mode(&self.label_source)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; + let current_ordering = scanner.raw_series_ordering(); + let current_frame = raw_series_frame_schema_with_ordering( + ¤t, + raw_label_mode(&self.label_source), + current_ordering, + )?; if current_frame != self.arrow_schema || scanner.properties().num_partitions().max(1) != partitions { @@ -672,6 +679,11 @@ impl ExecutionPlan for SeriesScanExec { "raw series capability disappeared during execution".into(), ) })?; + if raw.ordering() != current_ordering { + return Err(DataFusionError::Execution( + "raw series stream ordering does not match its planned guarantee".into(), + )); + } if raw.schema().fields.len() != self.series_schema.fields.len() || raw .schema() diff --git a/src/table/src/table/scan/series_tests.rs b/src/table/src/table/scan/series_tests.rs index a90965baf8a..6613d990d9c 100644 --- a/src/table/src/table/scan/series_tests.rs +++ b/src/table/src/table/scan/series_tests.rs @@ -20,6 +20,7 @@ use std::task::{Context, Poll}; use api::v1::SemanticType; use common_error::ext::BoxedError; use common_query::request::RawSeriesRequest; +use common_query::series_frame::raw_series_frame_ordering; use common_recordbatch::{ QueryMemoryTracker, RecordBatch, RecordBatches, SendableRecordBatchStream, }; @@ -62,6 +63,8 @@ struct State { polls: usize, drops: usize, resets: usize, + planned_ordering: Option, + stream_ordering: Option, } fn raw_error(reason: &str) -> BoxedError { @@ -81,6 +84,7 @@ struct RawStream { state: Arc>, fail_first_poll: bool, error_after_poll: Option, + ordering: RawSeriesOrdering, } impl Drop for RawStream { @@ -112,7 +116,7 @@ impl RawSeriesStream for RawStream { &self.source } fn ordering(&self) -> RawSeriesOrdering { - RawSeriesOrdering::ReadKeyThenTime + self.ordering } } @@ -149,6 +153,13 @@ impl RegionScanner for TestScanner { fn metadata(&self) -> store_api::metadata::RegionMetadataRef { self.metadata.clone() } + fn raw_series_ordering(&self) -> RawSeriesOrdering { + self.state + .lock() + .unwrap() + .planned_ordering + .unwrap_or(RawSeriesOrdering::ReadKeyThenTime) + } fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> { self.properties.prepare(request); Ok(()) @@ -188,7 +199,11 @@ impl RegionScanner for TestScanner { if state.raw_none { return Ok(None); } + let ordering = state + .stream_ordering + .unwrap_or(RawSeriesOrdering::ReadKeyThenTime); Ok(Some(Box::pin(RawStream { + ordering, schema: state .stream_schema .clone() @@ -402,14 +417,16 @@ async fn supported_empty_stream_remains_native_with_declared_frame_schema() { .unwrap() .unwrap(); let mut stream = plan.execute(0, context()).unwrap(); + assert_eq!(stream.schema(), plan.schema()); assert!(stream.next().await.is_none()); assert_eq!(state.lock().unwrap().drops, 1); drop(stream); assert_eq!( plan.schema(), - datatypes::series::frame::raw_series_frame_schema( + raw_series_frame_schema_with_ordering( plan.series_schema(), - RawLabelMode::Explicit + RawLabelMode::Explicit, + RawSeriesOrdering::ReadKeyThenTime ) .unwrap() ); @@ -418,6 +435,123 @@ async fn supported_empty_stream_remains_native_with_declared_frame_schema() { assert_eq!(state.legacy_calls, 0); } +#[tokio::test] +async fn planned_ordering_is_preserved_for_empty_and_nonempty_frames() { + for ordering in [ + RawSeriesOrdering::ReadKeyThenTime, + RawSeriesOrdering::Contiguous, + ] { + for nonempty in [false, true] { + let schema = series_schema(); + let chunks = if nonempty { + vec![chunk(&schema)] + } else { + vec![] + }; + let (scan, state) = fixture(Some(schema), chunks); + { + let mut state = state.lock().unwrap(); + state.planned_ordering = Some(ordering); + state.stream_ordering = Some(ordering); + } + let plan = scan + .clone() + .try_to_series_scan(RawLabelSource::Explicit) + .unwrap() + .unwrap(); + let planned_schema = plan.schema(); + assert_eq!( + ordering, + raw_series_frame_ordering(&planned_schema).unwrap() + ); + { + let state = state.lock().unwrap(); + assert_eq!(0, state.raw_calls); + assert_eq!(0, state.polls); + assert_eq!(0, state.legacy_calls); + } + let stream = plan.execute(0, context()).unwrap(); + assert_eq!(stream.schema(), planned_schema); + assert_eq!( + plan.properties().equivalence_properties().schema(), + &planned_schema + ); + assert_eq!( + ordering, + raw_series_frame_ordering(stream.schema().as_ref()).unwrap() + ); + let frames = stream.try_collect::>().await.unwrap(); + assert_eq!(usize::from(nonempty), frames.len()); + for frame in &frames { + assert_eq!(planned_schema.as_ref(), frame.schema().as_ref()); + assert_eq!( + ordering, + raw_series_frame_ordering(frame.schema().as_ref()).unwrap() + ); + } + let state = state.lock().unwrap(); + assert_eq!(1, state.raw_calls); + assert_eq!(0, state.legacy_calls); + } + } +} + +#[tokio::test] +async fn planned_and_stream_ordering_mismatches_fail_without_legacy_fallback() { + for (planned, actual) in [ + ( + RawSeriesOrdering::ReadKeyThenTime, + RawSeriesOrdering::Contiguous, + ), + ( + RawSeriesOrdering::Contiguous, + RawSeriesOrdering::ReadKeyThenTime, + ), + ] { + let schema = series_schema(); + let (scan, state) = fixture(Some(schema.clone()), vec![chunk(&schema)]); + state.lock().unwrap().planned_ordering = Some(planned); + let plan = scan + .clone() + .try_to_series_scan(RawLabelSource::Explicit) + .unwrap() + .unwrap(); + assert_eq!( + planned, + raw_series_frame_ordering(plan.schema().as_ref()).unwrap() + ); + state.lock().unwrap().stream_ordering = Some(actual); + let error = plan + .execute(0, context()) + .err() + .expect("ordering mismatch rejected before returning stream"); + assert!(error.to_string().contains("ordering"), "{error}"); + let state = state.lock().unwrap(); + assert_eq!(1, state.raw_calls); + assert_eq!(0, state.polls); + assert_eq!(1, state.drops); + assert_eq!(0, state.legacy_calls); + } +} + +#[tokio::test] +async fn ordering_changed_after_planning_fails_before_raw_execution() { + let schema = series_schema(); + let (scan, state) = fixture(Some(schema), vec![]); + let plan = scan + .clone() + .try_to_series_scan(RawLabelSource::Explicit) + .unwrap() + .unwrap(); + state.lock().unwrap().planned_ordering = Some(RawSeriesOrdering::Contiguous); + assert!(plan.execute(0, context()).is_err()); + let state = state.lock().unwrap(); + assert_eq!(0, state.raw_calls); + assert_eq!(0, state.polls); + assert_eq!(0, state.drops); + assert_eq!(0, state.legacy_calls); +} + #[tokio::test] async fn default_scanner_unsupported_native_preserves_two_column_row() { let schema = Arc::new(Schema::new(vec![ diff --git a/tests-integration/src/tests/nested_merge_scan_capability_test.rs b/tests-integration/src/tests/nested_merge_scan_capability_test.rs index 705117713c3..2adf72da179 100644 --- a/tests-integration/src/tests/nested_merge_scan_capability_test.rs +++ b/tests-integration/src/tests/nested_merge_scan_capability_test.rs @@ -982,7 +982,7 @@ async fn test_native_single_region_raw_flight_preserves_typed_filter_and_snapsho } RawLabelSource::Explicit => panic!("expected key-backed source"), } - assert_eq!(RawSeriesOrdering::Contiguous, raw.ordering()); + assert_eq!(RawSeriesOrdering::ReadKeyThenTime, raw.ordering()); assert_eq!(PrimaryKeyEncoding::Dense, metadata.primary_key_encoding); assert_eq!(&[host_id], metadata.primary_key.as_slice()); let expected_key = new_primary_key(&["alpha"]); @@ -1209,6 +1209,7 @@ async fn assert_raw_entrypoint_wrapper_contract( ) { use common_base::Plugins; use common_query::OutputData; + use common_query::series_frame::raw_series_frame_ordering; use datafusion::arrow::datatypes::DataType; use datafusion::common::TableReference; use datafusion::datasource::DefaultTableSource; @@ -1218,6 +1219,7 @@ async fn assert_raw_entrypoint_wrapper_contract( use datafusion::physical_plan::coop::CooperativeExec; use datafusion::physical_plan::execution_plan::SchedulingType; use datafusion_expr::{col, lit}; + use datatypes::series::raw::RawSeriesOrdering; use query::dummy_catalog::DummyTableProviderFactory; use query::options::QueryOptions; use query::physical_wrapper::{PhysicalPlanWrapper, PhysicalPlanWrapperRef}; @@ -1343,6 +1345,10 @@ async fn assert_raw_entrypoint_wrapper_contract( let native_schema = native_batches.schema(); let native_schema = native_schema.arrow_schema(); assert_eq!(native_root_schema.as_ref(), native_schema.as_ref()); + assert_eq!( + RawSeriesOrdering::ReadKeyThenTime, + raw_series_frame_ordering(native_schema).unwrap() + ); assert_eq!( vec!["read_key", "is_last", "time", "fields"], native_schema @@ -1720,7 +1726,7 @@ async fn test_native_histogram_raw_flight_preserves_payload_across_flush() { } RawLabelSource::Explicit => panic!("expected key-backed source"), } - assert_eq!(RawSeriesOrdering::Contiguous, stream.ordering()); + assert_eq!(RawSeriesOrdering::ReadKeyThenTime, stream.ordering()); let chunks = stream.try_collect::>().await.unwrap(); let mut timestamps = Vec::new(); for (chunk_index, chunk) in chunks.iter().enumerate() { diff --git a/tests/compatibility/wire/raw_series_ordering/README.md b/tests/compatibility/wire/raw_series_ordering/README.md new file mode 100644 index 00000000000..630dc25e2a2 --- /dev/null +++ b/tests/compatibility/wire/raw_series_ordering/README.md @@ -0,0 +1,19 @@ +# Raw-series ordering schema metadata compatibility + +`v1_metadata.json` is a hand-authored, frozen set of Arrow schema metadata maps +for the v1 raw-series frame. It records the established layout/content/labels/ +time metadata and the new optional ordering entry. The Rust unit test parses +these literal maps through `raw_series_frame_ordering`; the fixture is not +produced by the schema builder. + +Run the focused check: + +```shell +cargo nextest run -p common-query -E 'test(raw_series_ordering_metadata_fixture)' +``` + +The fixture proves that absent ordering metadata defaults to `Contiguous`, the +two known values decode, and an unknown value is rejected. It does not prove +interoperability with an old binary, nor does it test an end-to-end client or +service. Separate pack/IPC tests check the declared ordering schema and batch +schema agreement for both orderings, including empty streams. diff --git a/tests/compatibility/wire/raw_series_ordering/v1_metadata.json b/tests/compatibility/wire/raw_series_ordering/v1_metadata.json new file mode 100644 index 00000000000..c5b3c0ea69b --- /dev/null +++ b/tests/compatibility/wire/raw_series_ordering/v1_metadata.json @@ -0,0 +1,45 @@ +[ + { + "name": "missing_defaults_to_contiguous", + "metadata": { + "greptime.series.layout": "v1", + "greptime.series.content": "raw", + "greptime.series.labels": "explicit", + "greptime.series.time": "timestamps" + }, + "ordering": "contiguous" + }, + { + "name": "known_contiguous", + "metadata": { + "greptime.series.layout": "v1", + "greptime.series.content": "raw", + "greptime.series.labels": "explicit", + "greptime.series.time": "timestamps", + "greptime.series.ordering": "contiguous" + }, + "ordering": "contiguous" + }, + { + "name": "known_read_key_then_time", + "metadata": { + "greptime.series.layout": "v1", + "greptime.series.content": "raw", + "greptime.series.labels": "explicit", + "greptime.series.time": "timestamps", + "greptime.series.ordering": "read_key_then_time" + }, + "ordering": "read_key_then_time" + }, + { + "name": "unknown_ordering_rejected", + "metadata": { + "greptime.series.layout": "v1", + "greptime.series.content": "raw", + "greptime.series.labels": "explicit", + "greptime.series.time": "timestamps", + "greptime.series.ordering": "future_value" + }, + "ordering": null + } +]