diff --git a/tests-integration/src/cluster.rs b/tests-integration/src/cluster.rs index e74a53b21bb..b574f90f21b 100644 --- a/tests-integration/src/cluster.rs +++ b/tests-integration/src/cluster.rs @@ -69,8 +69,9 @@ use meta_srv::mocks::MockInfo; use mito2::gc::GcConfig; use mito2::region::MitoRegionRef; use object_store::config::ObjectStoreConfig; +use query::options::QueryOptions; use rand::Rng; -use servers::grpc::flight::FlightCraftWrapper; +use servers::grpc::flight::{FlightCraftRef, FlightCraftWrapper}; use servers::grpc::region_server::RegionServerRequestHandler; use servers::grpc::{GrpcOptions, HealthCheckHandler}; use servers::server::ServerHandlers; @@ -88,14 +89,18 @@ use crate::test_util::{ create_tmp_dir_and_datanode_opts, }; -/// Flight `DoGet` requests another node sent to a datanode over its network address (see +/// Flight requests another node sent to a datanode over its network address (see /// [`GreptimeDbClusterBuilder::with_real_datanode_grpc_addr`]). /// -/// The frontend and datanodes inside the test process use in-process clients, so counted requests -/// come from remote nodes querying regions owned by this datanode. +/// The datanodes inside the test process, and the frontend unless it opts into real clients (see +/// [`GreptimeDbClusterBuilder::with_real_frontend_clients`]), use in-process clients whose duplex +/// streams are not counted. Counted requests therefore come from the nodes that dial the real +/// listener: a datanode querying regions owned by another datanode, or a frontend that opted into +/// real clients. #[derive(Debug, Default)] pub struct DatanodeRpcStats { do_get_requests: AtomicUsize, + do_action_requests: AtomicUsize, } impl DatanodeRpcStats { @@ -103,6 +108,12 @@ impl DatanodeRpcStats { pub fn requests(&self) -> usize { self.do_get_requests.load(Ordering::Relaxed) } + + /// The number of Flight `DoAction` requests another node sent to the datanode, e.g. the named + /// raw-series preflight of the native PromQL path. + pub fn prepare_requests(&self) -> usize { + self.do_action_requests.load(Ordering::Relaxed) + } } pub struct GreptimeDbCluster { @@ -192,6 +203,15 @@ impl GreptimeDbCluster { } } +/// Builds the Flight handler that serves a datanode at its real network address. +/// +/// The hook receives the node id and the region server of the datanode, and the handler it +/// returns serves every Flight request that reaches the real TCP listener of the datanode; the +/// in-process duplex listener keeps serving the bare region server (see +/// [`GreptimeDbClusterBuilder::with_datanode_flight_hook`]). +type DatanodeFlightHook = + dyn Fn(DatanodeId, datanode::region_server::RegionServer) -> FlightCraftRef + Send + Sync; + pub struct GreptimeDbClusterBuilder { cluster_name: String, kv_backend: KvBackendRef, @@ -209,6 +229,9 @@ pub struct GreptimeDbClusterBuilder { local_file_access: LocalFileAccess, event_recorder_options: EventRecorderOptions, real_datanode_grpc_addr: bool, + real_frontend_clients: bool, + frontend_query_options: QueryOptions, + datanode_flight_hook: Option>, } impl GreptimeDbClusterBuilder { @@ -247,6 +270,9 @@ impl GreptimeDbClusterBuilder { local_file_access: LocalFileAccess::default(), event_recorder_options: EventRecorderOptions::default(), real_datanode_grpc_addr: false, + real_frontend_clients: false, + frontend_query_options: QueryOptions::default(), + datanode_flight_hook: None, } } @@ -347,6 +373,47 @@ impl GreptimeDbClusterBuilder { self } + /// Serves the frontend with its own clients that dial the real datanode addresses, instead of + /// the in-process duplex clients that every other in-process node uses. + /// + /// By default the frontend keeps the in-process clients, so its requests stay out of + /// [`DatanodeRpcStats`]. Opting in makes the frontend reach the datanodes over the network, + /// where both its Flight `DoGet` reads and its Flight `DoAction` named raw-series preflight + /// are counted. This requires [`Self::with_real_datanode_grpc_addr`] to be enabled: the + /// datanode addresses of the table routes must be real listeners. + /// + /// The metasrv, the datanodes and the information extension keep the shared in-process + /// clients; only the query engine of the frontend receives these clients. + #[must_use] + pub fn with_real_frontend_clients(mut self, real_frontend_clients: bool) -> Self { + self.real_frontend_clients = real_frontend_clients; + self + } + + /// Sets the [`QueryOptions`] of the frontend query engine. + /// + /// The datanodes keep the options they are built with, exactly like a real deployment where + /// the planning node is configured on its own. + #[must_use] + pub fn with_frontend_query_options(mut self, frontend_query_options: QueryOptions) -> Self { + self.frontend_query_options = frontend_query_options; + self + } + + /// Replaces the Flight handler that serves the region server of every datanode at its real + /// network address (see [`Self::with_real_datanode_grpc_addr`]). + /// + /// The hook is invoked once per datanode with its node id and its region server, and the + /// handler it returns serves every Flight request that reaches the real TCP listener. The + /// in-process duplex listener keeps serving the bare region server, so the hook does not + /// change the traffic of the in-process clients. Leave the hook unset to serve the bare + /// region server everywhere. + #[must_use] + pub fn with_datanode_flight_hook(mut self, hook: Arc) -> Self { + self.datanode_flight_hook = Some(hook); + self + } + pub async fn build_with( &self, datanode_options: Vec, @@ -355,8 +422,15 @@ impl GreptimeDbClusterBuilder { ) -> GreptimeDbCluster { let datanodes = datanode_options.len(); + assert!( + !self.real_frontend_clients || self.real_datanode_grpc_addr, + "with_real_frontend_clients(true) requires with_real_datanode_grpc_addr(true): the \ + real frontend clients dial the datanode addresses recorded in the table routes, which \ + only exist when every datanode is served at its own address" + ); + let channel_config = ChannelConfig::new().timeout(Some(Duration::from_secs(20))); - let datanode_clients = Arc::new(NodeClients::new(channel_config)); + let datanode_clients = Arc::new(NodeClients::new(channel_config.clone())); let opt = MetasrvOptions { procedure: ProcedureConfig { @@ -408,17 +482,30 @@ impl GreptimeDbClusterBuilder { &datanode_instances, &datanode_options, &datanode_rpc_stats, + self.datanode_flight_hook.as_deref(), ) .await; self.wait_datanodes_alive(metasrv.metasrv.meta_peer_client(), datanodes) .await; + // The frontend keeps the shared in-process clients by default. A frontend that must really + // reach the datanodes gets its own clients built from the same channel configuration: the + // shared clients have mock connectors registered for every datanode address (see + // `create_datanode_client`), but these fresh managers have none, so the frontend dials the + // real listeners and its requests are counted. + let frontend_node_clients = if self.real_frontend_clients { + Arc::new(NodeClients::new(channel_config)) + } else { + datanode_clients.clone() + }; + let mut frontend = self .build_frontend( metasrv.clone(), datanode_clients.clone(), start_frontend_servers, + frontend_node_clients, ) .await; @@ -574,6 +661,7 @@ impl GreptimeDbClusterBuilder { metasrv: MockInfo, datanode_clients: Arc, start_frontend_servers: bool, + frontend_node_clients: Arc, ) -> Frontend { let mut meta_client = MetaClientBuilder::frontend_default_options() .channel_manager(metasrv.channel_manager) @@ -619,7 +707,7 @@ impl GreptimeDbClusterBuilder { cached_meta_backend.clone(), cache_registry.clone(), catalog_manager, - datanode_clients, + frontend_node_clients, meta_client.clone(), Arc::new(ProcessManager::new(fe_opts.grpc.server_addr.clone(), None)), ) @@ -653,6 +741,7 @@ impl GreptimeDbClusterBuilder { let mut fe_opts = FrontendOptions { auto_create_table: self.frontend_auto_create_table, event_recorder: self.event_recorder_options.clone(), + query: self.frontend_query_options.clone(), ..Default::default() }; @@ -710,14 +799,17 @@ async fn build_datanode_clients( instances: &HashMap, options: &[DatanodeOptions], rpc_stats: &HashMap>, + flight_hook: Option<&DatanodeFlightHook>, ) { for opts in options { let datanode_id = opts.node_id.unwrap(); let instance = &instances[&datanode_id]; let (addr, client) = create_datanode_client( instance, + datanode_id, &opts.grpc.server_addr, rpc_stats.get(&datanode_id).cloned(), + flight_hook, ) .await; clients @@ -728,10 +820,14 @@ async fn build_datanode_clients( /// Runs a gRPC server that serves the region server of `datanode` over `incoming` until the /// cluster is dropped. +/// +/// `flight_craft` replaces the Flight handler that serves the region server; `None` serves the +/// bare region server. fn serve_datanode_region_server( datanode: &Datanode, incoming: I, rpc_stats: Option>, + flight_craft: Option, ) where I: futures::Stream> + Send + 'static, IO: AsyncRead + AsyncWrite + Connected + Unpin + Send + 'static, @@ -742,7 +838,8 @@ fn serve_datanode_region_server( .build() .unwrap(); - let flight_handler = FlightCraftWrapper(datanode.region_server()); + let flight_handler = + FlightCraftWrapper(flight_craft.unwrap_or_else(|| Arc::new(datanode.region_server()))); let region_server_handler = RegionServerRequestHandler::new(Arc::new(datanode.region_server()), runtime); @@ -771,30 +868,39 @@ fn serve_datanode_region_server( /// Serves the region server of `datanode` and returns the address and the client of the address. /// -/// The returned client is always an in-process client: the frontend and the datanodes of the test -/// process reach the region server through a duplex stream, no matter which address they use. This -/// keeps the in-process traffic out of `rpc_stats`. +/// The returned client is always an in-process client. The datanodes of the test process, and the +/// frontend unless it opts into real clients +/// ([`GreptimeDbClusterBuilder::with_real_frontend_clients`]), reach the region server through a +/// duplex stream, no matter which address they use. This keeps that in-process traffic out of +/// `rpc_stats`. /// /// [`test_util::PEER_PLACEHOLDER_ADDR`] is not a real address, so it cannot be served over the /// network at all. Any other address is a real one: the region server is additionally served on -/// its local TCP port (`rpc_stats` counts the requests of the remote nodes that reach it, e.g. the -/// region query that a datanode sends for the regions of another datanode). +/// its local TCP port (`rpc_stats` counts the requests of the nodes that dial it, e.g. the region +/// query that a datanode sends for the regions of another datanode, or a request of a frontend +/// configured with real clients), and `flight_hook` builds the handler of that listener. async fn create_datanode_client( datanode: &Datanode, + datanode_id: DatanodeId, addr: &str, rpc_stats: Option>, + flight_hook: Option<&DatanodeFlightHook>, ) -> (String, Client) { let (client, server) = tokio::io::duplex(1024); serve_datanode_region_server( datanode, futures::stream::iter(vec![Ok::<_, std::io::Error>(server)]), None, + None, ); if addr != test_util::PEER_PLACEHOLDER_ADDR { let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener); - serve_datanode_region_server(datanode, incoming, rpc_stats); + // Only the real TCP listener is instrumented: the in-process duplex listener above keeps + // serving the bare region server, and the hook is invoked once for the listener. + let flight_craft = flight_hook.map(|hook| hook(datanode_id, datanode.region_server())); + serve_datanode_region_server(datanode, incoming, rpc_stats, flight_craft); } let mut client = Some(client); @@ -822,7 +928,7 @@ async fn create_datanode_client( ) } -/// Counts Flight `DoGet` requests received by the wrapped server. +/// Counts Flight `DoGet` and `DoAction` requests received by the wrapped server. #[derive(Clone)] struct CountRequests { inner: S, @@ -842,10 +948,16 @@ where } fn call(&mut self, request: http::Request) -> Self::Future { - if request.uri().path() == "/arrow.flight.protocol.FlightService/DoGet" - && let Some(rpc_stats) = &self.rpc_stats - { - rpc_stats.do_get_requests.fetch_add(1, Ordering::Relaxed); + if let Some(rpc_stats) = &self.rpc_stats { + match request.uri().path() { + "/arrow.flight.protocol.FlightService/DoGet" => { + rpc_stats.do_get_requests.fetch_add(1, Ordering::Relaxed); + } + "/arrow.flight.protocol.FlightService/DoAction" => { + rpc_stats.do_action_requests.fetch_add(1, Ordering::Relaxed); + } + _ => {} + } } self.inner.call(request) diff --git a/tests-integration/src/grpc/flight.rs b/tests-integration/src/grpc/flight.rs index e74d4d5bf70..64072886585 100644 --- a/tests-integration/src/grpc/flight.rs +++ b/tests-integration/src/grpc/flight.rs @@ -19,14 +19,16 @@ mod test { use std::collections::HashMap; use std::net::SocketAddr; use std::pin::Pin; - use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use api::v1::auth_header::AuthScheme; use api::v1::greptime_request::Request as GreptimeQueryRequest; use api::v1::health_check_server::HealthCheckServer; use api::v1::query_request::Query; + use api::v1::region::RegionRequestHeader; use api::v1::{Basic, ColumnDataType, ColumnDef, CreateTableExpr, QueryRequest, SemanticType}; use arrow_flight::flight_service_server::FlightServiceServer; use arrow_flight::{FlightData, FlightDescriptor, Ticket}; @@ -41,17 +43,21 @@ mod test { use common_grpc::flight::do_put::{DoPutMetadata, DoPutResponse}; use common_grpc::flight::{FlightDecoder, FlightEncoder, FlightMessage}; use common_meta::peer::Peer; + use common_query::request::{QueryRequest as LogicalQueryRequest, RawSeriesRequest}; use common_query::{Output, OutputData}; use common_recordbatch::adapter::RegionWatermarkEntry; use common_recordbatch::{ RecordBatch, RecordBatchStreamWrapper, RecordBatches, SendableRecordBatchStream, }; use common_telemetry::tracing_context::TracingContext; + use datafusion_expr::LogicalPlan; use datatypes::arrow::datatypes::{ DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit, }; use datatypes::prelude::{ConcreteDataType, ScalarVector, VectorRef}; use datatypes::schema::{ColumnSchema, Schema}; + use datatypes::series::SeriesOrdering; + use datatypes::series::frame::{RawLabelMode, raw_series_frame_schema}; use datatypes::vectors::{Int32Vector, StringVector, TimestampMillisecondVector}; use futures_util::{Stream, StreamExt}; use hyper_util::rt::TokioIo; @@ -69,6 +75,7 @@ mod test { use session::context::QueryContextRef; use session::hints::INSERT_SKIP_WAL_HINT; use tokio::net::TcpListener; + use tokio::sync::oneshot; use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream}; use tonic::transport::Server as TonicServer; use tonic::{Response, Status}; @@ -88,6 +95,36 @@ mod test { struct ErrorFlightCraft; + struct PendingFlightDataStream { + first: Option, + released: Option>, + } + + impl Stream for PendingFlightDataStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + match self.first.take() { + Some(first) => Poll::Ready(Some(Ok(first))), + None => Poll::Pending, + } + } + } + + impl Drop for PendingFlightDataStream { + fn drop(&mut self) { + if let Some(released) = self.released.take() { + let _ = released.send(()); + } + } + } + + struct PendingRawSeriesFlightCraft { + first: FlightData, + released: Mutex>>, + do_get_count: Arc, + } + struct SlowRemoteQueryHandler { region_requester: RegionRequester, } @@ -109,6 +146,21 @@ mod test { .as_stream() } + #[async_trait::async_trait] + impl FlightCraft for PendingRawSeriesFlightCraft { + async fn do_get( + &self, + _: tonic::Request, + ) -> std::result::Result>, tonic::Status> { + self.do_get_count.fetch_add(1, Ordering::SeqCst); + let stream = PendingFlightDataStream { + first: Some(self.first.clone()), + released: self.released.lock().unwrap().take(), + }; + Ok(Response::new(Box::pin(stream))) + } + } + #[async_trait::async_trait] impl FlightCraft for SlowFlightCraft { async fn do_get( @@ -335,6 +387,78 @@ mod test { server_result.unwrap().unwrap(); } + #[rstest] + #[case::missing_ordering(false)] + #[case::unknown_ordering(true)] + #[tokio::test(flavor = "multi_thread")] + async fn test_raw_series_query_ordering_errors_drop_transport_stream( + #[case] unknown_ordering: bool, + ) { + let binding = RawSeriesRequest::from_extension_value(include_str!( + "../../../tests/compatibility/wire/raw_series_request/v1_request.json" + )) + .unwrap(); + let (schema, _) = binding + .bind(Arc::new(binding.physical_metadata.clone())) + .unwrap(); + let arrow_schema = raw_series_frame_schema(&schema, RawLabelMode::Key).unwrap(); + let arrow_schema = if unknown_ordering { + let mut metadata = arrow_schema.metadata().clone(); + metadata.insert( + "greptime.series.ordering".to_string(), + "future_value".to_string(), + ); + ArrowSchema::new_with_metadata(arrow_schema.fields().clone(), metadata) + } else { + arrow_schema.as_ref().clone() + }; + let first = FlightEncoder::default().encode_schema(&arrow_schema); + + let (released_tx, released_rx) = oneshot::channel(); + let do_get_count = Arc::new(AtomicUsize::new(0)); + let client = client_for_flight_craft( + "raw-series-ordering", + PendingRawSeriesFlightCraft { + first, + released: Mutex::new(Some(released_tx)), + do_get_count: do_get_count.clone(), + }, + ); + let requester = RegionRequester::new(client.clone(), false, false); + let request = LogicalQueryRequest { + header: Some(RegionRequestHeader::default()), + region_id: binding.physical_metadata.region_id, + plan: LogicalPlan::default(), + }; + let result = requester.handle_raw_series_query(request, binding).await; + + if unknown_ordering { + let error = result + .err() + .expect("unknown ordering must reject the raw stream"); + assert!( + error + .root_cause() + .expect("ordering error cause") + .to_string() + .contains("unknown raw series ordering"), + "expected unknown-ordering error, got {error:?}" + ); + } else { + let raw = result.expect("missing ordering defaults to contiguous"); + assert_eq!(SeriesOrdering::Contiguous, raw.ordering()); + drop(raw); + } + + tokio::time::timeout(Duration::from_secs(2), released_rx) + .await + .expect("returned raw-series stream should be dropped") + .expect("the stream drop acknowledgement should be sent"); + assert_eq!(1, do_get_count.load(Ordering::SeqCst)); + drop(requester); + drop(client); + } + #[tokio::test(flavor = "multi_thread")] async fn test_do_get_timeout_does_not_cancel_slow_flight_stream() { let client = client_for_flight_craft("slow-flight", SlowFlightCraft); diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs index 074be282543..b2532c89618 100644 --- a/tests-integration/src/standalone.rs +++ b/tests-integration/src/standalone.rs @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(test)] +#[path = "standalone/native_promql_tests.rs"] +mod native_promql_tests; + use std::sync::Arc; use std::time::Duration; @@ -91,6 +95,7 @@ pub struct GreptimeDbStandaloneBuilder { logical_batcher: Option, table_batcher: BatcherOptions, mito_config: Option, + query_options: Option, } impl GreptimeDbStandaloneBuilder { @@ -112,9 +117,17 @@ impl GreptimeDbStandaloneBuilder { logical_batcher: None, table_batcher: BatcherOptions::default(), mito_config: None, + query_options: None, } } + /// Overrides the query options for this test instance. + #[must_use] + pub fn with_query_options(mut self, options: query::options::QueryOptions) -> Self { + self.query_options = Some(options); + self + } + /// Overrides the Mito configuration for this test instance. #[must_use] pub fn with_mito_config(mut self, config: mito2::config::MitoConfig) -> Self { @@ -401,6 +414,10 @@ impl GreptimeDbStandaloneBuilder { ..StandaloneOptions::default() }; + if let Some(query_options) = &self.query_options { + standalone_opts.query = query_options.clone(); + } + if let Some(config) = &self.mito_config { for engine in &mut standalone_opts.region_engine { if let datanode::config::RegionEngineConfig::Mito(mito) = engine { @@ -420,3 +437,402 @@ impl GreptimeDbStandaloneBuilder { .await } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use api::region::RegionResponse; + use api::v1::region::{ + ListMetadataRequest, RegionRequest, RegionRequestHeader, region_request, + }; + use api::v1::{QueryContext as ProtoQueryContext, SnapshotSequences}; + use common_meta::error::Result as MetaResult; + use common_meta::node_manager::{Datanode, bind_raw_series_query}; + use common_meta::peer::Peer; + use common_query::request::{ + QueryRequest, RAW_SERIES_REQUEST_EXTENSION_KEY, RawSeriesRequest, RawSeriesTag, + }; + use common_recordbatch::SendableRecordBatchStream; + use datafusion::common::{ScalarValue, TableReference}; + use datafusion::logical_expr::TableSource; + use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, col, lit}; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::SampleRef; + use frontend::instance::Instance; + use futures_util::TryStreamExt; + use mito2::test_util::sst_util::new_primary_key; + use query::parser::QueryLanguageParser; + use session::context::{QueryContext, QueryContextRef}; + use store_api::metadata::RegionMetadata; + use store_api::region_engine::RawLabelSource; + + use super::GreptimeDbStandaloneBuilder; + use crate::test_util::execute_sql; + + struct NoExecutionDatanode; + + #[async_trait::async_trait] + impl Datanode for NoExecutionDatanode { + async fn handle_request(&self, _request: Arc) -> MetaResult { + panic!("unexpected handle_request") + } + + async fn handle_query( + &self, + _request: QueryRequest, + ) -> MetaResult { + panic!("default prepare must not execute a query") + } + } + + #[tokio::test] + async fn test_raw_series_binding_and_default_prepare_contract() { + let binding: RawSeriesRequest = serde_json::from_str(include_str!( + "../../tests/compatibility/wire/raw_series_request/v1_request.json" + )) + .unwrap(); + let header = RegionRequestHeader { + tracing_context: std::collections::HashMap::from([( + "traceparent".to_string(), + "00-11111111111111111111111111111111-2222222222222222-01".to_string(), + )]), + query_context: Some(ProtoQueryContext { + current_catalog: "custom_catalog".to_string(), + current_schema: "custom_schema".to_string(), + timezone: "Asia/Shanghai".to_string(), + channel: common_base::protocol::Channel::Mysql as u32, + snapshot_seqs: Some(SnapshotSequences { + snapshot_seqs: std::collections::HashMap::from([( + binding.physical_metadata.region_id.as_u64(), + 77, + )]), + sst_min_sequences: std::collections::HashMap::new(), + }), + extensions: std::collections::HashMap::from([ + ("raw-series-unrelated".to_string(), "preserved".to_string()), + ( + session::hints::READ_PREFERENCE_EXTENSION_KEY.to_string(), + "follower".to_string(), + ), + ]), + explain: None, + }), + ..Default::default() + }; + let request = || QueryRequest { + header: Some(header.clone()), + region_id: binding.physical_metadata.region_id, + plan: LogicalPlanBuilder::empty(false).build().unwrap(), + }; + let original_header = request().header.unwrap(); + let (bound, schema, labels) = bind_raw_series_query(request(), &binding).unwrap(); + assert_eq!( + vec!["aux", "value"], + schema + .fields + .iter() + .map(|f| f.name.as_ref()) + .collect::>() + ); + match labels { + RawLabelSource::PrimaryKey { + metric_name, + logical_tags, + .. + } => { + assert_eq!("cpu", metric_name.as_ref()); + assert_eq!(1, logical_tags.len()); + assert_eq!(1, logical_tags[0].column_id); + assert_eq!("host", logical_tags[0].name.as_ref()); + } + RawLabelSource::Explicit => panic!("expected key-backed source"), + } + let mut bound_header = bound.header.unwrap(); + let extension = bound_header + .query_context + .as_mut() + .unwrap() + .extensions + .remove(RAW_SERIES_REQUEST_EXTENSION_KEY) + .unwrap(); + assert_eq!(binding.to_extension_value().unwrap(), extension); + assert_eq!(original_header, bound_header); + + let datanode = NoExecutionDatanode; + let mut invalid = binding.clone(); + invalid.version = 42; + assert_eq!( + None, + datanode + .prepare_raw_series_query(request(), invalid) + .await + .unwrap() + ); + let mut mismatch = request(); + mismatch.region_id = store_api::storage::RegionId::from_u64( + binding.physical_metadata.region_id.as_u64() + 1, + ); + let error = bind_raw_series_query(mismatch, &binding).unwrap_err(); + assert!(format!("{error:?}").contains("region does not match")); + let mut invalid = binding.clone(); + invalid.version = 42; + let error = bind_raw_series_query(request(), &invalid).unwrap_err(); + assert!(format!("{error:?}").contains("Invalid raw-series request")); + let mut invalid_field = binding.clone(); + invalid_field.field_ids = vec![u32::MAX]; + let error = bind_raw_series_query(request(), &invalid_field).unwrap_err(); + assert!(format!("{error:?}").contains("Invalid raw-series fields")); + let mut collision = request(); + let mut context = session::context::QueryContext::with_db_name(None); + context.set_extension(RAW_SERIES_REQUEST_EXTENSION_KEY, "occupied"); + collision.header = Some(RegionRequestHeader { + query_context: Some((&context).into()), + ..Default::default() + }); + let error = bind_raw_series_query(collision, &binding).unwrap_err(); + assert!(format!("{error:?}").contains("marker already exists")); + } + + fn table_source(plan: &LogicalPlan) -> Option> { + match plan { + LogicalPlan::TableScan(scan) => Some(scan.source.clone()), + _ => plan.inputs().into_iter().find_map(table_source), + } + } + + async fn plan_sql( + frontend: &Arc, + sql: &str, + query_ctx: QueryContextRef, + ) -> LogicalPlan { + let statement = QueryLanguageParser::parse_sql(sql, &query_ctx).unwrap(); + frontend + .statement_executor() + .plan(&statement, query_ctx) + .await + .unwrap() + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_standalone_native_raw_series_default_and_revalidation() { + common_telemetry::init_default_ut_logging(); + const TABLE: &str = "standalone_native_raw_series"; + let standalone = GreptimeDbStandaloneBuilder::new(TABLE).build().await; + let frontend = standalone.fe_instance().clone(); + execute_sql(&frontend, &format!("CREATE TABLE {TABLE} (host STRING, sample_value DOUBLE, ts TIMESTAMP, TIME INDEX (ts), PRIMARY KEY(host)) ENGINE=mito")).await; + execute_sql( + &frontend, + &format!("INSERT INTO {TABLE} VALUES ('alpha', 1.5, 1000), ('alpha', NULL, 2000)"), + ) + .await; + + let table = frontend + .catalog_manager() + .table("greptime", "public", TABLE, None) + .await + .unwrap() + .unwrap(); + let table_id = table.table_info().ident.table_id; + let partitions = frontend + .partition_manager() + .batch_find_table_partitions(&[table_id]) + .await + .unwrap()[&table_id] + .clone(); + assert_eq!(1, partitions.len()); + let region_id = partitions[0].id; + + let datanode = frontend.node_manager().datanode(&Peer::empty(0)).await; + let response = datanode + .handle(RegionRequest { + header: Some(RegionRequestHeader::default()), + body: Some(region_request::Body::ListMetadata(ListMetadataRequest { + region_ids: vec![region_id.as_u64()], + })), + }) + .await + .unwrap(); + let metadata: Vec> = + serde_json::from_slice(&response.metadata).unwrap(); + assert_eq!(1, metadata.len()); + let metadata = metadata[0].as_ref().unwrap(); + assert_eq!(region_id, metadata.region_id); + let region = standalone.mito_engine.find_region(region_id).unwrap(); + let snapshot = region.find_committed_sequence(); + let column_id = |name: &str| { + metadata + .column_metadatas + .iter() + .find(|column| column.column_schema.name == name) + .unwrap() + .column_id + }; + let host_id = column_id("host"); + let value_id = column_id("sample_value"); + + let ctx = QueryContext::with_db_name(None); + ctx.set_snapshot(region_id.as_u64(), snapshot); + let ctx = Arc::new(ctx); + let base = plan_sql(&frontend, &format!("SELECT * FROM {TABLE}"), ctx.clone()).await; + let source = table_source(&base).unwrap(); + let plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(TABLE), + source, + Some(vec![ + metadata + .column_metadatas + .iter() + .position(|c| c.column_id == value_id) + .unwrap(), + ]), + vec![col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(1000), None)))], + ) + .unwrap() + .build() + .unwrap(); + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.clone(), + metric_name: TABLE.to_string(), + logical_tags: vec![RawSeriesTag { + column_id: host_id, + name: "host".into(), + }], + field_ids: vec![value_id], + }; + let request = || QueryRequest { + header: Some(RegionRequestHeader { + query_context: Some(ctx.as_ref().into()), + ..Default::default() + }), + region_id, + plan: plan.clone(), + }; + let mut parent_request = request(); + parent_request.plan = LogicalPlanBuilder::from(plan.clone()) + .filter(col("sample_value").gt(lit(ScalarValue::Float64(Some(0.0))))) + .unwrap() + .build() + .unwrap(); + assert_eq!( + None, + datanode + .prepare_raw_series_query(parent_request, binding.clone()) + .await + .unwrap() + ); + let mut wrong_region = request(); + wrong_region.region_id = store_api::storage::RegionId::from_u64(region_id.as_u64() + 1); + assert!( + datanode + .prepare_raw_series_query(wrong_region, binding.clone()) + .await + .is_err() + ); + let mut marked_request = request(); + marked_request + .header + .as_mut() + .unwrap() + .query_context + .as_mut() + .unwrap() + .extensions + .insert( + RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(), + "occupied".to_string(), + ); + assert!( + datanode + .prepare_raw_series_query(marked_request, binding.clone()) + .await + .is_err() + ); + let prepared = datanode + .prepare_raw_series_query(request(), binding.clone()) + .await + .unwrap(); + assert_eq!(Some(SeriesOrdering::KeyThenTime), prepared); + + let raw = datanode + .handle_raw_series_query(request(), binding.clone()) + .await + .unwrap(); + assert_eq!(SeriesOrdering::KeyThenTime, raw.ordering()); + match raw.label_source() { + RawLabelSource::PrimaryKey { + metric_name, + logical_tags, + .. + } => { + assert_eq!(TABLE, metric_name.as_ref()); + assert_eq!(1, logical_tags.len()); + assert_eq!(host_id, logical_tags[0].column_id); + assert_eq!("host", logical_tags[0].name.as_ref()); + } + RawLabelSource::Explicit => panic!("expected key-backed source"), + } + assert_eq!("sample_value", raw.schema().fields[0].name.as_ref()); + let chunks = raw.try_collect::>().await.unwrap(); + let mut timestamps = Vec::new(); + let mut values = Vec::new(); + for chunk in &chunks { + assert_eq!(new_primary_key(&["alpha"]), chunk.primary_key.as_slice()); + assert!(chunk.metric.is_none()); + assert_eq!(1, chunk.fields.len()); + assert_eq!(chunk.time.len(), chunk.fields.get(0).unwrap().len()); + timestamps.extend_from_slice(chunk.time.as_buffer()); + for i in 0..chunk.time.len() { + values.push(chunk.fields.get(0).unwrap().sample(i)); + } + } + assert_eq!(vec![1000, 2000], timestamps); + assert_eq!(2, values.len()); + assert!(matches!(values[0], SampleRef::Float(1.5))); + assert!(matches!(values[1], SampleRef::Missing)); + assert!(chunks.last().unwrap().is_last); + assert!( + chunks + .iter() + .take(chunks.len() - 1) + .all(|chunk| !chunk.is_last) + ); + + execute_sql( + &frontend, + &format!("INSERT INTO {TABLE} VALUES ('alpha', 9.5, 3000)"), + ) + .await; + let old = datanode + .handle_raw_series_query(request(), binding.clone()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + vec![1000, 2000], + old.iter() + .flat_map(|chunk| chunk.time.as_buffer().iter().copied()) + .collect::>() + ); + + let mut stale = binding; + stale.physical_metadata.schema_version += 1; + let prepare_error = datanode + .prepare_raw_series_query(request(), stale.clone()) + .await + .unwrap_err(); + assert!(format!("{prepare_error:?}").contains("Raw-series metadata mismatch")); + let error = match datanode.handle_raw_series_query(request(), stale).await { + Ok(_) => panic!("stale raw-series metadata unexpectedly succeeded"), + Err(error) => error, + }; + let message = format!("{error:?}"); + assert!( + message.contains("Raw-series metadata mismatch"), + "unexpected stale binding error chain: {message}" + ); + } +} diff --git a/tests-integration/src/standalone/native_promql_tests.rs b/tests-integration/src/standalone/native_promql_tests.rs new file mode 100644 index 00000000000..33f3325e9a3 --- /dev/null +++ b/tests-integration/src/standalone/native_promql_tests.rs @@ -0,0 +1,396 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use common_query::OutputData; +use common_recordbatch::RecordBatches; +use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray}; +use datafusion::arrow::datatypes::{DataType, TimeUnit}; +use frontend::instance::Instance; +use query::options::QueryOptions; +use servers::query_handler::sql::SqlQueryHandler; +use session::context::QueryContext; + +use super::GreptimeDbStandaloneBuilder; +use crate::test_util::execute_sql; + +const QUERY: &str = "TQL EVAL (1, 3, '1s') baseline_native"; +const FILTERED_QUERY: &str = "TQL EVAL (1, 3, '1s') baseline_native > 6"; +const CREATE_TABLE: &str = "CREATE TABLE baseline_native (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) ENGINE=mito"; +const INSERT_ROWS: &str = "INSERT INTO baseline_native VALUES (1000, 'alpha', 1.5), (2000, 'alpha', NULL), (3000, 'alpha', 3.5), (1000, '', 4.5), (2000, '', 5.5), (3000, '', 6.5), (1000, NULL, 10.5), (2000, NULL, 11.5), (3000, NULL, 12.5), (1000, 'beta', 7.5), (3000, 'beta', 9.5)"; + +async fn run_query(instance: &Arc, sql: &str) -> String { + let output = SqlQueryHandler::do_query(instance.as_ref(), sql, QueryContext::arc()) + .await + .remove(0) + .unwrap(); + output.data.pretty_print().await +} + +async fn query_batches(instance: &Arc, sql: &str) -> RecordBatches { + let output = SqlQueryHandler::do_query(instance.as_ref(), sql, QueryContext::arc()) + .await + .remove(0) + .unwrap(); + match output.data { + OutputData::RecordBatches(batches) => batches, + OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), + OutputData::AffectedRows(_) => panic!("expected query batches"), + } +} + +async fn create_seeded_instance( + name: &str, + options: QueryOptions, +) -> crate::standalone::GreptimeDbStandalone { + let standalone = GreptimeDbStandaloneBuilder::new(name) + .with_query_options(options) + .build() + .await; + let instance = &standalone.frontend.instance; + execute_sql(instance, CREATE_TABLE).await; + execute_sql(instance, INSERT_ROWS).await; + standalone +} + +fn rows(batches: &RecordBatches) -> Vec<(i64, Option, Option)> { + let mut rows = Vec::new(); + for batch in batches.iter() { + let batch = batch.df_record_batch(); + let ts = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let host = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let val = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + for index in 0..batch.num_rows() { + rows.push(( + ts.value(index), + (!host.is_null(index)).then(|| host.value(index).to_string()), + (!val.is_null(index)).then(|| val.value(index)), + )); + } + } + rows.sort_by(|left, right| { + left.0.cmp(&right.0).then_with(|| { + left.1 + .is_none() + .cmp(&right.1.is_none()) + .then_with(|| left.1.cmp(&right.1)) + }) + }); + rows +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_promql_standalone_executes_with_real_tql_query() { + let disabled_options = QueryOptions { + parallelism: 1, + ..Default::default() + }; + let enabled_options = QueryOptions { + experimental_native_promql: true, + ..disabled_options.clone() + }; + let enabled = create_seeded_instance("native_promql_enabled", enabled_options).await; + let ordinary = create_seeded_instance("native_promql_disabled", disabled_options).await; + let instance = &enabled.frontend.instance; + let baseline_instance = &ordinary.frontend.instance; + + let analyzed = run_query(instance, "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native").await; + assert!( + analyzed.contains("NativeInstantManipulateExec"), + "experimental plan did not execute via native instant manipulation:\n{analyzed}" + ); + assert!( + analyzed.contains("SeriesScanExec: source=primary_key"), + "native plan omitted the primary-key raw-series scan:\n{analyzed}" + ); + let ordinary_plan = run_query( + baseline_instance, + "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native", + ) + .await; + assert!( + !ordinary_plan.contains("NativeInstantManipulateExec"), + "{ordinary_plan}" + ); + + let enabled_batches = query_batches(instance, QUERY).await; + let ordinary_batches = query_batches(baseline_instance, QUERY).await; + assert_eq!(enabled_batches.schema(), ordinary_batches.schema()); + let arrow_schema = enabled_batches.schema().arrow_schema().clone(); + assert_eq!( + arrow_schema + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + vec!["ts", "host", "val"] + ); + assert_eq!( + arrow_schema.field(0).data_type(), + &DataType::Timestamp(TimeUnit::Millisecond, None) + ); + assert_eq!(arrow_schema.field(1).data_type(), &DataType::Utf8); + assert_eq!(arrow_schema.field(2).data_type(), &DataType::Float64); + assert_eq!(rows(&enabled_batches), rows(&ordinary_batches)); + assert_eq!( + vec![ + (1_000, Some(String::new()), Some(4.5)), + (1_000, Some("alpha".to_string()), Some(1.5)), + (1_000, Some("beta".to_string()), Some(7.5)), + (1_000, None, Some(10.5)), + (2_000, Some(String::new()), Some(5.5)), + (2_000, Some("alpha".to_string()), None), + (2_000, Some("beta".to_string()), Some(7.5)), + (2_000, None, Some(11.5)), + (3_000, Some(String::new()), Some(6.5)), + (3_000, Some("alpha".to_string()), Some(3.5)), + (3_000, Some("beta".to_string()), Some(9.5)), + (3_000, None, Some(12.5)), + ], + rows(&enabled_batches) + ); + + let single_eval = "TQL ANALYZE VERBOSE (1, 1, '1s') baseline_native"; + let unsupported_plan = run_query(instance, single_eval).await; + assert!( + !unsupported_plan.contains("NativeInstantManipulateExec"), + "{unsupported_plan}" + ); + let unsupported_result = query_batches(instance, "TQL EVAL (1, 1, '1s') baseline_native").await; + assert_eq!( + vec![ + (1_000, Some(String::new()), Some(4.5)), + (1_000, Some("alpha".to_string()), Some(1.5)), + (1_000, Some("beta".to_string()), Some(7.5)), + (1_000, None, Some(10.5)), + ], + rows(&unsupported_result) + ); + + for test_instance in [instance, baseline_instance] { + execute_sql( + test_instance, + "CREATE TABLE native_tag_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm') ENGINE=mito", + ) + .await; + execute_sql( + test_instance, + "INSERT INTO native_tag_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3), (1000, 'zeta', 10), (3000, 'zeta', 30)", + ) + .await; + let table = test_instance + .catalog_manager() + .table("greptime", "public", "native_tag_parts", None) + .await + .unwrap() + .unwrap(); + let table_id = table.table_info().ident.table_id; + let partitions = test_instance + .partition_manager() + .batch_find_table_partitions(&[table_id]) + .await + .unwrap()[&table_id] + .clone(); + assert_eq!(2, partitions.len(), "native_tag_parts"); + execute_sql( + test_instance, + "CREATE TABLE native_time_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:00:02', ts >= '1970-01-01 00:00:02') ENGINE=mito", + ) + .await; + execute_sql( + test_instance, + "INSERT INTO native_time_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3)", + ) + .await; + let table = test_instance + .catalog_manager() + .table("greptime", "public", "native_time_parts", None) + .await + .unwrap() + .unwrap(); + let table_id = table.table_info().ident.table_id; + let partitions = test_instance + .partition_manager() + .batch_find_table_partitions(&[table_id]) + .await + .unwrap()[&table_id] + .clone(); + assert_eq!(2, partitions.len(), "native_time_parts"); + } + + let tag_query = "TQL EVAL (1, 3, '1s') native_tag_parts"; + let tag_plan = run_query( + instance, + "TQL ANALYZE VERBOSE (1, 3, '1s') native_tag_parts", + ) + .await; + assert!( + tag_plan.contains("NativeInstantManipulateExec"), + "tag-partitioned plan did not use native instant manipulation:\n{tag_plan}" + ); + let tag_enabled = query_batches(instance, tag_query).await; + let tag_ordinary = + query_batches(baseline_instance, "TQL EVAL (1, 3, '1s') native_tag_parts").await; + assert_eq!(tag_enabled.schema(), tag_ordinary.schema()); + assert_eq!(rows(&tag_enabled), rows(&tag_ordinary)); + assert_eq!( + vec![ + (1_000, Some("alpha".to_string()), Some(1.0)), + (1_000, Some("zeta".to_string()), Some(10.0)), + (2_000, Some("alpha".to_string()), Some(1.0)), + (2_000, Some("zeta".to_string()), Some(10.0)), + (3_000, Some("alpha".to_string()), Some(3.0)), + (3_000, Some("zeta".to_string()), Some(30.0)), + ], + rows(&tag_enabled) + ); + + let time_query = "TQL EVAL (1, 3, '1s') native_time_parts"; + let time_plan = run_query( + instance, + "TQL ANALYZE VERBOSE (1, 3, '1s') native_time_parts", + ) + .await; + assert!( + time_plan.contains("NativeInstantManipulateExec"), + "time-partitioned plan did not use native instant manipulation:\n{time_plan}" + ); + assert!( + time_plan.contains("NativeRawMergeExec"), + "time-partitioned plan did not merge the native raw series of its regions:\n{time_plan}" + ); + let time_enabled = query_batches(instance, time_query).await; + let time_ordinary = + query_batches(baseline_instance, "TQL EVAL (1, 3, '1s') native_time_parts").await; + assert_eq!(time_enabled.schema(), time_ordinary.schema()); + assert_eq!(rows(&time_enabled), rows(&time_ordinary)); + assert_eq!( + vec![ + (1_000, Some("alpha".to_string()), Some(1.0)), + (2_000, Some("alpha".to_string()), Some(1.0)), + (3_000, Some("alpha".to_string()), Some(3.0)), + ], + rows(&time_enabled) + ); + + let filtered_plan = run_query( + instance, + "TQL ANALYZE VERBOSE (1, 3, '1s') baseline_native > 6", + ) + .await; + assert!( + !filtered_plan.contains("NativeInstantManipulateExec"), + "unsupported filtered plan unexpectedly used native instant manipulation:\n{filtered_plan}" + ); + let filtered_enabled = query_batches(instance, FILTERED_QUERY).await; + let filtered_ordinary = query_batches(baseline_instance, FILTERED_QUERY).await; + assert_eq!(filtered_enabled.schema(), filtered_ordinary.schema()); + assert_eq!(rows(&filtered_enabled), rows(&filtered_ordinary)); + assert_eq!( + vec![ + (1_000, Some("beta".to_string()), Some(7.5)), + (1_000, None, Some(10.5)), + (2_000, Some("beta".to_string()), Some(7.5)), + (2_000, None, Some(11.5)), + (3_000, Some(String::new()), Some(6.5)), + (3_000, Some("beta".to_string()), Some(9.5)), + (3_000, None, Some(12.5)), + ], + rows(&filtered_enabled) + ); +} + +/// The time-partitioned case at parallelism 4: the frontend plans more than one target partition, +/// and the native instant manipulation must still consume the merged raw series of the two +/// regions that hold the one series of the table. +/// +/// An ordinary instance built with the same options and seeded with the same fixture is the schema +/// oracle of this case, so the complete public schema of the result is compared instead of only +/// the plan of the enabled instance. +#[tokio::test(flavor = "multi_thread")] +async fn test_native_promql_standalone_time_partitioned_parallelism_4() { + const CREATE_TIME_PARTS: &str = "CREATE TABLE native_time_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:00:02', ts >= '1970-01-01 00:00:02') ENGINE=mito"; + const INSERT_TIME_PARTS: &str = + "INSERT INTO native_time_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3)"; + const TIME_PARTS_QUERY: &str = "TQL EVAL (1, 3, '1s') native_time_parts"; + const TIME_PARTS_PLAN: &str = "TQL ANALYZE VERBOSE (1, 3, '1s') native_time_parts"; + + let enabled = create_seeded_instance( + "native_promql_time_parts_p4", + QueryOptions { + parallelism: 4, + experimental_native_promql: true, + ..Default::default() + }, + ) + .await; + let ordinary = create_seeded_instance( + "native_promql_time_parts_p4_ordinary", + QueryOptions { + parallelism: 4, + ..Default::default() + }, + ) + .await; + let instance = &enabled.frontend.instance; + let ordinary_instance = &ordinary.frontend.instance; + for target in [instance, ordinary_instance] { + execute_sql(target, CREATE_TIME_PARTS).await; + execute_sql(target, INSERT_TIME_PARTS).await; + } + + let plan = run_query(instance, TIME_PARTS_PLAN).await; + assert!( + plan.contains("NativeInstantManipulateExec"), + "time-partitioned plan at parallelism 4 did not use native instant manipulation:\n{plan}" + ); + assert!( + plan.contains("NativeRawMergeExec"), + "time-partitioned plan at parallelism 4 did not merge the native raw series of its \ + regions:\n{plan}" + ); + + let time_batches = query_batches(instance, TIME_PARTS_QUERY).await; + let ordinary_batches = query_batches(ordinary_instance, TIME_PARTS_QUERY).await; + // The complete public schema, including nullability and field and schema metadata: the + // frontend has already expanded scan-time dictionaries, so a dictionary-shaped native schema + // must fail here instead of being normalized away. + assert_eq!(time_batches.schema(), ordinary_batches.schema()); + assert_eq!( + time_batches.schema().arrow_schema(), + ordinary_batches.schema().arrow_schema() + ); + assert_eq!(rows(&time_batches), rows(&ordinary_batches)); + assert_eq!( + vec![ + (1_000, Some("alpha".to_string()), Some(1.0)), + (2_000, Some("alpha".to_string()), Some(1.0)), + (3_000, Some("alpha".to_string()), Some(3.0)), + ], + rows(&time_batches) + ); +} diff --git a/tests-integration/src/tests.rs b/tests-integration/src/tests.rs index 4a5b2f0c6c5..2a9b678c9aa 100644 --- a/tests-integration/src/tests.rs +++ b/tests-integration/src/tests.rs @@ -16,6 +16,7 @@ mod gc; mod instance_kafka_wal_test; mod instance_noop_wal_test; mod instance_test; +mod native_promql_cluster_test; mod nested_merge_scan_capability_test; mod promql_test; mod reconcile_table; diff --git a/tests-integration/src/tests/native_promql_cluster_test.rs b/tests-integration/src/tests/native_promql_cluster_test.rs new file mode 100644 index 00000000000..8bf0b12ff48 --- /dev/null +++ b/tests-integration/src/tests/native_promql_cluster_test.rs @@ -0,0 +1,2015 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Real-TCP acceptance of the cross-region native PromQL path on a distributed frontend. +//! +//! Two datanodes serve one time-partitioned metric table: one region per partition and one region +//! leader per datanode, so the single series of the table spans both datanodes. Only the frontend +//! is configured with `experimental_native_promql`, exactly like a deployment where the planning +//! node carries the flag. The frontend reaches the datanodes over their real Flight listeners +//! ([`GreptimeDbClusterBuilder::with_real_frontend_clients`]), so the per-datanode RPC counters +//! prove that the frontend itself performed the named raw-series preflight (Flight `DoAction`) and +//! the raw-series read (Flight `DoGet`) against both region leaders before the rows are consumed. +//! The disabled frontend proves the flag gates the whole path, and a filter the native planner +//! cannot push down proves unsupported shapes are rejected before any preflight RPC leaves the +//! frontend. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use common_query::{Output, OutputData}; +use common_recordbatch::RecordBatches; +use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray}; +use datafusion::arrow::datatypes::{DataType, TimeUnit}; +use frontend::instance::Instance; +use query::options::QueryOptions; +use servers::query_handler::sql::SqlQueryHandler; +use session::context::QueryContext; + +use crate::cluster::{DatanodeRpcStats, GreptimeDbCluster, GreptimeDbClusterBuilder}; +use crate::test_util::execute_sql; + +/// One series in two time partitions, so the two regions of the table each hold one sample. +const TABLE: &str = "native_cluster_parts"; +const CREATE_TABLE: &str = "CREATE TABLE native_cluster_parts (ts TIMESTAMP(3), host STRING, val DOUBLE, TIME INDEX (ts), PRIMARY KEY (host)) PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:00:02', ts >= '1970-01-01 00:00:02') ENGINE=mito"; +const INSERT_ROWS: &str = + "INSERT INTO native_cluster_parts VALUES (1000, 'alpha', 1), (3000, 'alpha', 3)"; +const ANALYZE: &str = "TQL ANALYZE VERBOSE (1, 3, '1s') native_cluster_parts"; +const EVAL: &str = "TQL EVAL (1, 3, '1s') native_cluster_parts"; +/// A filter the native planner cannot push down, so the shape is rejected before any RPC. +const FILTERED_ANALYZE: &str = "TQL ANALYZE VERBOSE (1, 3, '1s') native_cluster_parts > 6"; +const FILTERED_EVAL: &str = "TQL EVAL (1, 3, '1s') native_cluster_parts > 6"; + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_promql_cluster_cross_region_parallelism_1() { + run_cross_region_case("native_promql_cluster_p1", 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_promql_cluster_cross_region_parallelism_4() { + run_cross_region_case("native_promql_cluster_p4", 4).await; +} + +/// Builds one two-datanode cluster whose frontend owns the query options and the real clients. +async fn build_cluster( + name: &str, + parallelism: usize, + experimental_native_promql: bool, +) -> GreptimeDbCluster { + GreptimeDbClusterBuilder::new(name) + .await + .with_datanodes(2) + // The datanodes must be reachable at the addresses of the table routes, and the frontend + // must really dial them, or neither its `DoAction` preflight nor its `DoGet` reads are + // counted. + .with_real_datanode_grpc_addr(true) + .with_real_frontend_clients(true) + .with_frontend_query_options(QueryOptions { + parallelism, + experimental_native_promql, + ..Default::default() + }) + .build(false) + .await +} + +async fn run_cross_region_case(name: &str, parallelism: usize) { + common_telemetry::init_default_ut_logging(); + + let enabled = build_cluster(&format!("{name}_enabled"), parallelism, true).await; + let disabled = build_cluster(&format!("{name}_disabled"), parallelism, false).await; + let enabled_frontend = enabled.fe_instance().clone(); + let disabled_frontend = disabled.fe_instance().clone(); + + for frontend in [&enabled_frontend, &disabled_frontend] { + execute_sql(frontend, CREATE_TABLE).await; + execute_sql(frontend, INSERT_ROWS).await; + } + + // One region per time partition, and the partitions must be served by different datanodes: + // only then does the single series really span both datanodes. + let leaders = region_leaders(&enabled_frontend, TABLE).await; + assert_eq!( + 2, + leaders.len(), + "expected one region per time partition of {TABLE}, actual region leaders: {leaders:?}" + ); + assert_eq!( + BTreeSet::from([1_u64, 2_u64]), + leaders.values().copied().collect::>(), + "expected the time partitions of {TABLE} to be served by both datanodes, actual region \ + leaders: {leaders:?}" + ); + + // The ordinary read proves the seeded rows are complete before TQL runs. + let stored = query_batches( + &enabled_frontend, + &format!("SELECT ts, host, val FROM {TABLE} ORDER BY ts"), + ) + .await; + assert_eq!(expected_columns(), columns(&stored)); + assert_eq!( + expected_stored_rows(), + rows(&stored), + "unexpected stored rows of {TABLE}" + ); + + // The enabled frontend must reach the native plan that consumes the raw series of both + // regions; the disabled frontend must keep the ordinary plan. + let enabled_plan = query_pretty(&enabled_frontend, ANALYZE).await; + assert!( + enabled_plan.contains("NativeInstantManipulateExec"), + "the enabled frontend did not use the native instant manipulation:\n{enabled_plan}" + ); + assert!( + enabled_plan.contains("NativeRawMergeExec"), + "the enabled frontend did not merge the native raw series of the regions:\n{enabled_plan}" + ); + let disabled_plan = query_pretty(&disabled_frontend, ANALYZE).await; + assert!( + !disabled_plan.contains("NativeInstantManipulateExec"), + "the disabled frontend unexpectedly used the native instant manipulation:\n{disabled_plan}" + ); + assert!( + !disabled_plan.contains("NativeRawMergeExec"), + "the disabled frontend unexpectedly merged native raw series:\n{disabled_plan}" + ); + + // Seeding and planning are done: from here on only the TQL EVAL below may move the counters. + let baseline = leaders + .values() + .map(|datanode| { + ( + *datanode, + ( + rpc_requests(&enabled, *datanode), + prepare_requests(&enabled, *datanode), + ), + ) + }) + .collect::>(); + + let native_batches = query_batches(&enabled_frontend, EVAL).await; + + // Both protocols of both datanodes ran before the rows above were consumed: the named + // raw-series preflight of the planning phase and the raw-series read of the execution phase. + for (datanode, (do_get, prepare)) in &baseline { + assert_eq!( + do_get + 1, + rpc_requests(&enabled, *datanode), + "expected the TQL EVAL to read the region of the datanode {datanode} exactly once over \ + Flight DoGet (baseline {do_get})" + ); + assert_eq!( + prepare + 1, + prepare_requests(&enabled, *datanode), + "expected the TQL EVAL to preflight the named raw series at the datanode {datanode} \ + exactly once over Flight DoAction (baseline {prepare})" + ); + } + + assert_eq!(expected_columns(), columns(&native_batches)); + assert_eq!(expected_eval_rows(), rows(&native_batches)); + + let ordinary_batches = query_batches(&disabled_frontend, EVAL).await; + assert_eq!(columns(&native_batches), columns(&ordinary_batches)); + // The column comparison above only covers names and types, so compare the complete public + // schemas as well: the GreptimeDB schema and its Arrow schema, including nullability and + // field and schema metadata. The frontend has already expanded scan-time dictionaries when the + // rows left it, so a dictionary-shaped native schema must fail here instead of being + // normalized away. + assert_eq!(native_batches.schema(), ordinary_batches.schema()); + assert_eq!( + native_batches.schema().arrow_schema(), + ordinary_batches.schema().arrow_schema() + ); + assert_eq!(rows(&native_batches), rows(&ordinary_batches)); + assert_eq!(expected_eval_rows(), rows(&ordinary_batches)); + + // An unsupported filtered shape is rejected locally, before any preflight RPC leaves the + // frontend, and the ordinary path still returns the complete known result. + let prepare_baseline = baseline + .keys() + .map(|datanode| (*datanode, prepare_requests(&enabled, *datanode))) + .collect::>(); + + let filtered_plan = query_pretty(&enabled_frontend, FILTERED_ANALYZE).await; + assert!( + !filtered_plan.contains("NativeInstantManipulateExec"), + "the unsupported filtered plan unexpectedly used the native instant manipulation:\n\ + {filtered_plan}" + ); + assert!( + !filtered_plan.contains("NativeRawMergeExec"), + "the unsupported filtered plan unexpectedly merged native raw series:\n{filtered_plan}" + ); + + let filtered_batches = query_batches(&enabled_frontend, FILTERED_EVAL).await; + let filtered_ordinary = query_batches(&disabled_frontend, FILTERED_EVAL).await; + assert_eq!(expected_columns(), columns(&filtered_batches)); + assert_eq!(columns(&filtered_batches), columns(&filtered_ordinary)); + // The unsupported filtered shape runs the ordinary path on both frontends; the same complete + // public schema comparison applies to it. + assert_eq!(filtered_batches.schema(), filtered_ordinary.schema()); + assert_eq!( + filtered_batches.schema().arrow_schema(), + filtered_ordinary.schema().arrow_schema() + ); + // No stored sample of this fixture passes `> 6`, so the complete filtered result is empty. + let expected_filtered: Vec<(i64, Option, Option)> = Vec::new(); + assert_eq!( + expected_filtered, + rows(&filtered_batches), + "unexpected filtered result" + ); + assert_eq!(rows(&filtered_batches), rows(&filtered_ordinary)); + + for (datanode, prepare) in &prepare_baseline { + assert_eq!( + *prepare, + prepare_requests(&enabled, *datanode), + "the unsupported filtered shape must be rejected before any prepare RPC at the \ + datanode {datanode}" + ); + } + + // The disabled frontend never preflights, whatever the query shape. + for datanode in leaders.values() { + assert_eq!( + 0, + prepare_requests(&disabled, *datanode), + "the disabled frontend must not preflight named raw series at the datanode {datanode}" + ); + } +} + +async fn run_sql(frontend: &Arc, sql: &str) -> Output { + SqlQueryHandler::do_query(frontend.as_ref(), sql, QueryContext::arc()) + .await + .remove(0) + .unwrap_or_else(|error| panic!("`{sql}` failed: {error}")) +} + +async fn query_batches(frontend: &Arc, sql: &str) -> RecordBatches { + output_batches(run_sql(frontend, sql).await).await +} + +async fn query_pretty(frontend: &Arc, sql: &str) -> String { + run_sql(frontend, sql).await.data.pretty_print().await +} + +async fn output_batches(output: Output) -> RecordBatches { + match output.data { + OutputData::RecordBatches(batches) => batches, + OutputData::Stream(stream) => RecordBatches::try_collect(stream) + .await + .expect("the output stream must be collectable"), + OutputData::AffectedRows(rows) => { + panic!("expected a query output, got {rows} affected rows") + } + } +} + +/// The complete schema of the TQL result the ordinary and the native path must share. +fn expected_columns() -> Vec<(String, DataType)> { + vec![ + ( + "ts".to_string(), + DataType::Timestamp(TimeUnit::Millisecond, None), + ), + ("host".to_string(), DataType::Utf8), + ("val".to_string(), DataType::Float64), + ] +} + +fn columns(batches: &RecordBatches) -> Vec<(String, DataType)> { + batches + .schema() + .arrow_schema() + .fields() + .iter() + .map(|field| (field.name().clone(), field.data_type().clone())) + .collect() +} + +/// The complete stored rows of the fixture: one series with one sample per time partition. +fn expected_stored_rows() -> Vec<(i64, Option, Option)> { + vec![ + (1_000, Some("alpha".to_string()), Some(1.0)), + (3_000, Some("alpha".to_string()), Some(3.0)), + ] +} + +/// The complete TQL result: every evaluation time carries the series, and 2000 is filled by the +/// lookback window from the sample of 1000. +fn expected_eval_rows() -> Vec<(i64, Option, Option)> { + vec![ + (1_000, Some("alpha".to_string()), Some(1.0)), + (2_000, Some("alpha".to_string()), Some(1.0)), + (3_000, Some("alpha".to_string()), Some(3.0)), + ] +} + +/// The complete rows of a three-column TQL result, sorted into the canonical order. +fn rows(batches: &RecordBatches) -> Vec<(i64, Option, Option)> { + let mut rows = Vec::new(); + for batch in batches.iter() { + let batch = batch.df_record_batch(); + let ts = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let host = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let val = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + for index in 0..batch.num_rows() { + rows.push(( + ts.value(index), + (!host.is_null(index)).then(|| host.value(index).to_string()), + (!val.is_null(index)).then(|| val.value(index)), + )); + } + } + rows.sort_by(|left, right| { + left.0.cmp(&right.0).then_with(|| { + left.1 + .is_none() + .cmp(&right.1.is_none()) + .then_with(|| left.1.cmp(&right.1)) + }) + }); + rows +} + +/// Maps every region of `table` to the id of its leader datanode. +async fn region_leaders(frontend: &Arc, table: &str) -> BTreeMap { + use datatypes::arrow::array::AsArray; + use datatypes::arrow::datatypes::UInt64Type; + + let sql = format!( + "SELECT region_id, peer_id FROM information_schema.region_peers + WHERE table_schema = 'public' AND table_name = '{table}' AND is_leader = 'Yes' + ORDER BY region_id" + ); + let batches = query_batches(frontend, &sql).await; + + let mut leaders = BTreeMap::new(); + for batch in batches.iter() { + let batch = batch.df_record_batch(); + let region_ids = batch + .column_by_name("region_id") + .expect("region_id column") + .as_primitive::(); + let peer_ids = batch + .column_by_name("peer_id") + .expect("peer_id column") + .as_primitive::(); + for row in 0..batch.num_rows() { + leaders.insert(region_ids.value(row), peer_ids.value(row)); + } + } + leaders +} + +fn rpc_requests(cluster: &GreptimeDbCluster, datanode_id: u64) -> usize { + rpc_stats(cluster, datanode_id).requests() +} + +fn prepare_requests(cluster: &GreptimeDbCluster, datanode_id: u64) -> usize { + rpc_stats(cluster, datanode_id).prepare_requests() +} + +fn rpc_stats(cluster: &GreptimeDbCluster, datanode_id: u64) -> &Arc { + cluster + .datanode_rpc_stats(datanode_id) + .unwrap_or_else(|| panic!("expected the rpc stats of the datanode {datanode_id}")) +} + +/// Bounded acceptance tests of the frontend-visible failures of the cross-region native PromQL +/// path. +/// +/// Every case builds its own two-datanode cluster whose datanodes serve the real TCP Flight +/// listener through [`FaultFlight`], while the in-process duplex listener keeps serving the bare +/// region server; the frontend, its real clients, the table route and the fixture rows are the +/// ones the positive cases above already use. A case seeds its table and reads its rows before it +/// arms its fault, so the window of the faulted query starts empty, and a fault only ever replaces +/// the named raw-series preflight or the raw-series read of the armed regions. No case arms a +/// fault while `TQL ANALYZE` runs: its one-shot answers would be consumed by the analyze. +/// +/// A wrapper only ever applies its fault after it forwarded the real payload prefix of its actual +/// response, never before: the failed read of a case is released only once its sibling read is +/// held with its actual response still open, and a held read is only released by the client that +/// cancels the query. Every cancellation of a case is therefore driven by the failure of that +/// case, and every query phase is bounded by [`QUERY_TIMEOUT`] or [`CANCEL_ACK_TIMEOUT`]. +mod fault_acceptance { + use std::collections::{BTreeMap, BTreeSet}; + use std::future::Future; + use std::pin::Pin; + use std::sync::{Arc, Mutex}; + use std::task::{Context, Poll}; + use std::time::Duration; + + use api::v1::region::QueryRequest as RegionQueryRequest; + use arrow_flight::{Action, FlightData, Ticket}; + use common_error::ext::ErrorExt; + use common_error::status_code::StatusCode; + use common_grpc::flight::{FlightDecoder, FlightMessage}; + use common_meta::DatanodeId; + use common_query::request::{ + PREPARE_RAW_SERIES_ACTION, RAW_SERIES_REQUEST_EXTENSION_KEY, + encode_prepare_raw_series_response, + }; + use common_recordbatch::SendableRecordBatchStream; + use datanode::region_server::RegionServer as DatanodeRegionServer; + use futures::{Stream, StreamExt, ready}; + use prost::Message; + use servers::grpc::flight::{FlightCraft, FlightCraftRef, TonicStream}; + use tokio::sync::{mpsc, oneshot}; + use tonic::{Request, Response, Status}; + + use crate::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; + use crate::test_util::{execute_sql, try_execute_sql}; + + use super::*; + + /// The unique marker of the failing preflight of the second case. + const PREFLIGHT_ERROR_MARKER: &str = "fault acceptance: preflight internal error"; + /// The unique marker of the late raw-series body error of the third case. + const LATE_BODY_ERROR_MARKER: &str = "fault acceptance: late raw-series body error"; + /// The bound of one cancellation acknowledgement. + const CANCEL_ACK_TIMEOUT: Duration = Duration::from_secs(5); + /// The bound of one query phase of a case: the faulted `TQL EVAL` with its planning call and + /// the readiness phase that drives it, and the follow-up queries of a disarmed case. + const QUERY_TIMEOUT: Duration = Duration::from_secs(30); + + /// One observed Flight request of a datanode. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Event { + /// A named raw-series preflight (`Flight` `DoAction`). + Prepare(DatanodeId), + /// A raw-series read (`Flight` `DoGet` carrying the raw-series extension). + RawGet(DatanodeId), + /// An ordinary region read (`Flight` `DoGet` without the raw-series extension). + OrdinaryGet(DatanodeId), + } + + /// The observed Flight traffic of one datanode. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + struct Traffic { + /// Named raw-series preflights. + prepare: usize, + /// Raw-series reads. + raw_get: usize, + /// Ordinary region reads. + ordinary_get: usize, + } + + impl Traffic { + /// Counts the events of `node` in the log window `window`. + fn of(window: &[Event], node: DatanodeId) -> Self { + let mut traffic = Self::default(); + for event in window { + match event { + Event::Prepare(observed) if *observed == node => traffic.prepare += 1, + Event::RawGet(observed) if *observed == node => traffic.raw_get += 1, + Event::OrdinaryGet(observed) if *observed == node => traffic.ordinary_get += 1, + _ => {} + } + } + traffic + } + } + + /// What a wrapper stream does once it forwarded the real payload prefix of its actual response. + enum AfterPrefix { + /// Holds this raw read pending, with its actual response open and unfinished, until the + /// client cancels the query; the first park reports itself as the witness of the case. + Park, + /// Fails this raw read with `status`, and only once the sibling raw read of the case is + /// held, so a released error never hides a sibling response that was not held open. + Fail(Status), + } + + /// The fault a case arms after its fixture is ready. + #[derive(Debug)] + enum ArmedFault { + /// Answers the preflight of `region` with the frozen unsupported body and a clean end of + /// stream. + UnsupportedPreflight { region: u64 }, + /// Fails the preflight of `region` with the internal peer status of `marker`. + FailingPreflight { region: u64, marker: &'static str }, + /// Holds the raw read of `sibling` with its real payload prefix already forwarded, and + /// fails the raw read of `selected` late, once `sibling` is held. + LateRawError { + selected: u64, + sibling: u64, + marker: &'static str, + }, + /// Holds the raw read of every region of `regions`, each with its real payload prefix + /// already forwarded, until the client cancels the query. + ParkedRawStreams { regions: BTreeSet }, + } + + /// The real payload prefix one wrapper stream forwarded from the actual region server. + /// + /// The witness only exists once a record batch frame of the actual response was forwarded, so + /// a schema-only prefix never produces one. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + struct PayloadPrefix { + /// The datanode whose region server produced the frames. + node: DatanodeId, + /// The actual response frames forwarded until the record batch, schema frame included. + frames: usize, + } + + /// The shared state of one case: the ordered event log and its one-shot witnesses. + /// + /// Both datanodes share one state, so the log is a single ordered vector. Every lock is a + /// short critical section that appends or takes one value; no lock is held across an await. + struct FaultState { + events: Mutex>, + armed: Mutex>, + prefixes: Mutex>, + /// Reports that a raw read of the case is held: its real payload prefix was forwarded and + /// its actual response is still open behind the pending stream. + sibling_hold: Mutex>>, + /// Waits for that report before the late error of the selected raw read is released. + sibling_hold_waiter: Mutex>>, + parked: mpsc::UnboundedSender, + dropped: mpsc::UnboundedSender, + } + + impl FaultState { + /// Creates the shared state of one case; the witnesses report to the test's channels. + fn new( + parked: mpsc::UnboundedSender, + dropped: mpsc::UnboundedSender, + ) -> Self { + Self { + events: Mutex::new(Vec::new()), + armed: Mutex::new(None), + prefixes: Mutex::new(Vec::new()), + sibling_hold: Mutex::new(None), + sibling_hold_waiter: Mutex::new(None), + parked, + dropped, + } + } + + /// Arms `fault` and prepares the hold witness of the case. + /// + /// The witness is taken by the first held raw read of the case, so a case that holds more + /// than one read still reports the hold exactly once. + fn arm(&self, fault: ArmedFault) { + *self.armed.lock().unwrap() = Some(fault); + let (hold, hold_waiter) = oneshot::channel(); + *self.sibling_hold.lock().unwrap() = Some(hold); + *self.sibling_hold_waiter.lock().unwrap() = Some(hold_waiter); + } + + /// Disarms the case, so every later raw read is forwarded unwrapped. + /// + /// A held raw read is only released by the client that cancels its query, so this is + /// called after every cancellation of the case was acknowledged. + fn disarm(&self) { + *self.armed.lock().unwrap() = None; + } + + /// The observed event log of the case. + fn events(&self) -> Vec { + self.events.lock().unwrap().clone() + } + + /// Appends one observation. + fn push(&self, event: Event) { + self.events.lock().unwrap().push(event); + } + + /// The fault waiting for one raw read of `region`, `None` when the case does not touch it. + fn raw_read_plan(&self, region: u64) -> Option { + let fault = match self.armed.lock().unwrap().as_ref()? { + ArmedFault::LateRawError { + selected, marker, .. + } if region == *selected => { + AfterPrefix::Fail(peer_status(StatusCode::Internal, marker)) + } + ArmedFault::LateRawError { sibling, .. } if region == *sibling => AfterPrefix::Park, + ArmedFault::ParkedRawStreams { regions } if regions.contains(®ion) => { + AfterPrefix::Park + } + _ => return None, + }; + Some(fault) + } + } + + /// Serves the real region server of one datanode, records the fixture traffic of its real TCP + /// listener, and injects the armed fault of the case. + struct FaultFlight { + /// The datanode that owns the real region server behind this handler. + node: DatanodeId, + /// The real handler of the datanode; every request that is not a fault delegates to it. + inner: FlightCraftRef, + /// The case state shared by both datanodes of the cluster. + state: Arc, + } + + #[async_trait::async_trait] + impl FlightCraft for FaultFlight { + async fn do_get( + &self, + request: Request, + ) -> std::result::Result>, Status> { + let Some(region) = raw_series_region(&request.get_ref().ticket) else { + self.state.push(Event::OrdinaryGet(self.node)); + return self.inner.do_get(request).await; + }; + self.state.push(Event::RawGet(self.node)); + // The actual response is opened, and its region-server stream is retained by the + // wrapper, before the case decides how the body of this read continues. + let response = self.inner.do_get(request).await?; + let Some(fault) = self.state.raw_read_plan(region) else { + return Ok(response); + }; + // Only a read that is armed to fail waits for the hold of the case; a read that is + // armed to be held is self-contained. + let sibling = match fault { + AfterPrefix::Fail(_) => self.state.sibling_hold_waiter.lock().unwrap().take(), + AfterPrefix::Park => None, + }; + Ok(Response::new(Box::pin(WrappedRawStream { + node: self.node, + inner: Some(response.into_inner()), + decoder: FlightDecoder::default(), + frames: 0, + prefix: None, + after_prefix: Some(fault), + sibling, + parked: false, + done: false, + state: Arc::clone(&self.state), + }))) + } + + async fn do_put( + &self, + request: Request>, + ) -> std::result::Result>, Status> { + self.inner.do_put(request).await + } + + async fn do_action( + &self, + request: Request, + ) -> std::result::Result>, Status> { + let Some(region) = prepare_region(request.get_ref()) else { + return self.inner.do_action(request).await; + }; + self.state.push(Event::Prepare(self.node)); + match self.state.armed.lock().unwrap().as_ref() { + Some(ArmedFault::UnsupportedPreflight { region: armed }) if *armed == region => { + // The frozen unsupported shape is one explicit result followed by a clean end + // of stream, never a bare error of the action call. + let body = encode_prepare_raw_series_response(None) + .expect("the frozen unsupported body must encode"); + let answer: [std::result::Result; 1] = + [Ok(arrow_flight::Result { body: body.into() })]; + return Ok(Response::new(Box::pin(futures_util::stream::iter(answer)))); + } + Some(ArmedFault::FailingPreflight { + region: armed, + marker, + }) if *armed == region => { + return Err(peer_status(StatusCode::Internal, marker)); + } + _ => {} + } + self.inner.do_action(request).await + } + } + + /// The body of one raw read of the armed fixture. + /// + /// It owns the actual stream of the real region server, forwards its real payload prefix, + /// applies the fault of the case, and drops the actual stream before it acknowledges the + /// cancellation of its client. + struct WrappedRawStream { + /// The datanode whose region server produced the stream. + node: DatanodeId, + /// The actual stream of the real region server; [`Drop`] takes and drops it first. + inner: Option>, + /// Decodes the forwarded frames, which witnesses the first real record batch. + decoder: FlightDecoder, + /// The actual response frames forwarded so far, schema frame included. + frames: usize, + /// The real payload prefix witness, set once a record batch was forwarded. + prefix: Option, + /// The fault waiting for this read, applied once the prefix above was forwarded. + after_prefix: Option, + /// Waits for the hold of the sibling raw read of the third case before the late error of + /// this read is released; `None` for a read that does not fail. + sibling: Option>, + /// Whether the stream already reported its held state. + parked: bool, + /// Whether the stream already released its terminal item. + done: bool, + /// The case state of the cluster. + state: Arc, + } + + impl Stream for WrappedRawStream { + type Item = std::result::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.done { + return Poll::Ready(None); + } + if this.prefix.is_none() { + return this.poll_actual(cx); + } + match this.after_prefix.take() { + Some(AfterPrefix::Fail(status)) => { + if let Some(mut sibling) = this.sibling.take() + && Pin::new(&mut sibling).poll(cx).is_pending() + { + this.sibling = Some(sibling); + this.after_prefix = Some(AfterPrefix::Fail(status)); + return Poll::Pending; + } + this.done = true; + Poll::Ready(Some(Err(status))) + } + Some(AfterPrefix::Park) => { + this.after_prefix = Some(AfterPrefix::Park); + if !this.parked { + this.parked = true; + let _ = this.state.parked.send(this.node); + // The actual response of this read stays open behind the pending stream, + // and the failing sibling of the case is only released after this report. + if let Some(hold) = this.state.sibling_hold.lock().unwrap().take() { + let _ = hold.send(()); + } + } + Poll::Pending + } + // A wrapper only exists for a read with a fault, and both arms above either + // complete the stream or restore the fault before they return. + None => unreachable!("a wrapped raw read applies its fault exactly once"), + } + } + } + + impl WrappedRawStream { + /// Forwards the actual stream and witnesses the first real record batch of the prefix. + fn poll_actual(&mut self, cx: &mut Context<'_>) -> Poll::Item>> { + let Some(inner) = self.inner.as_mut() else { + return Poll::Ready(None); + }; + match ready!(inner.as_mut().poll_next(cx)) { + Some(Ok(flight_data)) => { + self.frames += 1; + let decoded = self.decoder.try_decode(&flight_data); + if self.prefix.is_none() + && matches!(decoded, Ok(Some(FlightMessage::RecordBatch(_)))) + { + let prefix = PayloadPrefix { + node: self.node, + frames: self.frames, + }; + self.prefix = Some(prefix); + self.state.prefixes.lock().unwrap().push(prefix); + } + Poll::Ready(Some(Ok(flight_data))) + } + Some(Err(status)) => { + self.done = true; + Poll::Ready(Some(Err(status))) + } + None => { + self.done = true; + Poll::Ready(None) + } + } + } + } + + impl Drop for WrappedRawStream { + fn drop(&mut self) { + // The actual region-server stream is dropped first, so the acknowledgement below + // reports a cancellation the real response has already observed. + drop(self.inner.take()); + let _ = self.state.dropped.send(self.node); + } + } + + /// The region of a Flight `DoGet` when its ticket carries the raw-series extension. + /// + /// The ticket of a region read is the encoded `api::v1::region::QueryRequest` of the caller, + /// so the extension key of its query context classifies the read without executing it. + fn raw_series_region(ticket: &[u8]) -> Option { + let request = RegionQueryRequest::decode(ticket).ok()?; + let extensions = request.header?.query_context?.extensions; + extensions + .contains_key(RAW_SERIES_REQUEST_EXTENSION_KEY) + .then_some(request.region_id) + } + + /// The region of a named raw-series preflight action. + fn prepare_region(action: &Action) -> Option { + if action.r#type != PREPARE_RAW_SERIES_ACTION { + return None; + } + RegionQueryRequest::decode(action.body.as_ref()) + .ok() + .map(|request| request.region_id) + } + + /// The peer status of a failed preflight or a failed raw read of a case. + /// + /// It carries the greptime error code as metadata, so the client preserves the code and can + /// never report the status as a bare `Unimplemented` decline of an absent action. + fn peer_status(code: StatusCode, marker: &str) -> Status { + let headers = common_error::from_err_code_msg_to_header(code as u32, marker); + Status::with_metadata( + tonic::Code::Internal, + marker, + tonic::metadata::MetadataMap::from_headers(headers), + ) + } + + /// The hook a case installs on the real TCP Flight listener of both datanodes. + type FaultFlightHook = dyn Fn(DatanodeId, DatanodeRegionServer) -> FlightCraftRef + Send + Sync; + + /// Builds one two-datanode cluster whose frontend owns the query options and the real clients, + /// with the case hook on the real TCP Flight listener of every datanode. + async fn build_hooked_cluster(name: &str, state: Arc) -> GreptimeDbCluster { + let hook: Arc = + Arc::new(move |node: DatanodeId, server: DatanodeRegionServer| { + let handler: FlightCraftRef = Arc::new(FaultFlight { + node, + inner: Arc::new(server), + state: Arc::clone(&state), + }); + handler + }); + GreptimeDbClusterBuilder::new(name) + .await + .with_datanodes(2) + .with_real_datanode_grpc_addr(true) + .with_real_frontend_clients(true) + .with_frontend_query_options(QueryOptions { + parallelism: 1, + experimental_native_promql: true, + ..Default::default() + }) + .with_datanode_flight_hook(hook) + .build(false) + .await + } + + /// Seeds the two-datanode fixture and returns the leader of every time partition. + async fn seed_fixture(frontend: &Arc) -> BTreeMap { + execute_sql(frontend, CREATE_TABLE).await; + execute_sql(frontend, INSERT_ROWS).await; + let leaders = region_leaders(frontend, TABLE).await; + assert_eq!( + 2, + leaders.len(), + "expected one region per time partition of {TABLE}, actual region leaders: {leaders:?}" + ); + assert_eq!( + BTreeSet::from([1_u64, 2_u64]), + leaders.values().copied().collect::>(), + "expected the time partitions of {TABLE} to be served by both datanodes, actual region \ + leaders: {leaders:?}" + ); + leaders + } + + /// Reads the stored fixture of `frontend` and proves it is complete. + /// + /// This runs for the seed check of a case and for the recovery check of a disarmed case. + async fn assert_stored_rows(frontend: &Arc) { + let stored = query_batches_within( + frontend, + &format!("SELECT ts, host, val FROM {TABLE} ORDER BY ts"), + QUERY_TIMEOUT, + ) + .await; + assert_eq!(expected_columns(), columns(&stored)); + assert_eq!( + expected_stored_rows(), + rows(&stored), + "unexpected stored rows of {TABLE}" + ); + } + + /// The datanodes of the fixture, which its two regions must span. + fn nodes(leaders: &BTreeMap) -> BTreeSet { + leaders.values().copied().collect() + } + + /// The sibling datanode of `node` in the two-datanode fixture. + fn sibling_node(leaders: &BTreeMap, node: DatanodeId) -> DatanodeId { + *leaders + .values() + .find(|leader| **leader != node) + .expect("the fixture must span two datanodes") + } + + /// Proves the expected traffic of every datanode of the fixture in one query window. + fn assert_traffic( + window: &[Event], + leaders: &BTreeMap, + expected: impl Fn(DatanodeId) -> Traffic, + ) { + for node in leaders.values() { + assert_eq!( + expected(*node), + Traffic::of(window, *node), + "unexpected traffic of the datanode {node}: {window:?}" + ); + } + } + + /// Proves that every preflight of `window` preceded its first read. + fn assert_prepares_first(window: &[Event]) { + let last_prepare = window + .iter() + .rposition(|event| matches!(event, Event::Prepare(_))); + let first_read = window + .iter() + .position(|event| !matches!(event, Event::Prepare(_))); + match (last_prepare, first_read) { + (Some(prepare), Some(read)) => assert!( + prepare < read, + "every preflight must precede the first read: {window:?}" + ), + _ => panic!("the window must contain a preflight and a read: {window:?}"), + } + } + + /// Proves that every node of `nodes` forwarded a real payload prefix of its actual response. + /// + /// A wrapper stream only reports a prefix once a record batch of the actual response was + /// forwarded, so a witness proves that the read really carried the payload of the region + /// server and not just the schema of an empty answer. + fn assert_payload_prefixes(state: &FaultState, nodes: impl IntoIterator) { + let prefixes = state.prefixes.lock().unwrap().clone(); + for node in nodes { + let prefix = prefixes + .iter() + .find(|prefix| prefix.node == node) + .unwrap_or_else(|| { + panic!("the read of the datanode {node} must forward a real payload prefix") + }); + assert!( + prefix.frames >= 2, + "the prefix of the datanode {node} must include the schema frame and a record \ + batch: {prefix:?}" + ); + } + } + + /// Runs the native `TQL EVAL` of the preflight-failure case and returns the debug chain of the + /// failure it must surface. + /// + /// A failure of the planning phase surfaces as the error of the call, and a failure of the + /// body surfaces as the terminal error of the returned stream; both are valid observations of + /// a preflight that fails before execution, so the case accepts either. Both branches assert + /// the peer status code of the failure before the diagnostic string is built, so a case that + /// loses the code cannot pass on a message that merely looks right. + async fn eval_failure(frontend: &Arc) -> String { + tokio::time::timeout(QUERY_TIMEOUT, async { + match try_execute_sql(frontend, EVAL).await { + Ok(output) => { + let OutputData::Stream(stream) = output.data else { + panic!("expected the native TQL EVAL to fail"); + }; + let error = collect_body_error(stream).await; + assert_eq!( + StatusCode::Internal, + error.status_code(), + "the peer status code must survive the body error, actual: {}", + error_chain(&error) + ); + error_chain(&error) + } + Err(error) => { + assert_eq!( + StatusCode::Internal, + error.status_code(), + "the peer status code must survive the planning error, actual: {}", + error_chain(&error) + ); + error_chain(&error) + } + } + }) + .await + .unwrap_or_else(|_| panic!("the faulted TQL EVAL must fail within {QUERY_TIMEOUT:?}")) + } + + /// Consumes a result stream and returns its terminal error. + /// + /// The consumed stream is the only owner of the query, so dropping it here is what cancels the + /// frontend side of the raw reads. + async fn collect_body_error( + mut stream: SendableRecordBatchStream, + ) -> common_recordbatch::error::Error { + loop { + match stream.next().await { + Some(Ok(_)) => continue, + Some(Err(error)) => return error, + None => panic!("the faulted body ended without the observed error"), + } + } + } + + /// Runs a query that must complete within `bound`. + async fn query_batches_within( + frontend: &Arc, + sql: &str, + bound: Duration, + ) -> RecordBatches { + tokio::time::timeout(bound, query_batches(frontend, sql)) + .await + .unwrap_or_else(|_| panic!("`{sql}` must finish within {bound:?}")) + } + + /// Awaits one cancellation acknowledgement per datanode, bounded by [`CANCEL_ACK_TIMEOUT`]. + async fn await_drop_acks( + acknowledgements: &mut mpsc::UnboundedReceiver, + leaders: &BTreeMap, + ) -> BTreeSet { + let mut acknowledged = BTreeSet::new(); + while acknowledged.len() < leaders.len() { + let acknowledgement = tokio::time::timeout(CANCEL_ACK_TIMEOUT, acknowledgements.recv()) + .await + .unwrap_or_else(|_| { + panic!( + "every cancelled raw read must drop its actual region-server stream within \ + {CANCEL_ACK_TIMEOUT:?}" + ) + }); + let Some(node) = acknowledgement else { + panic!("the drop acknowledgement channel must stay open"); + }; + acknowledged.insert(node); + } + acknowledged + } + + /// The debug view of an error and every source behind it. + /// + /// A peer status travels through several wrappers before it reaches a test, and the wrappers + /// of different layers print different parts of it, so the whole chain is searched instead of + /// the outermost display. + fn error_chain(error: &E) -> String { + let mut text = format!("{error:?}"); + let mut source = std::error::Error::source(error); + while let Some(cause) = source { + text.push_str(&format!("\n{cause:?}\n{cause}")); + source = std::error::Error::source(cause); + } + text + } + + /// The preflight of the greatest region id answers with the frozen unsupported body, so the + /// frontend must return the complete ordinary result without opening any raw read. + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_cluster_remote_unsupported_preflight_falls_back() { + common_telemetry::init_default_ut_logging(); + + let (parked, _parked_signals) = mpsc::unbounded_channel(); + let (dropped, _dropped_signals) = mpsc::unbounded_channel(); + let state = Arc::new(FaultState::new(parked, dropped)); + let enabled = build_hooked_cluster("native_promql_unsupported", state.clone()).await; + let disabled = build_cluster("native_promql_unsupported_disabled", 1, false).await; + let enabled_frontend = enabled.fe_instance().clone(); + let disabled_frontend = disabled.fe_instance().clone(); + + let leaders = seed_fixture(&enabled_frontend).await; + execute_sql(&disabled_frontend, CREATE_TABLE).await; + execute_sql(&disabled_frontend, INSERT_ROWS).await; + assert_stored_rows(&enabled_frontend).await; + + // The greatest region id is the one that answers the unsupported body. The case does not + // depend on the order in which the frontend works through its regions: that region must be + // preflighted exactly once and then read once over the ordinary path, the other region may + // still be preflighted before the decline is seen, so its preflight count is only bounded, + // and neither region may be opened as a raw read. + let unsupported = *leaders + .keys() + .next_back() + .expect("one region per time partition"); + state.arm(ArmedFault::UnsupportedPreflight { + region: unsupported, + }); + let start = state.events().len(); + + let native = query_batches_within(&enabled_frontend, EVAL, QUERY_TIMEOUT).await; + let ordinary = query_batches_within(&disabled_frontend, EVAL, QUERY_TIMEOUT).await; + + assert_eq!(expected_columns(), columns(&native)); + assert_eq!(expected_eval_rows(), rows(&native)); + assert_eq!(columns(&native), columns(&ordinary)); + assert_eq!(native.schema(), ordinary.schema()); + assert_eq!( + native.schema().arrow_schema(), + ordinary.schema().arrow_schema() + ); + assert_eq!(rows(&native), rows(&ordinary)); + + let log = state.events(); + let observed = &log[start..]; + let designated = leaders[&unsupported]; + let expected = Traffic { + prepare: 1, + raw_get: 0, + ordinary_get: 1, + }; + assert_eq!( + expected, + Traffic::of(observed, designated), + "the designated region {unsupported}: {observed:?}" + ); + let sibling = Traffic::of(observed, sibling_node(&leaders, designated)); + assert!( + sibling.prepare <= 1 && sibling.raw_get == 0 && sibling.ordinary_get == 1, + "the sibling region must be preflighted at most once and read once: {observed:?}" + ); + // Every preflight of both regions precedes the first read of the fallback. + assert_prepares_first(observed); + } + + /// The preflight of the greatest region id fails with an internal peer status that carries the + /// marker, so the frontend must fail without a read and without a fallback. + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_cluster_preflight_error_is_terminal() { + common_telemetry::init_default_ut_logging(); + + let (parked, _parked_signals) = mpsc::unbounded_channel(); + let (dropped, _dropped_signals) = mpsc::unbounded_channel(); + let state = Arc::new(FaultState::new(parked, dropped)); + let enabled = build_hooked_cluster("native_promql_preflight_error", state.clone()).await; + let frontend = enabled.fe_instance().clone(); + + let leaders = seed_fixture(&frontend).await; + assert_stored_rows(&frontend).await; + + // The greatest region id fails its preflight; the case does not depend on the order in + // which the frontend preflights its regions. + let failing = *leaders + .keys() + .next_back() + .expect("one region per time partition"); + state.arm(ArmedFault::FailingPreflight { + region: failing, + marker: PREFLIGHT_ERROR_MARKER, + }); + let start = state.events().len(); + + let failure = eval_failure(&frontend).await; + let log = state.events(); + let observed = &log[start..]; + + assert!( + failure.contains(PREFLIGHT_ERROR_MARKER), + "the peer preflight failure must surface unchanged, actual: {failure}" + ); + let designated = leaders[&failing]; + let expected = Traffic { + prepare: 1, + raw_get: 0, + ordinary_get: 0, + }; + assert_eq!( + expected, + Traffic::of(observed, designated), + "the designated region {failing}: {observed:?}" + ); + let sibling = Traffic::of(observed, sibling_node(&leaders, designated)); + assert!( + sibling.prepare <= 1 && sibling.raw_get == 0 && sibling.ordinary_get == 0, + "a failed preflight must not read or fall back at the sibling region: {observed:?}" + ); + } + + /// The raw read of the greatest region id forwards the real payload prefix of its actual + /// response and then fails late, while the read of the other region holds its actual response + /// open behind its own real payload prefix; the cancellation that follows the error must drop + /// both actual region-server streams. + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_cluster_late_body_error_after_real_prefix() { + common_telemetry::init_default_ut_logging(); + + let (parked, mut parked_signals) = mpsc::unbounded_channel(); + let (dropped, mut dropped_acks) = mpsc::unbounded_channel(); + let state = Arc::new(FaultState::new(parked, dropped)); + let enabled = build_hooked_cluster("native_promql_late_body_error", state.clone()).await; + let frontend = enabled.fe_instance().clone(); + + let leaders = seed_fixture(&frontend).await; + assert_stored_rows(&frontend).await; + + // The case does not depend on the order in which the frontend reads its regions: the lower + // region id holds its read open, and the higher one waits for that hold before it fails, + // so the sibling response is held whichever read the frontend opens first. + let mut regions = leaders.keys().copied(); + let sibling_region = regions.next().expect("one region per time partition"); + let selected_region = regions.next().expect("one region per time partition"); + state.arm(ArmedFault::LateRawError { + selected: selected_region, + sibling: sibling_region, + marker: LATE_BODY_ERROR_MARKER, + }); + let start = state.events().len(); + + // One bound covers the planning call and the body of the faulted query. + let failure = tokio::time::timeout(QUERY_TIMEOUT, async { + let output = try_execute_sql(&frontend, EVAL) + .await + .expect("both preflights are supported, so the TQL EVAL must return its body"); + let OutputData::Stream(stream) = output.data else { + panic!("expected the body stream of the TQL EVAL"); + }; + collect_body_error(stream).await + }) + .await + .unwrap_or_else(|_| { + panic!("the late body error must be released within {QUERY_TIMEOUT:?}") + }); + + assert_eq!( + StatusCode::Internal, + failure.status_code(), + "the peer error code must be preserved, actual: {}", + error_chain(&failure) + ); + assert!( + error_chain(&failure).contains(LATE_BODY_ERROR_MARKER), + "the peer status of the late body error must surface unchanged, actual: {}", + error_chain(&failure) + ); + + // The held sibling reported itself while the error was still unreleased, and no other raw + // read of the case parked. + let held = parked_signals + .try_recv() + .expect("the held sibling must report itself before the late error is released"); + assert_eq!( + leaders[&sibling_region], held, + "the read of the held region must park" + ); + assert!( + parked_signals.try_recv().is_err(), + "only one raw read of the case may park" + ); + + let log = state.events(); + let observed = &log[start..]; + assert_traffic(observed, &leaders, |_| Traffic { + prepare: 1, + raw_get: 1, + ordinary_get: 0, + }); + assert_prepares_first(observed); + // Both reads forwarded the real payload prefix of their actual response before the error. + assert_payload_prefixes(&state, nodes(&leaders)); + + // The cancelled reads drop the actual region-server stream first and acknowledge after. + let acknowledged = await_drop_acks(&mut dropped_acks, &leaders).await; + assert_eq!( + nodes(&leaders), + acknowledged, + "every raw read must acknowledge the cancellation its error caused" + ); + } + + /// Both raw reads forward the real payload prefix of their actual response and hold it open; + /// the frontend stream is cancelled while they are held, and the disarmed case must still + /// serve the complete fixture and the native `TQL EVAL`. + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_cluster_frontend_cancel_drops_server_streams() { + common_telemetry::init_default_ut_logging(); + + let (parked, mut parked_signals) = mpsc::unbounded_channel(); + let (dropped, mut dropped_acks) = mpsc::unbounded_channel(); + let state = Arc::new(FaultState::new(parked, dropped)); + let enabled = build_hooked_cluster("native_promql_frontend_cancel", state.clone()).await; + let disabled = build_cluster("native_promql_frontend_cancel_disabled", 1, false).await; + let frontend = enabled.fe_instance().clone(); + let disabled_frontend = disabled.fe_instance().clone(); + + let leaders = seed_fixture(&frontend).await; + execute_sql(&disabled_frontend, CREATE_TABLE).await; + execute_sql(&disabled_frontend, INSERT_ROWS).await; + assert_stored_rows(&frontend).await; + + let regions = leaders.keys().copied().collect::>(); + let region_count = regions.len(); + state.arm(ArmedFault::ParkedRawStreams { regions }); + let start = state.events().len(); + + // One bound covers the planning call, the body and the readiness phase below: the client + // stream is driven until both raw reads are held, and nothing else is polled. No collector + // holds another copy of the stream, so the drop below is the one cancellation of the + // query. + let (stream, held) = tokio::time::timeout(QUERY_TIMEOUT, async { + let output = try_execute_sql(&frontend, EVAL) + .await + .expect("both preflights are supported, so the TQL EVAL must return its body"); + let OutputData::Stream(mut stream) = output.data else { + panic!("expected the body stream of the TQL EVAL"); + }; + let mut held_nodes = BTreeSet::new(); + while held_nodes.len() < region_count { + tokio::select! { + batch = stream.next() => match batch { + Some(Ok(_)) => {} + Some(Err(error)) => panic!("a held raw read must not fail: {error}"), + None => panic!("the TQL EVAL ended before both raw reads were held"), + }, + signal = parked_signals.recv() => { + let node = signal.expect("the hold witness channel must stay open"); + held_nodes.insert(node); + } + } + } + (stream, held_nodes) + }) + .await + .unwrap_or_else(|_| panic!("both raw reads must be held within {QUERY_TIMEOUT:?}")); + + assert_eq!( + nodes(&leaders), + held, + "both datanodes must hold a raw read of the fixture" + ); + + drop(stream); + + // The cancellation reaches the server-side wrappers, which drop the actual region-server + // stream before they acknowledge it. + let acknowledged = await_drop_acks(&mut dropped_acks, &leaders).await; + assert_eq!( + held, acknowledged, + "every held raw read must observe the cancellation of its actual stream" + ); + assert_payload_prefixes(&state, nodes(&leaders)); + + // The counter window of the cancelled query ends before the follow-up queries below, which + // are asserted on their own. + let follow_up_start = state.events().len(); + + // The same frontend must still serve the complete stored fixture through ordinary reads of + // both datanodes, so the cancellation did not wedge the paths this case used. The disabled + // cluster below only supplies the expected result of the native follow-up: it cannot prove + // anything about the cancelled one. + state.disarm(); + assert_stored_rows(&frontend).await; + let native = query_batches_within(&frontend, EVAL, QUERY_TIMEOUT).await; + let ordinary = query_batches_within(&disabled_frontend, EVAL, QUERY_TIMEOUT).await; + assert_eq!(expected_columns(), columns(&native)); + assert_eq!(expected_eval_rows(), rows(&native)); + assert_eq!(columns(&native), columns(&ordinary)); + assert_eq!(native.schema(), ordinary.schema()); + assert_eq!( + native.schema().arrow_schema(), + ordinary.schema().arrow_schema() + ); + assert_eq!(expected_eval_rows(), rows(&ordinary)); + assert_eq!(rows(&native), rows(&ordinary)); + + // The cancelled query is the window before the follow-up queries: every region of the + // fixture was preflighted and read once, no ordinary read happened, and nothing was + // replayed. + let log = state.events(); + let observed = &log[start..follow_up_start]; + assert_traffic(observed, &leaders, |_| Traffic { + prepare: 1, + raw_get: 1, + ordinary_get: 0, + }); + } +} + +/// Multi-`Float64` acceptance of the whole-table native instant mapping, on a standalone frontend +/// and on the real two-datanode cluster. +/// +/// Both shapes of this module declare their `Float64` fields in a deliberately non-lexical order +/// (`z_first`, `a_second`, optionally `m_third`), so a mapping that sorts or reorders field names +/// fails the fixture instead of a plan string, and the fixture makes the staleness rule of the +/// ordinary selector observable from the complete result alone: the checked first field alone +/// decides whether a sample is stale, whatever the other fields carry. +/// +/// * the stale marker in the unchecked second field at 3000 must keep its exact bits in the row +/// the evaluation point returns; +/// * the stale marker in the checked first field at 4000 must suppress that evaluation point +/// without reviving the older sample of 3000; +/// * the `NULL` first field at 5000 keeps a row whose first field is `NULL` and whose second field +/// keeps its ordinary `NaN` payload. +/// +/// The sparse `beta` series has one sample in each partition of the distributed shapes and none in +/// between, so the lookback of 2000, 3000 and 4000 is carried by its first sample while its 5000 +/// sample lives in the region of the other datanode. +mod multifloat_acceptance { + use api::v1::helper::{field_column_schema, tag_column_schema, time_index_column_schema}; + use api::v1::value::ValueData; + use api::v1::{ColumnDataType, Row, RowInsertRequest, RowInsertRequests, Rows, Value}; + use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS; + + use crate::standalone::GreptimeDbStandaloneBuilder; + use crate::test_util::execute_sql; + + use super::*; + + /// One table shape: the `Float64` fields in their declared, deliberately non-lexical order. + /// + /// The order is the fixture of the staleness rule: a mapping that sorts field names would check + /// `a_second` or `m_third` at 3000 instead of `z_first`. + struct Shape { + table: &'static str, + fields: &'static [&'static str], + } + + /// The two shapes of this lane: two and three `Float64` fields. + const SHAPES: &[Shape] = &[ + Shape { + table: "native_multifloat_two", + fields: &["z_first", "a_second"], + }, + Shape { + table: "native_multifloat_three", + fields: &["z_first", "a_second", "m_third"], + }, + ]; + + /// The exact bit patterns of the fixture and of its expectation: no cell is ever compared + /// through `f64` equality, which would hide a `NaN` payload or a signed zero. + const NEGATIVE_ZERO: u64 = 0x8000_0000_0000_0000; + const POSITIVE_ZERO: u64 = 0x0000_0000_0000_0000; + const TWO: u64 = 0x4000_0000_0000_0000; + const THREE: u64 = 0x4008_0000_0000_0000; + const FOUR: u64 = 0x4010_0000_0000_0000; + const SEVEN: u64 = 0x401c_0000_0000_0000; + const EIGHT: u64 = 0x4020_0000_0000_0000; + const NINE: u64 = 0x4022_0000_0000_0000; + /// An ordinary quiet `NaN` that is not the Prometheus stale marker. + const ORDINARY_NAN_ONE: u64 = 0x7ff8_0000_0000_0001; + /// A second ordinary quiet `NaN`, so the two planted payloads cannot be confused. + const ORDINARY_NAN_TWO: u64 = 0x7ff8_0000_0000_0002; + + /// The planted bits of every fixture row in insertion order; `None` is a stored `NULL`. + /// + /// `alpha` fills the evaluation grid with the three staleness cases, and the sparse `beta` + /// series carries the lookback across the partition at 3000. The third slot is only planted + /// into the three-field shape. + const FIXTURE: &[(i64, &str, [Option; 3])] = &[ + ( + 1_000, + "alpha", + [Some(NEGATIVE_ZERO), Some(POSITIVE_ZERO), None], + ), + (2_000, "alpha", [Some(ORDINARY_NAN_ONE), None, Some(TWO)]), + ( + 3_000, + "alpha", + [ + Some(THREE), + Some(PROMETHEUS_STALE_NAN_BITS), + Some(NEGATIVE_ZERO), + ], + ), + ( + 4_000, + "alpha", + [Some(PROMETHEUS_STALE_NAN_BITS), Some(FOUR), Some(FOUR)], + ), + ( + 5_000, + "alpha", + [None, Some(ORDINARY_NAN_TWO), Some(POSITIVE_ZERO)], + ), + (1_000, "beta", [Some(SEVEN), None, None]), + (5_000, "beta", [Some(EIGHT), Some(NINE), None]), + ]; + + /// The complete result of `TQL EVAL (1, 5, '1s')` over any shape, in the only sort order the + /// comparison uses: `(timestamp, host)`. + /// + /// Every cell is the exact `to_bits` of the source row its evaluation point selected, and + /// `alpha` has no row at 4000 at all. The third slot is only compared by the three-field shape. + const EXPECTED_RESULT: &[(i64, &str, [Option; 3])] = &[ + ( + 1_000, + "alpha", + [Some(NEGATIVE_ZERO), Some(POSITIVE_ZERO), None], + ), + (1_000, "beta", [Some(SEVEN), None, None]), + (2_000, "alpha", [Some(ORDINARY_NAN_ONE), None, Some(TWO)]), + (2_000, "beta", [Some(SEVEN), None, None]), + ( + 3_000, + "alpha", + [ + Some(THREE), + Some(PROMETHEUS_STALE_NAN_BITS), + Some(NEGATIVE_ZERO), + ], + ), + (3_000, "beta", [Some(SEVEN), None, None]), + (4_000, "beta", [Some(SEVEN), None, None]), + ( + 5_000, + "alpha", + [None, Some(ORDINARY_NAN_TWO), Some(POSITIVE_ZERO)], + ), + (5_000, "beta", [Some(EIGHT), Some(NINE), None]), + ]; + + /// One `Float64` cell of a planted row: the exact bits, or a stored `NULL`. + fn float_cell(bits: Option) -> Value { + bits.map(|bits| ValueData::F64Value(f64::from_bits(bits)).into()) + .unwrap_or_default() + } + + /// The partition clause of the distributed shapes: both regions split every series at 3000 ms, + /// so the first samples of every series live in another region than the last ones. + const PARTITION: &str = + " PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:00:03', ts >= '1970-01-01 00:00:03')"; + + /// The complete `DDL` of `shape`; a distributed shape appends [`PARTITION`]. + fn create_table_sql(shape: &Shape, partitioned: bool) -> String { + let fields = shape + .fields + .iter() + .map(|field| format!("{field} DOUBLE")) + .collect::>() + .join(", "); + let partition = if partitioned { PARTITION } else { "" }; + format!( + "CREATE TABLE {} (ts TIMESTAMP(3), host STRING, {fields}, TIME INDEX (ts), PRIMARY \ + KEY (host)){partition} ENGINE=mito", + shape.table + ) + } + + /// The `TQL EVAL` of one shape: the grid evaluates every planted second from 1000 to 5000. + fn eval_sql(shape: &Shape) -> String { + format!("TQL EVAL (1, 5, '1s') {}", shape.table) + } + + /// The `TQL ANALYZE VERBOSE` of one shape. + fn analyze_sql(shape: &Shape) -> String { + format!("TQL ANALYZE VERBOSE (1, 5, '1s') {}", shape.table) + } + + /// The complete column list of a result of `shape`, in the declared field order. + fn planned_columns(shape: &Shape) -> Vec<(String, DataType)> { + let mut columns = vec![ + ( + "ts".to_string(), + DataType::Timestamp(TimeUnit::Millisecond, None), + ), + ("host".to_string(), DataType::Utf8), + ]; + columns.extend( + shape + .fields + .iter() + .map(|field| ((*field).to_string(), DataType::Float64)), + ); + columns + } + + /// Reads every planned field of `batches` by name and keeps the exact bits of every cell: + /// `None` is a `NULL` and every other cell is its `to_bits`, so no `f64` equality can hide a + /// payload. The rows are sorted only by `(timestamp, host)`, the order of every expectation. + fn bit_rows( + batches: &RecordBatches, + shape: &Shape, + ) -> Vec<(i64, Option, Vec>)> { + assert_eq!( + 2 + shape.fields.len(), + batches.schema().arrow_schema().fields().len(), + "unexpected result column count of {}", + shape.table + ); + let mut rows: Vec<(i64, Option, Vec>)> = Vec::new(); + for batch in batches.iter() { + let batch = batch.df_record_batch(); + let ts = batch + .column_by_name("ts") + .unwrap_or_else(|| panic!("the result of {} must carry ts", shape.table)) + .as_any() + .downcast_ref::() + .unwrap(); + let host = batch + .column_by_name("host") + .unwrap_or_else(|| panic!("the result of {} must carry host", shape.table)) + .as_any() + .downcast_ref::() + .unwrap(); + let fields = shape + .fields + .iter() + .map(|field| { + batch + .column_by_name(field) + .unwrap_or_else(|| { + panic!("the result of {} must carry {field}", shape.table) + }) + .as_any() + .downcast_ref::() + .unwrap() + }) + .collect::>(); + for index in 0..batch.num_rows() { + rows.push(( + ts.value(index), + (!host.is_null(index)).then(|| host.value(index).to_string()), + fields + .iter() + .map(|field| (!field.is_null(index)).then(|| field.value(index).to_bits())) + .collect(), + )); + } + } + rows.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))); + rows + } + + /// The complete stored fixture of `shape` in the order of the stored check (`ts`, `host`). + fn fixture_stored_rows(shape: &Shape) -> Vec<(i64, Option, Vec>)> { + let mut rows = FIXTURE + .iter() + .map(|(ts, host, bits)| { + ( + *ts, + Some((*host).to_string()), + bits[..shape.fields.len()].to_vec(), + ) + }) + .collect::>(); + rows.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))); + rows + } + + /// The complete expected result of `shape`, with one slot per planned field. + fn fixture_result_rows(shape: &Shape) -> Vec<(i64, Option, Vec>)> { + EXPECTED_RESULT + .iter() + .map(|(ts, host, bits)| { + ( + *ts, + Some((*host).to_string()), + bits[..shape.fields.len()].to_vec(), + ) + }) + .collect() + } + + /// Seeds `shape` through the row-insert API of `frontend`: every planted `Float64` keeps its + /// exact bits, which no text protocol and no `SQL` literal can guarantee. + /// + /// The complete `DDL` above predeclares every column, so the insert never accommodates a + /// dynamic schema. + async fn ingest(frontend: &Arc, shape: &Shape) { + let mut schema = vec![ + time_index_column_schema("ts", ColumnDataType::TimestampMillisecond), + tag_column_schema("host", ColumnDataType::String), + ]; + schema.extend( + shape + .fields + .iter() + .map(|field| field_column_schema(field, ColumnDataType::Float64)), + ); + let rows = FIXTURE + .iter() + .map(|(ts, host, bits)| Row { + values: std::iter::once(ValueData::TimestampMillisecondValue(*ts).into()) + .chain(std::iter::once( + ValueData::StringValue((*host).to_string()).into(), + )) + .chain(bits[..shape.fields.len()].iter().copied().map(float_cell)) + .collect(), + }) + .collect::>(); + let output = frontend + .handle_row_inserts( + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: shape.table.to_string(), + rows: Some(Rows { schema, rows }), + }], + }, + QueryContext::arc(), + false, + false, + ) + .await + .unwrap_or_else(|error| { + panic!("inserting the fixture of {} failed: {error}", shape.table) + }); + assert!( + matches!(output.data, OutputData::AffectedRows(rows) if rows == FIXTURE.len()), + "expected the row insert of {} to affect {} rows", + shape.table, + FIXTURE.len() + ); + } + + /// Reads the whole stored fixture of `shape` through ordinary `SQL` before any `TQL` + /// assertion: the exact column list, the exact `NULL`s and the exact bits of every planted + /// float prove that the row insert reached the region(s) without normalizing a payload. + async fn assert_stored(frontend: &Arc, shape: &Shape) { + let sql = format!( + "SELECT ts, host, {} FROM {} ORDER BY ts, host", + shape.fields.join(", "), + shape.table + ); + let stored = query_batches(frontend, &sql).await; + assert_eq!(planned_columns(shape), columns(&stored)); + assert_eq!( + fixture_stored_rows(shape), + bit_rows(&stored, shape), + "unexpected stored fixture of {}", + shape.table + ); + } + + /// Runs the native `TQL EVAL` of `shape` once, proves its complete result against the planted + /// bits and returns it for the schema comparison with the ordinary result. + async fn eval_native(frontend: &Arc, shape: &Shape) -> RecordBatches { + let native = query_batches(frontend, &eval_sql(shape)).await; + assert_eq!(planned_columns(shape), columns(&native)); + assert_eq!( + fixture_result_rows(shape), + bit_rows(&native, shape), + "unexpected native result of {}", + shape.table + ); + native + } + + /// Runs one native and one ordinary eval of `shape` and proves both complete results against + /// the planted bits: the ordinary result is the independent oracle of the literals, and the + /// complete public schema of the two must be unchanged, nullability and metadata included. + async fn assert_eval(enabled: &Arc, ordinary: &Arc, shape: &Shape) { + let native = eval_native(enabled, shape).await; + let normal = query_batches(ordinary, &eval_sql(shape)).await; + assert_eq!(planned_columns(shape), columns(&normal)); + assert_eq!( + fixture_result_rows(shape), + bit_rows(&normal, shape), + "unexpected ordinary result of {}", + shape.table + ); + assert_eq!(columns(&native), columns(&normal)); + assert_eq!(native.schema(), normal.schema()); + assert_eq!( + native.schema().arrow_schema(), + normal.schema().arrow_schema() + ); + } + + /// The `ANALYZE VERBOSE` plan of `shape` on `frontend`. + async fn analyze_plan(frontend: &Arc, shape: &Shape) -> String { + query_pretty(frontend, &analyze_sql(shape)).await + } + + /// Proves the native plan of `shape`: the native instant manipulation always, and the + /// raw-series merge only when `raw_merge` states it, because only the distributed shapes span + /// two datanodes and must merge their regions. + async fn assert_native_plan(frontend: &Arc, shape: &Shape, raw_merge: Option) { + let plan = analyze_plan(frontend, shape).await; + assert!( + plan.contains("NativeInstantManipulateExec"), + "the native instant manipulation is missing for the multi-Float64 shape {}:\n{plan}", + shape.table + ); + if let Some(raw_merge) = raw_merge { + assert_eq!( + raw_merge, + plan.contains("NativeRawMergeExec"), + "the raw-series merge of {} must be {raw_merge} for this deployment:\n{plan}", + shape.table + ); + } + } + + /// Proves that the flag-free `frontend` keeps the ordinary plan of `shape`. + async fn assert_ordinary_plan(frontend: &Arc, shape: &Shape) { + let plan = analyze_plan(frontend, shape).await; + assert!( + !plan.contains("NativeInstantManipulateExec"), + "the flag-free frontend unexpectedly used the native instant manipulation for {}:\n\ + {plan}", + shape.table + ); + } + + /// Proves that the time partition of `shape` produced two regions, one leader per datanode, + /// and returns the leader of every region. + async fn assert_two_datanode_regions( + frontend: &Arc, + shape: &Shape, + ) -> BTreeMap { + let leaders = region_leaders(frontend, shape.table).await; + assert_eq!( + 2, + leaders.len(), + "expected one region per time partition of {}, actual region leaders: {leaders:?}", + shape.table + ); + assert_eq!( + BTreeSet::from([1_u64, 2_u64]), + leaders.values().copied().collect::>(), + "expected the time partitions of {} to be served by both datanodes, actual region \ + leaders: {leaders:?}", + shape.table + ); + leaders + } + + /// The raw-series counters of every datanode that leads a region of one shape. + fn rpc_snapshot( + cluster: &GreptimeDbCluster, + leaders: &BTreeMap, + ) -> BTreeMap { + leaders + .values() + .map(|datanode| { + ( + *datanode, + ( + rpc_requests(cluster, *datanode), + prepare_requests(cluster, *datanode), + ), + ) + }) + .collect() + } + + /// Proves that everything since `baseline` read and preflighted every region it covers + /// exactly once: one raw read and one named preflight per datanode, so one eval of any shape + /// costs exactly one Flight `DoGet` and one Flight `DoAction` per region leader. + fn assert_one_raw_rpc_per_node( + cluster: &GreptimeDbCluster, + baseline: &BTreeMap, + ) { + for (datanode, (do_get, prepare)) in baseline { + assert_eq!( + do_get + 1, + rpc_requests(cluster, *datanode), + "expected exactly one raw-series read at the datanode {datanode} since the baseline" + ); + assert_eq!( + prepare + 1, + prepare_requests(cluster, *datanode), + "expected exactly one raw-series preflight at the datanode {datanode} since the \ + baseline" + ); + } + } + + /// Flushes `shape` and proves that the same grid is still served by the native plan: a + /// normalizing write or read path of a flushed value could only fail here. + async fn flush_shape(frontend: &Arc, shape: &Shape, raw_merge: Option) { + execute_sql(frontend, &format!("ADMIN FLUSH_TABLE('{}')", shape.table)).await; + assert_native_plan(frontend, shape, raw_merge).await; + } + + /// Runs the standalone case at parallelism 1 for both shapes. + /// + /// The standalone table carries no partition clause, so the whole table is one region; the + /// plan of that local route is asserted through the native instant manipulation only. The + /// second instance keeps the flag off and supplies the ordinary result of the same fixture. + async fn run_standalone_case(name: &str) { + common_telemetry::init_default_ut_logging(); + + let enabled = GreptimeDbStandaloneBuilder::new(&format!("{name}_enabled")) + .with_query_options(QueryOptions { + parallelism: 1, + experimental_native_promql: true, + ..Default::default() + }) + .build() + .await; + let ordinary = GreptimeDbStandaloneBuilder::new(&format!("{name}_ordinary")) + .with_query_options(QueryOptions { + parallelism: 1, + experimental_native_promql: false, + ..Default::default() + }) + .build() + .await; + let enabled_frontend = enabled.fe_instance().clone(); + let ordinary_frontend = ordinary.fe_instance().clone(); + + for shape in SHAPES { + execute_sql(&enabled_frontend, &create_table_sql(shape, false)).await; + execute_sql(&ordinary_frontend, &create_table_sql(shape, false)).await; + ingest(&enabled_frontend, shape).await; + ingest(&ordinary_frontend, shape).await; + + // The ordinary read proves the stored bits of the whole table before any `TQL` runs. + assert_stored(&enabled_frontend, shape).await; + + assert_native_plan(&enabled_frontend, shape, None).await; + assert_ordinary_plan(&ordinary_frontend, shape).await; + + assert_eval(&enabled_frontend, &ordinary_frontend, shape).await; + + // The flush moves the samples of every series from the memtable into an SST; the same + // grid must still be served natively and must still return the exact same bits. + flush_shape(&enabled_frontend, shape, None).await; + eval_native(&enabled_frontend, shape).await; + } + } + + /// Runs the two-datanode case at `parallelism` for both shapes. + /// + /// The frontend carries the flag while every datanode keeps its default, exactly like a + /// deployment where the planning node opted in, and the datanodes are reachable at the + /// addresses of the table routes, so both its named preflight and its raw-series read are + /// counted. A second, flag-free cluster serves the same fixture and supplies the ordinary + /// result the complete public schema is compared with. + async fn run_cluster_case(name: &str, parallelism: usize) { + common_telemetry::init_default_ut_logging(); + + let enabled = build_cluster(&format!("{name}_enabled"), parallelism, true).await; + let disabled = build_cluster(&format!("{name}_disabled"), parallelism, false).await; + let enabled_frontend = enabled.fe_instance().clone(); + let disabled_frontend = disabled.fe_instance().clone(); + + for shape in SHAPES { + execute_sql(&enabled_frontend, &create_table_sql(shape, true)).await; + execute_sql(&disabled_frontend, &create_table_sql(shape, true)).await; + ingest(&enabled_frontend, shape).await; + ingest(&disabled_frontend, shape).await; + + // Each shape is one region per time partition, and the two regions must be served by + // the two different datanodes: only then does every series span both of them. + let leaders = assert_two_datanode_regions(&enabled_frontend, shape).await; + + // The ordinary read proves the seeded rows of both datanodes are complete and + // bit-exact before any `TQL` runs. + assert_stored(&enabled_frontend, shape).await; + + assert_native_plan(&enabled_frontend, shape, Some(true)).await; + assert_ordinary_plan(&disabled_frontend, shape).await; + + // Seeding and planning are done: from here on only the `TQL EVAL` below may move the + // counters, so the baseline is taken after the analyze and before the eval. + let baseline = rpc_snapshot(&enabled, &leaders); + assert_eval(&enabled_frontend, &disabled_frontend, shape).await; + assert_one_raw_rpc_per_node(&enabled, &baseline); + + // The flushed regions must still be served by the native path; a fallback below would + // make the repeat eval vacuous. + flush_shape(&enabled_frontend, shape, Some(true)).await; + let flushed_baseline = rpc_snapshot(&enabled, &leaders); + eval_native(&enabled_frontend, shape).await; + assert_one_raw_rpc_per_node(&enabled, &flushed_baseline); + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_multifloat_standalone_p1() { + run_standalone_case("native_promql_multifloat_standalone_p1").await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_multifloat_cluster_p1() { + run_cluster_case("native_promql_multifloat_cluster_p1", 1).await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_native_promql_multifloat_cluster_p4() { + run_cluster_case("native_promql_multifloat_cluster_p4", 4).await; + } +} 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 7c696e7373e..f8675717ac7 100644 --- a/tests-integration/src/tests/nested_merge_scan_capability_test.rs +++ b/tests-integration/src/tests/nested_merge_scan_capability_test.rs @@ -13,11 +13,12 @@ // limitations under the License. //! Exercises hand-built nested `MergeScan` plans at datanode execution, not optimizer behavior. -//! The outer `handle_remote_read` request is in-process; inner region reads use real TCP Flight. -//! The probe scan resolves against the request's region catalog, while the nested payload resolves -//! against the engine catalog; distinct column names ensure these scopes cannot be confused. -//! Success compares the complete duplicate-sensitive result multiset with frontend SQL and known -//! rows. Missing inner tables and closed remote inner regions must each fail the whole query. +//! Existing nested-plan tests use in-process outer `handle_remote_read` requests; inner region +//! reads use real TCP Flight. The standalone requester baseline below calls an actual datanode's +//! `handle_query` over TCP Flight. The probe scan resolves against the request's region catalog, +//! while the nested payload resolves against the engine catalog; distinct column names ensure +//! these scopes cannot be confused. Success compares complete duplicate-sensitive results with +//! frontend SQL and known rows. Missing inner tables and closed remote inner regions must each fail. use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -28,9 +29,12 @@ use client::region::RegionRequester; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; use common_grpc::channel_manager::ChannelManager; +use common_meta::error::Result as MetaResult; use common_query::Output; +use common_query::request::RawSeriesRequest; use common_recordbatch::{RecordBatch, RecordBatches, SendableRecordBatchStream}; use common_telemetry::info; +use datafusion::logical_expr::TableSource; use datafusion_expr::{JoinType, LogicalPlan, LogicalPlanBuilder}; use datanode::region_server::RegionServer; use frontend::instance::Instance; @@ -40,6 +44,7 @@ use query::parser::QueryLanguageParser; use query::query_engine::DefaultSerializer; use servers::query_handler::sql::SqlQueryHandler; use session::context::{QueryContext, QueryContextRef}; +use store_api::region_engine::SendableRawSeriesStream; use store_api::region_request::{RegionCloseRequest, RegionRequest}; use store_api::storage::RegionId; use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan}; @@ -73,6 +78,85 @@ const BUILD_ROWS: &[(i32, i32, i32)] = &[ (121, 40, 5), ]; +#[tokio::test(flavor = "multi_thread")] +async fn test_region_requester_scan_over_tcp_flight() { + use common_meta::node_manager::Datanode; + use common_query::request::QueryRequest as LogicalQueryRequest; + + common_telemetry::init_default_ut_logging(); + + let cluster = build_cluster("test_region_requester_scan_over_tcp_flight").await; + let frontend = cluster.fe_instance().clone(); + prepare_tables(&frontend).await; + + let leaders = region_leaders(&frontend, PROBE_TABLE).await; + assert_eq!( + 2, + leaders.len(), + "expected every probe region to have a leader" + ); + + let sql = format!("SELECT a_id, probe_key, probe_v FROM {PROBE_TABLE} WHERE probe_key >= 20"); + let reference = query_pretty(&frontend, &sql, query_ctx()).await; + let expected = multiset(table_cells(&reference)); + assert_eq!( + vec![vec!["120", "30", "300"], vec!["2", "20", "200"]], + expected, + "unexpected filtered frontend SQL result:\n{reference}" + ); + + let query_ctx = query_ctx(); + let plan = plan_sql(&frontend, &sql, &query_ctx).await; + let mut rows = Vec::new(); + for (region_id, (datanode_id, address)) in &leaders { + let baseline = rpc_requests(&cluster, *datanode_id); + let client = Client::with_query_and_control_managers( + ChannelManager::new(), + ChannelManager::new(), + [address.as_str()], + ); + let requester = RegionRequester::new(client, false, false); + let stream = Datanode::handle_query( + &requester, + LogicalQueryRequest { + header: Some(region_request_header(&query_ctx)), + region_id: RegionId::from_u64(*region_id), + plan: plan.clone(), + }, + ) + .await + .unwrap_or_else(|e| panic!("Flight query for region {region_id} failed: {e}")); + let batches = RecordBatches::try_collect(stream) + .await + .unwrap_or_else(|e| panic!("Flight stream for region {region_id} failed: {e}")); + for batch in batches.iter() { + let names = batch + .df_record_batch() + .schema_ref() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(); + assert_eq!(vec!["a_id", "probe_key", "probe_v"], names); + } + rows.extend(table_cells( + &batches + .pretty_print() + .expect("record batches are printable"), + )); + assert_eq!( + baseline + 1, + rpc_requests(&cluster, *datanode_id), + "expected exactly one DoGet for region {region_id} at datanode {datanode_id}" + ); + } + assert_eq!( + expected, + multiset(rows), + "Flight results differ from SQL oracle:\n{reference}" + ); +} + #[tokio::test(flavor = "multi_thread")] async fn test_nested_merge_scan_capability_join_across_datanodes() { common_telemetry::init_default_ut_logging(); @@ -747,3 +831,1269 @@ fn multiset(mut rows: Vec>) -> Vec> { rows.sort(); rows } + +fn table_source(plan: &LogicalPlan) -> Option> { + match plan { + LogicalPlan::TableScan(scan) => Some(scan.source.clone()), + _ => plan.inputs().into_iter().find_map(table_source), + } +} + +async fn expect_raw_unsupported(result: MetaResult) -> String { + use futures_util::TryStreamExt; + + match result { + Err(error) => error_chain(&error), + Ok(stream) => match stream.try_collect::>().await { + Err(error) => error_chain(&error), + Ok(chunks) => panic!( + "unsupported raw query unexpectedly returned {} chunks", + chunks.len() + ), + }, + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_single_region_raw_flight_preserves_typed_filter_and_snapshot() { + use common_meta::node_manager::Datanode; + use common_query::request::{QueryRequest as LogicalQueryRequest, RawSeriesTag}; + use datafusion::arrow::array::{Array, Float64Array}; + use datafusion::common::TableReference; + use datafusion_expr::{col, lit}; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::SampleRef; + use futures_util::TryStreamExt; + use mito2::test_util::sst_util::new_primary_key; + use store_api::codec::PrimaryKeyEncoding; + use store_api::region_engine::RawLabelSource; + + const TABLE: &str = "native_raw_flight_single_region"; + common_telemetry::init_default_ut_logging(); + let cluster = build_cluster("test_native_single_region_raw_flight").await; + let frontend = cluster.fe_instance().clone(); + execute_sql(&frontend, &format!( + "CREATE TABLE {TABLE} (host STRING, left_value DOUBLE, right_value DOUBLE, predicate_value BIGINT, ts TIMESTAMP, TIME INDEX (ts), PRIMARY KEY(host)) ENGINE=mito" + )).await; + execute_sql(&frontend, &format!( + "INSERT INTO {TABLE} VALUES ('alpha', 1.25, 11.0, 9007199254740992, 1000), ('alpha', NULL, -0.0, 9007199254740993, 2000), ('alpha', 3.75, 13.0, 9007199254740994, 3000)" + )).await; + + let frontend_sql = format!( + "SELECT ts, left_value, right_value FROM {TABLE} WHERE predicate_value > 9007199254740992" + ); + let normal_before = query_pretty(&frontend, &frontend_sql, query_ctx()).await; + assert_eq!(2, table_cells(&normal_before).len()); + + let leaders = region_leaders(&frontend, TABLE).await; + assert_eq!(1, leaders.len(), "fixture is required to have one region"); + let (datanode, address) = leaders.values().next().unwrap(); + let region_id = *leaders.keys().next().unwrap(); + let engine = region_server(&cluster, *datanode).mito_engine().unwrap(); + let region = engine.find_region(RegionId::from_u64(region_id)).unwrap(); + let metadata = region.metadata(); + let field_id = |name: &str| { + metadata + .column_metadatas + .iter() + .find(|column| column.column_schema.name == name) + .unwrap() + .column_id + }; + let left_id = field_id("left_value"); + let right_id = field_id("right_value"); + let host_id = field_id("host"); + let projection = ["right_value", "left_value"] + .iter() + .map(|name| { + metadata + .column_metadatas + .iter() + .position(|column| column.column_schema.name == *name) + .unwrap() + }) + .collect::>(); + let snapshot = region.find_committed_sequence(); + + let ctx = query_ctx(); + ctx.set_snapshot(region_id, snapshot); + let base = plan_sql(&frontend, &format!("SELECT * FROM {TABLE}"), &ctx).await; + // Take only the provider source from the ordinary query plan; build a new root scan with + // the intended static predicate rather than submitting its SQL projection/filter parents. + let source = table_source(&base).expect("ordinary plan must contain its table source"); + let filter = col("predicate_value").gt(lit(9_007_199_254_740_992_i64)); + let plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(TABLE), + source.clone(), + Some(projection.clone()), + vec![filter], + ) + .unwrap() + .build() + .unwrap(); + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.as_ref().clone(), + metric_name: TABLE.to_string(), + logical_tags: vec![RawSeriesTag { + column_id: host_id, + name: "host".into(), + }], + // Deliberately swapped field order; the predicate column is not projected. + field_ids: vec![right_id, left_id], + }; + let baseline = rpc_requests(&cluster, *datanode); + let client = Client::with_query_and_control_managers( + ChannelManager::new(), + ChannelManager::new(), + [address.as_str()], + ); + let requester = RegionRequester::new(client, false, false); + let raw_request = LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }; + let raw = requester + .handle_raw_series_query(raw_request, binding.clone()) + .await + .unwrap(); + assert_eq!(baseline + 1, rpc_requests(&cluster, *datanode)); + assert_eq!( + vec!["right_value", "left_value"], + raw.schema() + .fields + .iter() + .map(|f| f.name.as_ref()) + .collect::>() + ); + match raw.label_source() { + RawLabelSource::PrimaryKey { + metric_name, + physical_metadata, + logical_tags, + } => { + assert_eq!(TABLE, metric_name.as_ref()); + assert_eq!(metadata.region_id, physical_metadata.region_id); + assert_eq!(metadata.primary_key, physical_metadata.primary_key); + assert_eq!(1, logical_tags.len()); + assert_eq!(host_id, logical_tags[0].column_id); + assert_eq!("host", logical_tags[0].name.as_ref()); + } + RawLabelSource::Explicit => panic!("expected key-backed source"), + } + assert_eq!(SeriesOrdering::KeyThenTime, 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"]); + let chunks = raw.try_collect::>().await.unwrap(); + assert!(!chunks.is_empty()); + let mut timestamps = Vec::new(); + for chunk in &chunks { + assert!(chunk.metric.is_none()); + assert_eq!( + expected_key, + chunk.primary_key.as_slice(), + "every chunk must retain the complete encoded primary key" + ); + timestamps.extend_from_slice(chunk.time.as_buffer()); + assert_eq!(2, chunk.fields.len()); + assert_eq!(chunk.time.len(), chunk.fields.get(0).unwrap().len()); + assert_eq!(chunk.time.len(), chunk.fields.get(1).unwrap().len()); + for index in 0..chunk.time.len() { + let right = chunk.fields.get(0).unwrap().sample(index); + let left = chunk.fields.get(1).unwrap().sample(index); + match chunk.time.timestamp(index).unwrap() { + 2000 => { + assert!( + matches!(right, SampleRef::Float(value) if value == 0.0 && value.is_sign_negative()) + ); + assert!(matches!(left, SampleRef::Missing)); + } + 3000 => { + assert!(matches!(right, SampleRef::Float(13.0))); + assert!(matches!(left, SampleRef::Float(3.75))); + } + timestamp => panic!("unexpected returned timestamp {timestamp}"), + } + } + } + assert_eq!(vec![2000, 3000], timestamps); + assert!( + chunks + .iter() + .take(chunks.len() - 1) + .all(|chunk| !chunk.is_last) + ); + assert!(chunks.last().unwrap().is_last); + let normal_after_raw = query_pretty(&frontend, &frontend_sql, query_ctx()).await; + assert_eq!(normal_before, normal_after_raw); + + execute_sql( + &frontend, + &format!("INSERT INTO {TABLE} VALUES ('alpha', 4.75, 14.0, 9007199254740995, 4000)"), + ) + .await; + // Re-run the identical plan against the OLD snapshot after the write. + let old_baseline = rpc_requests(&cluster, *datanode); + let old_again = requester + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + binding.clone(), + ) + .await + .unwrap(); + let old_again_chunks = old_again.try_collect::>().await.unwrap(); + assert_eq!(old_baseline + 1, rpc_requests(&cluster, *datanode)); + let old_again_times = old_again_chunks + .iter() + .flat_map(|chunk| chunk.time.as_buffer().iter().copied()) + .collect::>(); + assert_eq!(vec![2000, 3000], old_again_times); + + let mut wrong_binding = binding.clone(); + wrong_binding.field_ids.swap(0, 1); + let wrong_order = requester + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + wrong_binding, + ) + .await; + let wrong_order_error = expect_raw_unsupported(wrong_order).await; + assert!( + wrong_order_error.contains("unsupported native raw-series plan"), + "expected unsupported native raw-series plan error, got: {wrong_order_error}" + ); + assert_eq!(old_baseline + 2, rpc_requests(&cluster, *datanode)); + + let parent_filter = LogicalPlanBuilder::from(plan.clone()) + .filter(col("right_value").gt(lit(0.0_f64))) + .unwrap() + .build() + .unwrap(); + let unsupported = requester + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: parent_filter, + }, + binding.clone(), + ) + .await; + let unsupported_error = expect_raw_unsupported(unsupported).await; + assert!( + unsupported_error.contains("unsupported native raw-series plan"), + "expected unsupported native raw-series plan error, got: {unsupported_error}" + ); + assert_eq!(old_baseline + 3, rpc_requests(&cluster, *datanode)); + + let fresh_ctx = query_ctx(); + fresh_ctx.set_snapshot(region_id, region.find_committed_sequence()); + let fresh_baseline = rpc_requests(&cluster, *datanode); + let fresh = requester + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(region_request_header(&fresh_ctx)), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + binding.clone(), + ) + .await + .unwrap(); + let fresh_chunks = fresh.try_collect::>().await.unwrap(); + let fresh_times = fresh_chunks + .iter() + .flat_map(|chunk| chunk.time.as_buffer().iter().copied()) + .collect::>(); + assert_eq!(fresh_baseline + 1, rpc_requests(&cluster, *datanode)); + assert_eq!(vec![2000, 3000, 4000], fresh_times); + + // A raw marker must not contaminate an ordinary request using the same requester and context. + let ordinary_baseline = rpc_requests(&cluster, *datanode); + // The scan's pushed-down predicate is inexact for ordinary execution, so keep an explicit + // residual Filter above an unfiltered full-schema scan before projecting the output fields. + let ordinary_plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(TABLE), + source.clone(), + None, + vec![], + ) + .unwrap() + .filter(col("predicate_value").gt(lit(9_007_199_254_740_992_i64))) + .unwrap() + .project(vec![col("right_value"), col("left_value")]) + .unwrap() + .build() + .unwrap(); + let ordinary_stream = Datanode::handle_query( + &requester, + LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: ordinary_plan, + }, + ) + .await + .unwrap(); + let ordinary_batches = RecordBatches::try_collect(ordinary_stream).await.unwrap(); + assert_eq!(ordinary_baseline + 1, rpc_requests(&cluster, *datanode)); + let mut ordinary_rows = Vec::new(); + for batch in ordinary_batches.iter() { + let batch = batch.df_record_batch(); + assert_eq!( + vec!["right_value", "left_value"], + batch + .schema_ref() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>() + ); + let right = batch + .column(0) + .as_any() + .downcast_ref::() + .expect("right_value column"); + let left = batch + .column(1) + .as_any() + .downcast_ref::() + .expect("left_value column"); + for index in 0..batch.num_rows() { + ordinary_rows.push((right.value(index), left.is_null(index), left.value(index))); + } + } + assert_eq!(2, ordinary_rows.len()); + assert!(ordinary_rows[0].0.is_sign_negative() && ordinary_rows[0].0 == 0.0); + assert!(ordinary_rows[0].1); + assert_eq!(13.0, ordinary_rows[1].0); + assert!(!ordinary_rows[1].1); + assert_eq!(3.75, ordinary_rows[1].2); + + let ordinary_after = query_pretty(&frontend, &frontend_sql, query_ctx()).await; + let ordinary_rows = table_cells(&ordinary_after); + assert_eq!(3, ordinary_rows.len()); + assert!( + ordinary_rows.contains(&vec![ + "1970-01-01T00:00:04".to_string(), + "4.75".to_string(), + "14.0".to_string(), + ]), + "unexpected fresh ordinary result:\n{ordinary_after}" + ); + + assert_raw_entrypoint_wrapper_contract( + &cluster, *datanode, region_id, TABLE, &ctx, &plan, binding, + ) + .await; +} + +async fn assert_raw_entrypoint_wrapper_contract( + cluster: &GreptimeDbCluster, + datanode_id: u64, + region_id: u64, + table: &str, + query_ctx: &QueryContextRef, + plan: &LogicalPlan, + binding: RawSeriesRequest, +) { + 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; + use datafusion::logical_expr::TableSource; + use datafusion::physical_plan::ExecutionPlan; + use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; + use datafusion::physical_plan::coop::CooperativeExec; + use datafusion::physical_plan::execution_plan::SchedulingType; + use datafusion_expr::{col, lit}; + use datatypes::series::SeriesOrdering; + use query::dummy_catalog::DummyTableProviderFactory; + use query::options::QueryOptions; + use query::physical_wrapper::{PhysicalPlanWrapper, PhysicalPlanWrapperRef}; + use query::query_engine::QueryEngineFactory; + use std::any::Any; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Mutex, Weak}; + use table::table::scan::SeriesScanExec; + + struct TestWrapper { + identity: bool, + calls: Arc, + prepared_ordering: Arc>>, + prepared_plan: Arc>>>, + } + + impl PhysicalPlanWrapper for TestWrapper { + fn wrap( + &self, + origin: Arc, + _ctx: QueryContextRef, + ) -> Arc { + self.calls.fetch_add(1, Ordering::SeqCst); + if let Some(root) = (origin.as_ref() as &dyn Any).downcast_ref::() + && let Some(child) = + (root.input().as_ref() as &dyn Any).downcast_ref::() + { + *self.prepared_ordering.lock().unwrap() = Some(child.raw_series_ordering()); + *self.prepared_plan.lock().unwrap() = Some(Arc::downgrade(&origin)); + } + if self.identity { + origin + } else { + Arc::new(CoalescePartitionsExec::new(origin)) + } + } + } + + let region_id = RegionId::from_u64(region_id); + let region_server = region_server(cluster, datanode_id); + let region_engine = region_server + .find_engine(region_id) + .unwrap() + .expect("table region engine should be registered"); + let provider = DummyTableProviderFactory + .create_table_provider(region_id, region_engine, Some(query_ctx.clone())) + .await + .unwrap(); + let provider_source: Arc = + Arc::new(DefaultTableSource::new(Arc::new(provider))); + let LogicalPlan::TableScan(scan) = plan else { + panic!("fixture plan must be a root table scan"); + }; + let scan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(table), + provider_source.clone(), + scan.projection.clone(), + scan.filters.clone(), + ) + .unwrap() + .build() + .unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let prepared_ordering = Arc::new(Mutex::new(None)); + let prepared_plan = Arc::new(Mutex::new(None)); + let plugins_for = |identity| { + let plugins = Plugins::new(); + plugins.insert(Arc::new(TestWrapper { + identity, + calls: calls.clone(), + prepared_ordering: prepared_ordering.clone(), + prepared_plan: prepared_plan.clone(), + }) as PhysicalPlanWrapperRef); + plugins + }; + let make_engine = |identity| { + QueryEngineFactory::new_with_plugins( + catalog::memory::new_memory_catalog_manager().unwrap(), + None, + None, + None, + None, + None, + false, + plugins_for(identity), + QueryOptions::default(), + ) + .query_engine() + }; + + let identity_engine = make_engine(true); + assert_eq!( + Some(SeriesOrdering::KeyThenTime), + identity_engine + .prepare_raw_series(scan.clone(), query_ctx.clone(), binding.clone()) + .await + .unwrap() + ); + assert_eq!(1, calls.load(Ordering::SeqCst)); + assert_eq!( + Some(SeriesOrdering::KeyThenTime), + *prepared_ordering.lock().unwrap() + ); + assert!( + prepared_plan + .lock() + .unwrap() + .as_ref() + .unwrap() + .upgrade() + .is_none(), + "preparation should release its physical plan" + ); + let mut mismatched_binding = binding.clone(); + mismatched_binding.physical_metadata.schema_version += 1; + let binding_error = identity_engine + .prepare_raw_series(scan.clone(), query_ctx.clone(), mismatched_binding) + .await + .unwrap_err(); + assert!( + binding_error + .to_string() + .contains("Raw-series metadata mismatch") + ); + calls.store(0, Ordering::SeqCst); + *prepared_ordering.lock().unwrap() = None; + *prepared_plan.lock().unwrap() = None; + let identity_output = identity_engine + .execute_raw_series(scan.clone(), query_ctx.clone(), binding.clone()) + .await + .unwrap(); + assert_eq!(1, calls.load(Ordering::SeqCst)); + let identity_plan = identity_output + .meta + .plan + .as_ref() + .expect("raw-series output should retain its physical plan"); + let native_root_schema = identity_plan.schema(); + { + let root = (identity_plan.as_ref() as &dyn Any) + .downcast_ref::() + .expect("native raw-series root should be CooperativeExec"); + let child = (root.input().as_ref() as &dyn Any) + .downcast_ref::() + .expect("native CooperativeExec input should be SeriesScanExec"); + assert!( + child.children().is_empty(), + "SeriesScanExec should be a leaf" + ); + let schema = child.schema(); + assert_eq!(schema.as_ref(), identity_plan.schema().as_ref()); + assert_eq!( + schema.as_ref(), + root.properties().equivalence_properties().schema().as_ref() + ); + } + assert_eq!( + 1, + identity_plan + .properties() + .output_partitioning() + .partition_count() + ); + assert_eq!( + SchedulingType::Cooperative, + identity_plan.properties().scheduling_type + ); + let OutputData::Stream(identity_stream) = identity_output.data else { + panic!("native raw-series entrypoint should return a stream"); + }; + let native_batches = RecordBatches::try_collect(identity_stream).await.unwrap(); + assert!(native_batches.iter().next().is_some()); + 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!( + SeriesOrdering::KeyThenTime, + raw_series_frame_ordering(native_schema).unwrap() + ); + assert_eq!( + vec!["read_key", "is_last", "time", "fields"], + native_schema + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>() + ); + let DataType::Struct(fields) = native_schema.field_with_name("fields").unwrap().data_type() + else { + panic!("native raw-series fields column must be a struct"); + }; + assert_eq!( + vec!["right_value", "left_value"], + fields + .iter() + .map(|field| field.name().as_str()) + .collect::>() + ); + + calls.store(0, Ordering::SeqCst); + *prepared_ordering.lock().unwrap() = None; + *prepared_plan.lock().unwrap() = None; + let wrapped_engine = make_engine(false); + assert_eq!( + None, + wrapped_engine + .prepare_raw_series(scan.clone(), query_ctx.clone(), binding.clone()) + .await + .unwrap() + ); + assert_eq!(1, calls.load(Ordering::SeqCst)); + calls.store(0, Ordering::SeqCst); + let raw_error = match wrapped_engine + .execute_raw_series(scan.clone(), query_ctx.clone(), binding.clone()) + .await + { + Err(error) => error, + Ok(_) => panic!("same-schema one-partition nonidentity wrapper must be rejected"), + }; + assert_eq!(1, calls.load(Ordering::SeqCst)); + assert!( + raw_error + .to_string() + .contains("unsupported native raw-series plan") + ); + + let ordinary_plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(table), + provider_source, + None, + vec![], + ) + .unwrap() + .filter(col("predicate_value").gt(lit(9_007_199_254_740_992_i64))) + .unwrap() + .project(vec![col("right_value"), col("left_value")]) + .unwrap() + .build() + .unwrap(); + let ordinary = wrapped_engine + .execute(ordinary_plan, query_ctx.clone()) + .await + .unwrap(); + let OutputData::Stream(ordinary_stream) = ordinary.data else { + panic!("ordinary scan should return a stream"); + }; + let ordinary_batches = RecordBatches::try_collect(ordinary_stream).await.unwrap(); + assert_eq!( + 2, + table_cells(&ordinary_batches.pretty_print().unwrap()).len() + ); + assert_eq!(2, calls.load(Ordering::SeqCst)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_histogram_raw_flight_preserves_payload_across_flush() { + use api::greptime_proto::io::prometheus::write::v2::histogram::{Count, ZeroCount}; + use api::greptime_proto::io::prometheus::write::v2::{BucketSpan, Histogram}; + use api::v1::helper::{field_column_schema, tag_column_schema, time_index_column_schema}; + use api::v1::value::ValueData; + use api::v1::{ColumnDataType, Row, RowInsertRequest, RowInsertRequests, Rows, SemanticType}; + use common_query::OutputData; + use common_query::native_histogram::{ + CounterResetHint, encode_native_histogram, native_histogram_column_schema, + native_histogram_value_type, + }; + use common_query::request::{QueryRequest as LogicalQueryRequest, RawSeriesTag}; + use datafusion::common::TableReference; + use datatypes::prelude::ConcreteDataType; + use datatypes::series::SeriesOrdering; + use datatypes::series::histogram::{BucketSideView, HistogramView}; + use datatypes::series::samples::SampleRef; + use futures_util::TryStreamExt; + use mito2::test_util::sst_util::new_primary_key; + use store_api::codec::PrimaryKeyEncoding; + use store_api::region_engine::RawLabelSource; + + const TABLE: &str = "native_histogram_raw_flight_flush"; + common_telemetry::init_default_ut_logging(); + let cluster = + build_cluster("test_native_histogram_raw_flight_preserves_payload_across_flush").await; + let frontend = cluster.fe_instance().clone(); + execute_sql( + &frontend, + &format!( + "CREATE TABLE {TABLE} (host STRING, ts TIMESTAMP TIME INDEX, float_value DOUBLE, PRIMARY KEY(host)) ENGINE=mito" + ), + ) + .await; + + let histogram_column = native_histogram_column_schema().unwrap(); + let histograms = [ + Histogram { + count: Some(Count::CountInt(8)), + sum: 10.0, + schema: 1, + zero_threshold: 0.001, + zero_count: Some(ZeroCount::ZeroCountInt(1)), + negative_spans: vec![BucketSpan { + offset: -2, + length: 1, + }], + negative_deltas: vec![1], + positive_spans: vec![BucketSpan { + offset: 0, + length: 3, + }], + positive_deltas: vec![1, 2, -1], + reset_hint: 2, + timestamp: 1_000, + start_timestamp: 500, + ..Default::default() + }, + Histogram { + count: Some(Count::CountFloat(6.5)), + sum: 20.0, + schema: 2, + zero_threshold: 0.002, + zero_count: Some(ZeroCount::ZeroCountFloat(0.5)), + positive_spans: vec![BucketSpan { + offset: 3, + length: 2, + }], + positive_counts: vec![2.0, 3.5], + negative_spans: vec![BucketSpan { + offset: -1, + length: 1, + }], + negative_counts: vec![0.5], + reset_hint: 3, + timestamp: 2_000, + start_timestamp: 750, + ..Default::default() + }, + Histogram { + count: Some(Count::CountFloat(3.5)), + sum: -0.0, + schema: -53, + zero_count: Some(ZeroCount::ZeroCountFloat(0.0)), + custom_values: vec![1.5, 2.5], + positive_spans: vec![BucketSpan { + offset: 0, + length: 3, + }], + positive_counts: vec![0.5, 1.25, 1.75], + reset_hint: 77, + timestamp: 3_000, + ..Default::default() + }, + ]; + let histograms = histograms + .iter() + .map(|histogram| encode_native_histogram(histogram).unwrap().into()) + .collect::>(); + let mut schema = vec![ + tag_column_schema("host", ColumnDataType::String), + time_index_column_schema("ts", ColumnDataType::TimestampMillisecond), + field_column_schema("float_value", ColumnDataType::Float64), + ]; + schema.push(histogram_column); + let rows = [1_000, 2_000, 3_000, 4_000] + .into_iter() + .zip(histograms.into_iter().map(Some).chain([None])) + .zip([None, Some(-0.0), Some(4.75), Some(7.25)]) + .map(|((timestamp, histogram), value)| Row { + values: vec![ + ValueData::StringValue("alpha".to_string()).into(), + ValueData::TimestampMillisecondValue(timestamp).into(), + value + .map(ValueData::F64Value) + .map(Into::into) + .unwrap_or_default(), + histogram.unwrap_or_default(), + ], + }) + .collect(); + let output = frontend + .handle_row_inserts( + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: TABLE.to_string(), + rows: Some(Rows { schema, rows }), + }], + }, + QueryContext::arc(), + false, + false, + ) + .await + .unwrap(); + assert!(matches!(output.data, OutputData::AffectedRows(4))); + + let leaders = region_leaders(&frontend, TABLE).await; + assert_eq!(1, leaders.len(), "fixture is required to have one region"); + let (datanode, address) = leaders.values().next().unwrap(); + let region_id = *leaders.keys().next().unwrap(); + let region = region_server(&cluster, *datanode) + .mito_engine() + .unwrap() + .find_region(RegionId::from_u64(region_id)) + .unwrap(); + let metadata = region.metadata(); + let histogram_column = metadata + .column_by_name("greptime_native_histogram") + .unwrap(); + let float_column = metadata.column_by_name("float_value").unwrap(); + let host_column = metadata.column_by_name("host").unwrap(); + assert_eq!(SemanticType::Field, histogram_column.semantic_type); + assert_eq!( + native_histogram_value_type(), + &histogram_column.column_schema.data_type + ); + assert_eq!(PrimaryKeyEncoding::Dense, metadata.primary_key_encoding); + assert_eq!( + vec!["host"], + metadata + .primary_key_columns() + .map(|column| column.column_schema.name.as_str()) + .collect::>() + ); + assert_eq!( + &ConcreteDataType::float64_datatype(), + &float_column.column_schema.data_type + ); + let histogram_index = metadata + .column_index_by_name("greptime_native_histogram") + .unwrap(); + let float_index = metadata.column_index_by_name("float_value").unwrap(); + let projection = vec![histogram_index, float_index]; + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.as_ref().clone(), + metric_name: TABLE.to_string(), + logical_tags: vec![RawSeriesTag { + column_id: host_column.column_id, + name: "host".to_string(), + }], + field_ids: vec![histogram_column.column_id, float_column.column_id], + }; + let committed = region.find_committed_sequence(); + assert!(committed > 0); + assert!(region.manifest_sst_entries().await.is_empty()); + + let ctx = query_ctx(); + ctx.set_snapshot(region_id, committed); + let base = plan_sql(&frontend, &format!("SELECT * FROM {TABLE}"), &ctx).await; + let source = table_source(&base).expect("ordinary plan must contain its table source"); + let plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(TABLE), + source, + Some(projection), + vec![], + ) + .unwrap() + .build() + .unwrap(); + let expected = [ + HistogramView { + schema: 1, + zero_threshold: 0.001, + sum: 10.0, + count: 8.0, + zero_count: 1.0, + reset_hint: CounterResetHint::NotCounterReset, + start_timestamp: Some(500), + custom_values: &[], + positive: BucketSideView { + span_offsets: &[0], + span_lengths: &[3], + buckets: &[1.0, 3.0, 2.0], + }, + negative: BucketSideView { + span_offsets: &[-2], + span_lengths: &[1], + buckets: &[1.0], + }, + }, + HistogramView { + schema: 2, + zero_threshold: 0.002, + sum: 20.0, + count: 6.5, + zero_count: 0.5, + reset_hint: CounterResetHint::Gauge, + start_timestamp: Some(750), + custom_values: &[], + positive: BucketSideView { + span_offsets: &[3], + span_lengths: &[2], + buckets: &[2.0, 3.5], + }, + negative: BucketSideView { + span_offsets: &[-1], + span_lengths: &[1], + buckets: &[0.5], + }, + }, + HistogramView { + schema: -53, + zero_threshold: 0.0, + sum: -0.0, + count: 3.5, + zero_count: 0.0, + reset_hint: CounterResetHint::Unrecognized(77), + start_timestamp: None, + custom_values: &[1.5, 2.5], + positive: BucketSideView { + span_offsets: &[0], + span_lengths: &[3], + buckets: &[0.5, 1.25, 1.75], + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }, + ]; + let expected_key = new_primary_key(&["alpha"]); + let client = Client::with_query_and_control_managers( + ChannelManager::new(), + ChannelManager::new(), + [address.as_str()], + ); + let requester = RegionRequester::new(client, false, false); + for after_flush in [false, true] { + if after_flush { + execute_sql(&frontend, &format!("ADMIN FLUSH_TABLE('{TABLE}')")).await; + assert!(!region.manifest_sst_entries().await.is_empty()); + assert!(region.flushed_sequence() >= committed); + } + let baseline = rpc_requests(&cluster, *datanode); + let stream = requester + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(region_request_header(&ctx)), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + binding.clone(), + ) + .await + .unwrap(); + assert_eq!( + vec!["greptime_native_histogram", "float_value"], + stream + .schema() + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>() + ); + assert!(stream.schema().eval_grid.is_none()); + match stream.label_source() { + RawLabelSource::PrimaryKey { + metric_name, + physical_metadata, + logical_tags, + } => { + assert_eq!(TABLE, metric_name.as_ref()); + assert_eq!(metadata.as_ref(), physical_metadata.as_ref()); + assert_eq!(1, logical_tags.len()); + assert_eq!(host_column.column_id, logical_tags[0].column_id); + assert_eq!("host", logical_tags[0].name.as_ref()); + } + RawLabelSource::Explicit => panic!("expected key-backed source"), + } + assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering()); + let chunks = stream.try_collect::>().await.unwrap(); + let mut timestamps = Vec::new(); + for (chunk_index, chunk) in chunks.iter().enumerate() { + assert!(chunk.metric.is_none()); + assert_eq!(expected_key, chunk.primary_key.as_slice()); + assert_eq!(2, chunk.fields.len()); + assert!(!chunk.time.is_empty()); + assert_eq!(chunk.time.len(), chunk.fields.get(0).unwrap().len()); + assert_eq!(chunk.time.len(), chunk.fields.get(1).unwrap().len()); + assert_eq!(chunk_index + 1 == chunks.len(), chunk.is_last); + for index in 0..chunk.time.len() { + let timestamp = chunk.time.timestamp(index).unwrap(); + timestamps.push(timestamp); + let histogram = chunk.fields.get(0).unwrap().sample(index); + let float_value = chunk.fields.get(1).unwrap().sample(index); + match timestamp { + 1_000 => { + let SampleRef::Histogram(actual) = histogram else { + panic!("expected histogram at {timestamp}") + }; + assert_histogram_view(actual, expected[0]); + assert!(matches!(float_value, SampleRef::Missing)); + } + 2_000 => { + let SampleRef::Histogram(actual) = histogram else { + panic!("expected histogram at {timestamp}") + }; + assert_histogram_view(actual, expected[1]); + assert!( + matches!(float_value, SampleRef::Float(value) if value.to_bits() == (-0.0_f64).to_bits()) + ); + } + 3_000 => { + let SampleRef::Histogram(actual) = histogram else { + panic!("expected histogram at {timestamp}") + }; + assert_histogram_view(actual, expected[2]); + assert!( + matches!(float_value, SampleRef::Float(value) if value.to_bits() == 4.75_f64.to_bits()) + ); + } + 4_000 => { + assert!(matches!(histogram, SampleRef::Missing)); + assert!( + matches!(float_value, SampleRef::Float(value) if value.to_bits() == 7.25_f64.to_bits()) + ); + } + timestamp => panic!("unexpected returned timestamp {timestamp}"), + } + } + } + assert_eq!(vec![1_000, 2_000, 3_000, 4_000], timestamps); + assert_eq!(baseline + 1, rpc_requests(&cluster, *datanode)); + } + + fn assert_histogram_view(actual: HistogramView<'_>, expected: HistogramView<'_>) { + assert_eq!(expected.schema, actual.schema); + assert_eq!(expected.reset_hint, actual.reset_hint); + assert_eq!(expected.start_timestamp, actual.start_timestamp); + assert_eq!( + expected.zero_threshold.to_bits(), + actual.zero_threshold.to_bits() + ); + assert_eq!(expected.sum.to_bits(), actual.sum.to_bits()); + assert_eq!(expected.count.to_bits(), actual.count.to_bits()); + assert_eq!(expected.zero_count.to_bits(), actual.zero_count.to_bits()); + let bits = |values: &[f64]| { + values + .iter() + .map(|value| value.to_bits()) + .collect::>() + }; + assert_eq!(bits(expected.custom_values), bits(actual.custom_values)); + for (expected, actual) in [ + (expected.positive, actual.positive), + (expected.negative, actual.negative), + ] { + assert_eq!(expected.span_offsets, actual.span_offsets); + assert_eq!(expected.span_lengths, actual.span_lengths); + assert_eq!(bits(expected.buckets), bits(actual.buckets)); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_native_raw_series_through_production_datanode_trait() { + use api::v1::region::{ListMetadataRequest, RegionRequest, region_request}; + use client::client_manager::NodeClients; + use common_meta::node_manager::DatanodeManager; + use common_meta::peer::Peer; + use common_query::request::RAW_SERIES_REQUEST_EXTENSION_KEY; + use common_query::request::{QueryRequest as LogicalQueryRequest, RawSeriesTag}; + use datafusion::common::TableReference; + use datafusion_expr::{col, lit}; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::SampleRef; + use futures_util::TryStreamExt; + use mito2::test_util::sst_util::new_primary_key; + use store_api::metadata::RegionMetadata; + use store_api::region_engine::RawLabelSource; + + const TABLE: &str = "native_trait_raw_series_tcp"; + common_telemetry::init_default_ut_logging(); + let cluster = build_cluster("test_native_raw_series_through_production_datanode_trait").await; + let frontend = cluster.fe_instance().clone(); + execute_sql(&frontend, &format!( + "CREATE TABLE {TABLE} (host STRING, left_value DOUBLE, right_value DOUBLE, predicate_value BIGINT, ts TIMESTAMP, TIME INDEX (ts), PRIMARY KEY(host)) ENGINE=mito" + )).await; + execute_sql(&frontend, &format!( + "INSERT INTO {TABLE} VALUES ('alpha', 1.25, 11.0, 9007199254740992, 1000), ('alpha', NULL, -0.0, 9007199254740993, 2000)" + )).await; + + let leaders = region_leaders(&frontend, TABLE).await; + assert_eq!(1, leaders.len()); + let (®ion_id, &(node_id, ref address)) = leaders.iter().next().unwrap(); + // The fixture frontend uses duplex clients; this fresh production client uses counted TCP. + let datanode = NodeClients::default() + .datanode(&Peer { + id: node_id, + addr: address.clone(), + }) + .await; + let list_response = datanode + .handle(RegionRequest { + header: Some(RegionRequestHeader::default()), + body: Some(region_request::Body::ListMetadata(ListMetadataRequest { + region_ids: vec![region_id], + })), + }) + .await + .unwrap(); + let metadata_list: Vec> = + serde_json::from_slice(&list_response.metadata).unwrap(); + assert_eq!(1, metadata_list.len(), "ListMetadata response count"); + let metadata = metadata_list + .into_iter() + .next() + .flatten() + .expect("metadata for requested region"); + assert_eq!(region_id, metadata.region_id.as_u64()); + + let ctx = query_ctx(); + let snapshot = region_server(&cluster, node_id) + .mito_engine() + .unwrap() + .find_region(RegionId::from_u64(region_id)) + .unwrap() + .find_committed_sequence(); + ctx.set_snapshot(region_id, snapshot); + execute_sql( + &frontend, + &format!("INSERT INTO {TABLE} VALUES ('alpha', 8.5, 99.0, 9007199254740994, 3000)"), + ) + .await; + + let base = plan_sql(&frontend, &format!("SELECT * FROM {TABLE}"), &ctx).await; + let source = table_source(&base).expect("ordinary plan table source"); + let field_id = |name: &str| metadata.column_by_name(name).unwrap().column_id; + let plan = LogicalPlanBuilder::scan_with_filters( + TableReference::bare(TABLE), + source, + Some(vec![ + metadata + .column_metadatas + .iter() + .position(|c| c.column_schema.name == "right_value") + .unwrap(), + metadata + .column_metadatas + .iter() + .position(|c| c.column_schema.name == "left_value") + .unwrap(), + ]), + vec![col("predicate_value").gt(lit(9_007_199_254_740_992_i64))], + ) + .unwrap() + .build() + .unwrap(); + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.clone(), + metric_name: TABLE.to_string(), + logical_tags: vec![RawSeriesTag { + column_id: field_id("host"), + name: "host".into(), + }], + field_ids: vec![field_id("right_value"), field_id("left_value")], + }; + let header = region_request_header(&ctx); + let baseline = rpc_requests(&cluster, node_id); + let raw = datanode + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(header.clone()), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + binding.clone(), + ) + .await + .unwrap(); + assert_eq!( + baseline + 1, + rpc_requests(&cluster, node_id), + "exactly one TCP Flight DoGet" + ); + assert_eq!( + vec!["right_value", "left_value"], + raw.schema() + .fields + .iter() + .map(|f| f.name.as_ref()) + .collect::>() + ); + assert_eq!(SeriesOrdering::KeyThenTime, raw.ordering()); + assert!(matches!( + raw.label_source(), + RawLabelSource::PrimaryKey { .. } + )); + let chunks = raw.try_collect::>().await.unwrap(); + assert_eq!(1, chunks.len()); + let chunk = &chunks[0]; + assert!(chunk.is_last); + assert!(chunk.metric.is_none()); + assert_eq!(2, chunk.fields.len()); + assert_eq!(chunk.time.len(), chunk.fields.get(0).unwrap().len()); + assert_eq!(chunk.time.len(), chunk.fields.get(1).unwrap().len()); + assert_eq!(new_primary_key(&["alpha"]), chunk.primary_key.as_slice()); + assert_eq!(&[2000], chunk.time.as_buffer().as_ref()); + assert!( + matches!(chunk.fields.get(0).unwrap().sample(0), SampleRef::Float(v) if v.to_bits() == (-0.0_f64).to_bits()) + ); + assert!(matches!( + chunk.fields.get(1).unwrap().sample(0), + SampleRef::Missing + )); + + let stale_baseline = rpc_requests(&cluster, node_id); + let mut stale = binding.clone(); + stale.physical_metadata.schema_version += 1; + let message = expect_raw_unsupported( + datanode + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(header.clone()), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + stale, + ) + .await, + ) + .await; + assert!( + message.contains("Raw-series metadata mismatch"), + "stale metadata rejection was not diagnostic: {message}" + ); + assert_eq!(stale_baseline + 1, rpc_requests(&cluster, node_id)); + + let mut marked_header = header.clone(); + marked_header + .query_context + .as_mut() + .unwrap() + .extensions + .insert( + RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(), + "{}".to_string(), + ); + let marker_baseline = rpc_requests(&cluster, node_id); + let message = expect_raw_unsupported( + datanode + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(marked_header), + region_id: RegionId::from_u64(region_id), + plan: plan.clone(), + }, + binding.clone(), + ) + .await, + ) + .await; + assert!( + message.contains("marker already exists"), + "unexpected marker rejection: {message}" + ); + assert_eq!(marker_baseline, rpc_requests(&cluster, node_id)); + + let mismatch_baseline = rpc_requests(&cluster, node_id); + let message = expect_raw_unsupported( + datanode + .handle_raw_series_query( + LogicalQueryRequest { + header: Some(header), + region_id: RegionId::from_u64(region_id + 1), + plan, + }, + binding, + ) + .await, + ) + .await; + assert!( + message.contains("region does not match binding"), + "unexpected region rejection: {message}" + ); + assert_eq!(mismatch_baseline, rpc_requests(&cluster, node_id)); +}