mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
test(tests-integration): add native PromQL and raw-series integration tests
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -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<Arc<DatanodeFlightHook>>,
|
||||
}
|
||||
|
||||
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<DatanodeFlightHook>) -> Self {
|
||||
self.datanode_flight_hook = Some(hook);
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn build_with(
|
||||
&self,
|
||||
datanode_options: Vec<DatanodeOptions>,
|
||||
@@ -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<NodeClients>,
|
||||
start_frontend_servers: bool,
|
||||
frontend_node_clients: Arc<NodeClients>,
|
||||
) -> 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<DatanodeId, Datanode>,
|
||||
options: &[DatanodeOptions],
|
||||
rpc_stats: &HashMap<DatanodeId, Arc<DatanodeRpcStats>>,
|
||||
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<I, IO>(
|
||||
datanode: &Datanode,
|
||||
incoming: I,
|
||||
rpc_stats: Option<Arc<DatanodeRpcStats>>,
|
||||
flight_craft: Option<FlightCraftRef>,
|
||||
) where
|
||||
I: futures::Stream<Item = Result<IO, std::io::Error>> + Send + 'static,
|
||||
IO: AsyncRead + AsyncWrite + Connected + Unpin + Send + 'static,
|
||||
@@ -742,7 +838,8 @@ fn serve_datanode_region_server<I, IO>(
|
||||
.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<I, IO>(
|
||||
|
||||
/// 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<Arc<DatanodeRpcStats>>,
|
||||
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<S> {
|
||||
inner: S,
|
||||
@@ -842,10 +948,16 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, request: http::Request<ReqBody>) -> 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)
|
||||
|
||||
@@ -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<FlightData>,
|
||||
released: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl Stream for PendingFlightDataStream {
|
||||
type Item = Result<FlightData, Status>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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<Option<oneshot::Sender<()>>>,
|
||||
do_get_count: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
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<Ticket>,
|
||||
) -> std::result::Result<Response<TonicStream<FlightData>>, 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);
|
||||
|
||||
@@ -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<BatcherOptions>,
|
||||
table_batcher: BatcherOptions,
|
||||
mito_config: Option<mito2::config::MitoConfig>,
|
||||
query_options: Option<query::options::QueryOptions>,
|
||||
}
|
||||
|
||||
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<RegionRequest>) -> MetaResult<RegionResponse> {
|
||||
panic!("unexpected handle_request")
|
||||
}
|
||||
|
||||
async fn handle_query(
|
||||
&self,
|
||||
_request: QueryRequest,
|
||||
) -> MetaResult<SendableRecordBatchStream> {
|
||||
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::<Vec<_>>()
|
||||
);
|
||||
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<Arc<dyn TableSource>> {
|
||||
match plan {
|
||||
LogicalPlan::TableScan(scan) => Some(scan.source.clone()),
|
||||
_ => plan.inputs().into_iter().find_map(table_source),
|
||||
}
|
||||
}
|
||||
|
||||
async fn plan_sql(
|
||||
frontend: &Arc<Instance>,
|
||||
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<Option<RegionMetadata>> =
|
||||
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::<Vec<_>>().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::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vec![1000, 2000],
|
||||
old.iter()
|
||||
.flat_map(|chunk| chunk.time.as_buffer().iter().copied())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Instance>, 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<Instance>, 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<String>, Option<f64>)> {
|
||||
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::<TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
let host = batch
|
||||
.column(1)
|
||||
.as_any()
|
||||
.downcast_ref::<StringArray>()
|
||||
.unwrap();
|
||||
let val = batch
|
||||
.column(2)
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.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<_>>(),
|
||||
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)
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user