mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
feat(query): execute bound raw-series reads over Flight
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
+114
-3
@@ -28,21 +28,26 @@ use arc_swap::ArcSwapOption;
|
||||
use arrow_flight::Ticket;
|
||||
use async_stream::stream;
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::ext::{BoxedError, ErrorExt, PlainError};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_grpc::flight::{FlightDecoder, FlightMessage};
|
||||
use common_meta::error::{self as meta_error, Result as MetaResult};
|
||||
use common_meta::node_manager::Datanode;
|
||||
use common_query::request::QueryRequest;
|
||||
use common_query::error::Error as CommonQueryError;
|
||||
use common_query::request::{QueryRequest, RAW_SERIES_REQUEST_EXTENSION_KEY, RawSeriesRequest};
|
||||
use common_query::series_frame::unpack_raw_series;
|
||||
use common_recordbatch::adapter::DfRecordBatchStreamAdapter;
|
||||
use common_recordbatch::error::ExternalSnafu;
|
||||
use common_recordbatch::{RecordBatch, RecordBatchStreamWrapper, SendableRecordBatchStream};
|
||||
use common_telemetry::error;
|
||||
use common_telemetry::tracing::Span;
|
||||
use common_telemetry::tracing_context::TracingContext;
|
||||
use datatypes::series::raw::RawSeriesOrdering;
|
||||
use futures_util::Stream;
|
||||
use prost::Message;
|
||||
use query::query_engine::DefaultSerializer;
|
||||
use snafu::{OptionExt, ResultExt, location};
|
||||
use store_api::region_engine::SendableRawSeriesStream;
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
use tokio_stream::StreamExt;
|
||||
use tonic::codec::CompressionEncoding;
|
||||
@@ -102,6 +107,80 @@ impl RegionRequester {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends an explicit trusted internal raw-series request and decodes its Flight frames.
|
||||
///
|
||||
/// The binding is an expectation supplied by the already-authorized internal planner; it is
|
||||
/// not evidence of provenance or an independent authorization grant.
|
||||
pub async fn handle_raw_series_query(
|
||||
&self,
|
||||
mut request: QueryRequest,
|
||||
binding: RawSeriesRequest,
|
||||
) -> MetaResult<SendableRawSeriesStream> {
|
||||
if request.region_id != binding.physical_metadata.region_id {
|
||||
return Err(BoxedError::new(PlainError::new(
|
||||
"raw-series request region does not match binding".to_string(),
|
||||
StatusCode::InvalidArguments,
|
||||
)))
|
||||
.context(meta_error::ExternalSnafu);
|
||||
}
|
||||
let (expected_schema, label_source) = binding
|
||||
.bind(Arc::new(binding.physical_metadata.clone()))
|
||||
.map_err(|error| {
|
||||
BoxedError::new(CommonQueryError::GeneralDataFusion {
|
||||
error,
|
||||
location: location!(),
|
||||
})
|
||||
})
|
||||
.context(meta_error::ExternalSnafu)?;
|
||||
if request
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|header| header.query_context.as_ref())
|
||||
.is_some_and(|context| {
|
||||
context
|
||||
.extensions
|
||||
.contains_key(RAW_SERIES_REQUEST_EXTENSION_KEY)
|
||||
})
|
||||
{
|
||||
return Err(BoxedError::new(PlainError::new(
|
||||
"raw-series request marker already exists".to_string(),
|
||||
StatusCode::InvalidArguments,
|
||||
)))
|
||||
.context(meta_error::ExternalSnafu);
|
||||
}
|
||||
let extension = binding
|
||||
.to_extension_value()
|
||||
.map_err(|error| {
|
||||
BoxedError::new(CommonQueryError::GeneralDataFusion {
|
||||
error,
|
||||
location: location!(),
|
||||
})
|
||||
})
|
||||
.context(meta_error::ExternalSnafu)?;
|
||||
request
|
||||
.header
|
||||
.get_or_insert_default()
|
||||
.query_context
|
||||
.get_or_insert_default()
|
||||
.extensions
|
||||
.insert(RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(), extension);
|
||||
let stream = Datanode::handle_query(self, request).await?;
|
||||
let stream = Box::pin(DfRecordBatchStreamAdapter::new(stream));
|
||||
unpack_raw_series(
|
||||
stream,
|
||||
expected_schema,
|
||||
label_source,
|
||||
RawSeriesOrdering::Contiguous,
|
||||
)
|
||||
.map_err(|error| {
|
||||
BoxedError::new(CommonQueryError::GeneralDataFusion {
|
||||
error,
|
||||
location: location!(),
|
||||
})
|
||||
})
|
||||
.context(meta_error::ExternalSnafu)
|
||||
}
|
||||
|
||||
pub async fn do_get_inner(&self, ticket: Ticket) -> Result<SendableRecordBatchStream> {
|
||||
let mut flight_client = self
|
||||
.client
|
||||
@@ -422,7 +501,8 @@ mod tests {
|
||||
};
|
||||
use api::v1::value::ValueData;
|
||||
use api::v1::{
|
||||
ColumnDataType, ColumnSchema as PbColumnSchema, Row, Rows, Status as PbStatus, Value,
|
||||
ColumnDataType, ColumnSchema as PbColumnSchema, QueryContext as ApiQueryContext, Row, Rows,
|
||||
Status as PbStatus, Value,
|
||||
};
|
||||
use common_error::ext::RetryHint;
|
||||
use common_grpc::channel_manager::{ChannelConfig, ChannelManager};
|
||||
@@ -441,6 +521,37 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::Error;
|
||||
|
||||
fn raw_series_fixture() -> RawSeriesRequest {
|
||||
RawSeriesRequest::from_extension_value(include_str!(
|
||||
"../../../tests/compatibility/wire/raw_series_request/v1_request.json"
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_query_rejects_existing_marker_before_transport() {
|
||||
let requester = RegionRequester::new(Client::new(), false, false);
|
||||
let mut context = ApiQueryContext::default();
|
||||
context.extensions.insert(
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(),
|
||||
"already-set".to_string(),
|
||||
);
|
||||
let request = QueryRequest {
|
||||
header: Some(RegionRequestHeader {
|
||||
query_context: Some(context),
|
||||
..Default::default()
|
||||
}),
|
||||
region_id: raw_series_fixture().physical_metadata.region_id,
|
||||
plan: Default::default(),
|
||||
};
|
||||
let error = requester
|
||||
.handle_raw_series_query(request, raw_series_fixture())
|
||||
.await
|
||||
.err()
|
||||
.expect("conflicting marker should be rejected before transport");
|
||||
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct RecordingRegionService {
|
||||
requests: Arc<Mutex<Vec<(RegionRequest, bool, bool)>>>,
|
||||
|
||||
@@ -55,6 +55,7 @@ use crate::{
|
||||
};
|
||||
|
||||
const REGION_SCAN_EXEC_NAME: &str = "RegionScanExec";
|
||||
pub const SERIES_SCAN_EXEC_NAME: &str = "SeriesScanExec";
|
||||
|
||||
type FutureStream =
|
||||
Pin<Box<dyn std::future::Future<Output = Result<SendableRecordBatchStream>> + Send>>;
|
||||
@@ -377,12 +378,16 @@ impl RecordBatchStreamAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_region_scan_name(name: &str) -> bool {
|
||||
name == REGION_SCAN_EXEC_NAME || name == SERIES_SCAN_EXEC_NAME
|
||||
}
|
||||
|
||||
/// Extracts total `output_bytes` from region scan plan nodes.
|
||||
pub fn region_scan_output_bytes(metrics: &RecordBatchMetrics) -> usize {
|
||||
metrics
|
||||
.plan_metrics
|
||||
.iter()
|
||||
.filter(|pm| pm.plan_name == REGION_SCAN_EXEC_NAME)
|
||||
.filter(|pm| is_region_scan_name(&pm.plan_name))
|
||||
.flat_map(|pm| &pm.metrics)
|
||||
.filter_map(|(name, value)| (name == "output_bytes").then_some(*value))
|
||||
.sum()
|
||||
@@ -434,7 +439,7 @@ fn collect_lightweight_query_load_metrics_inner(
|
||||
level: usize,
|
||||
record_batch_metrics: &mut RecordBatchMetrics,
|
||||
) {
|
||||
let is_region_scan = df_plan.name() == REGION_SCAN_EXEC_NAME;
|
||||
let is_region_scan = is_region_scan_name(df_plan.name());
|
||||
let mut region_scan_output_bytes = None;
|
||||
|
||||
if let Some(metrics) = df_plan.metrics() {
|
||||
@@ -967,6 +972,7 @@ mod test {
|
||||
properties: Arc<PlanProperties>,
|
||||
metrics: ExecutionPlanMetricsSet,
|
||||
format_plan: bool,
|
||||
plan_name: &'static str,
|
||||
}
|
||||
|
||||
impl TestMetricsExec {
|
||||
@@ -975,17 +981,23 @@ mod test {
|
||||
}
|
||||
|
||||
fn new_without_plan_formatting(schema: DfSchemaRef) -> Self {
|
||||
Self::with_output_bytes_and_formatting(schema, &[24], false)
|
||||
Self::with_output_bytes_and_formatting(schema, &[24], false, REGION_SCAN_EXEC_NAME)
|
||||
}
|
||||
|
||||
fn with_output_bytes(schema: DfSchemaRef, output_bytes_by_partition: &[usize]) -> Self {
|
||||
Self::with_output_bytes_and_formatting(schema, output_bytes_by_partition, true)
|
||||
Self::with_output_bytes_and_formatting(
|
||||
schema,
|
||||
output_bytes_by_partition,
|
||||
true,
|
||||
REGION_SCAN_EXEC_NAME,
|
||||
)
|
||||
}
|
||||
|
||||
fn with_output_bytes_and_formatting(
|
||||
schema: DfSchemaRef,
|
||||
output_bytes_by_partition: &[usize],
|
||||
format_plan: bool,
|
||||
plan_name: &'static str,
|
||||
) -> Self {
|
||||
let metrics = ExecutionPlanMetricsSet::new();
|
||||
let elapsed_compute = MetricBuilder::new(&metrics).elapsed_compute(0);
|
||||
@@ -1004,6 +1016,7 @@ mod test {
|
||||
)),
|
||||
metrics,
|
||||
format_plan,
|
||||
plan_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1014,7 +1027,7 @@ mod test {
|
||||
self.format_plan,
|
||||
"non-verbose lightweight partial metrics must not format the plan"
|
||||
);
|
||||
write!(f, "RegionScanExec")?;
|
||||
write!(f, "{}", self.plan_name)?;
|
||||
if matches!(t, DisplayFormatType::Verbose) {
|
||||
write!(f, ": files=[file-1.parquet]")?;
|
||||
}
|
||||
@@ -1024,7 +1037,7 @@ mod test {
|
||||
|
||||
impl ExecutionPlan for TestMetricsExec {
|
||||
fn name(&self) -> &str {
|
||||
REGION_SCAN_EXEC_NAME
|
||||
self.plan_name
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
@@ -1064,6 +1077,29 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lightweight_query_load_metrics_sums_series_scan_output_bytes() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"a",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let plan = TestMetricsExec::with_output_bytes_and_formatting(
|
||||
schema.arrow_schema().clone(),
|
||||
&[24, 18],
|
||||
true,
|
||||
SERIES_SCAN_EXEC_NAME,
|
||||
);
|
||||
|
||||
let metrics = collect_lightweight_query_load_metrics(&plan, Some(42));
|
||||
|
||||
assert_eq!(region_scan_output_bytes(&metrics), 42);
|
||||
assert_eq!(metrics.plan_metrics[0].plan_name, SERIES_SCAN_EXEC_NAME);
|
||||
|
||||
let full_metrics = collect_full_metrics(&plan, false, Some(42));
|
||||
assert_eq!(region_scan_output_bytes(&full_metrics), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lightweight_query_load_metrics_sums_region_scan_output_bytes() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
|
||||
@@ -29,7 +29,8 @@ use api::region::RegionResponse;
|
||||
use api::v1::meta::TopicStat;
|
||||
use api::v1::region::sync_request::ManifestInfo;
|
||||
use api::v1::region::{
|
||||
ListMetadataRequest, RegionResponse as RegionResponseV1, SyncRequest, region_request,
|
||||
ListMetadataRequest, RegionRequestHeader, RegionResponse as RegionResponseV1, SyncRequest,
|
||||
region_request,
|
||||
};
|
||||
use api::v1::{ResponseHeader, Status};
|
||||
use arrow_flight::{FlightData, Ticket};
|
||||
@@ -39,7 +40,10 @@ use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_meta::datanode::TopicStatsReporter;
|
||||
use common_query::OutputData;
|
||||
use common_query::request::QueryRequest;
|
||||
use common_query::request::{
|
||||
INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, QueryRequest,
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY, RawSeriesRequest, take_raw_series_request,
|
||||
};
|
||||
use common_recordbatch::adapter::RecordBatchMetrics;
|
||||
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream};
|
||||
use common_runtime::Runtime;
|
||||
@@ -98,9 +102,9 @@ use crate::error::{
|
||||
ConcurrentQueryLimiterTimeoutSnafu, DataFusionSnafu, DecodeLogicalPlanSnafu,
|
||||
ExecuteLogicalPlanSnafu, FindLogicalRegionsSnafu, GetRegionMetadataSnafu,
|
||||
HandleBatchDdlRequestSnafu, HandleBatchOpenRequestSnafu, HandleRegionRequestSnafu,
|
||||
NewPlanDecoderSnafu, RegionEngineNotFoundSnafu, RegionNotFoundSnafu, RegionNotReadySnafu,
|
||||
Result, RuntimeJoinSnafu, SerializeJsonSnafu, StopRegionEngineSnafu, UnexpectedSnafu,
|
||||
UnsupportedOutputSnafu,
|
||||
InvalidQueryContextSnafu, NewPlanDecoderSnafu, RegionEngineNotFoundSnafu, RegionNotFoundSnafu,
|
||||
RegionNotReadySnafu, Result, RuntimeJoinSnafu, SerializeJsonSnafu, StopRegionEngineSnafu,
|
||||
UnexpectedSnafu, UnsupportedOutputSnafu,
|
||||
};
|
||||
use crate::event_listener::RegionServerEventListenerRef;
|
||||
use crate::query_stream::QueryRuntimeStream;
|
||||
@@ -110,6 +114,21 @@ use crate::region_server::remote_dyn_filter::wrap_remote_dyn_filter_guarded_stre
|
||||
|
||||
const QUERY_RUNTIME_STREAM_BUFFER_SIZE: usize = 8;
|
||||
|
||||
fn has_initial_remote_dyn_filter(
|
||||
header: &Option<RegionRequestHeader>,
|
||||
query_ctx: &QueryContextRef,
|
||||
) -> bool {
|
||||
header.as_ref().is_some_and(|header| {
|
||||
header.query_context.as_ref().is_some_and(|context| {
|
||||
context
|
||||
.extensions
|
||||
.contains_key(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
|
||||
})
|
||||
}) || query_ctx
|
||||
.extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegionServer {
|
||||
inner: Arc<RegionServerInner>,
|
||||
@@ -279,17 +298,49 @@ impl RegionServer {
|
||||
/// Handle reads from remote. They're often query requests received by our Arrow Flight service.
|
||||
pub async fn handle_remote_read(
|
||||
&self,
|
||||
request: api::v1::region::QueryRequest,
|
||||
mut request: api::v1::region::QueryRequest,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
self.handle_remote_read_inner(request, query_ctx).await
|
||||
let raw_series = take_raw_series_request(&mut request.header).map_err(|err| {
|
||||
crate::error::InvalidQueryContextSnafu {
|
||||
reason: err.to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
self.handle_remote_read_inner(request, query_ctx, raw_series)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle_remote_read_inner(
|
||||
&self,
|
||||
request: api::v1::region::QueryRequest,
|
||||
query_ctx: QueryContextRef,
|
||||
raw_series: Option<RawSeriesRequest>,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
ensure!(
|
||||
query_ctx
|
||||
.extension(RAW_SERIES_REQUEST_EXTENSION_KEY)
|
||||
.is_none(),
|
||||
InvalidQueryContextSnafu {
|
||||
reason: "reserved raw-series extension already exists in supplied query context"
|
||||
.to_string()
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
raw_series.as_ref().is_none_or(
|
||||
|raw| raw.physical_metadata.region_id == RegionId::from_u64(request.region_id)
|
||||
),
|
||||
InvalidQueryContextSnafu {
|
||||
reason: "raw-series region does not match request region".to_string()
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
raw_series.is_none() || !has_initial_remote_dyn_filter(&request.header, &query_ctx),
|
||||
InvalidQueryContextSnafu {
|
||||
reason: "raw-series request cannot include initial remote dynamic filters"
|
||||
.to_string()
|
||||
}
|
||||
);
|
||||
let permit = if let Some(p) = &self.inner.parallelism {
|
||||
Some(p.acquire().await?)
|
||||
} else {
|
||||
@@ -323,13 +374,14 @@ impl RegionServer {
|
||||
|
||||
let stream = self
|
||||
.inner
|
||||
.handle_read(
|
||||
.handle_read_with_raw_series(
|
||||
QueryRequest {
|
||||
header: request.header,
|
||||
region_id,
|
||||
plan,
|
||||
},
|
||||
query_ctx.clone(),
|
||||
raw_series,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -977,8 +1029,14 @@ impl FlightCraft for RegionServer {
|
||||
ensure!(!self.is_suspended(), SuspendedSnafu);
|
||||
|
||||
let ticket = request.into_inner().ticket;
|
||||
let request = api::v1::region::QueryRequest::decode(ticket.as_ref())
|
||||
let mut request = api::v1::region::QueryRequest::decode(ticket.as_ref())
|
||||
.context(servers_error::InvalidFlightTicketSnafu)?;
|
||||
let raw_series = take_raw_series_request(&mut request.header).map_err(|err| {
|
||||
servers_error::InvalidParameterSnafu {
|
||||
reason: err.to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let tracing_context = request
|
||||
.header
|
||||
.as_ref()
|
||||
@@ -1003,7 +1061,7 @@ impl FlightCraft for RegionServer {
|
||||
let initializer_tracing_context = tracing_context.clone();
|
||||
let initializer = async move {
|
||||
region_server
|
||||
.handle_remote_read(request, initializer_query_ctx)
|
||||
.handle_remote_read_inner(request, initializer_query_ctx, raw_series)
|
||||
.trace(initializer_tracing_context.attach(info_span!("RegionServer::handle_read")))
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
@@ -1861,12 +1919,24 @@ impl RegionServerInner {
|
||||
self: &Arc<Self>,
|
||||
request: QueryRequest,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
self.handle_read_with_raw_series(request, query_ctx, None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle_read_with_raw_series(
|
||||
self: &Arc<Self>,
|
||||
request: QueryRequest,
|
||||
query_ctx: QueryContextRef,
|
||||
raw_series: Option<RawSeriesRequest>,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
let live_analyze_metrics =
|
||||
query_ctx.explain_verbose() && query_ctx.live_analyze_metrics_enabled();
|
||||
let inner = self.clone();
|
||||
let mut stream = common_runtime::spawn_query(async move {
|
||||
inner.handle_read_inner(request, query_ctx).await
|
||||
inner
|
||||
.handle_read_inner(request, query_ctx, raw_series)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
.context(RuntimeJoinSnafu {
|
||||
@@ -1918,14 +1988,19 @@ impl RegionServerInner {
|
||||
&self,
|
||||
request: QueryRequest,
|
||||
query_ctx: QueryContextRef,
|
||||
raw_series: Option<RawSeriesRequest>,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
// TODO(ruihang): add metrics and set trace id
|
||||
|
||||
let result = self
|
||||
.query_engine
|
||||
.execute(request.plan, query_ctx)
|
||||
.await
|
||||
.context(ExecuteLogicalPlanSnafu)?;
|
||||
let result = match raw_series {
|
||||
Some(binding) => {
|
||||
self.query_engine
|
||||
.execute_raw_series(request.plan, query_ctx, binding)
|
||||
.await
|
||||
}
|
||||
None => self.query_engine.execute(request.plan, query_ctx).await,
|
||||
}
|
||||
.context(ExecuteLogicalPlanSnafu)?;
|
||||
|
||||
match result.data {
|
||||
OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => {
|
||||
@@ -2050,7 +2125,7 @@ mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::{Rows, SemanticType};
|
||||
use api::v1::{QueryContext as ApiQueryContext, Rows, SemanticType};
|
||||
use common_error::ext::{ErrorExt, RetryHint};
|
||||
use common_recordbatch::RecordBatches;
|
||||
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
|
||||
@@ -2060,6 +2135,7 @@ mod tests {
|
||||
use futures_util::StreamExt;
|
||||
use mito2::test_util::CreateRequestBuilder;
|
||||
use query::options::FLOW_RETURN_REGION_SEQ;
|
||||
use session::context::QueryContext as SessionQueryContext;
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::{
|
||||
@@ -2069,8 +2145,217 @@ mod tests {
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use super::*;
|
||||
use crate::error::Error;
|
||||
use crate::tests::{MockRegionEngine, mock_region_server};
|
||||
|
||||
#[test]
|
||||
fn test_raw_series_rejects_initial_dynamic_filter_intent() {
|
||||
let query_ctx = SessionQueryContext::arc();
|
||||
let mut header = RegionRequestHeader::default();
|
||||
assert!(!has_initial_remote_dyn_filter(
|
||||
&Some(header.clone()),
|
||||
&query_ctx
|
||||
));
|
||||
|
||||
header.query_context = Some(ApiQueryContext {
|
||||
extensions: HashMap::from([(
|
||||
INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY.to_string(),
|
||||
"{}".to_string(),
|
||||
)]),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(has_initial_remote_dyn_filter(&Some(header), &query_ctx));
|
||||
|
||||
let mut query_ctx = QueryContextBuilder::default().build();
|
||||
query_ctx.set_extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, "{}");
|
||||
assert!(has_initial_remote_dyn_filter(&None, &Arc::new(query_ctx)));
|
||||
}
|
||||
|
||||
fn raw_series_fixture() -> RawSeriesRequest {
|
||||
RawSeriesRequest::from_extension_value(include_str!(
|
||||
"../../../tests/compatibility/wire/raw_series_request/v1_request.json"
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_raw_marker_is_removed_before_query_context_conversion() {
|
||||
let raw = raw_series_fixture();
|
||||
let mut header = Some(RegionRequestHeader {
|
||||
query_context: Some(ApiQueryContext {
|
||||
current_catalog: "catalog_a".to_string(),
|
||||
current_schema: "schema_b".to_string(),
|
||||
timezone: "UTC".to_string(),
|
||||
channel: session::context::Channel::Internal as u32,
|
||||
snapshot_seqs: Some(api::v1::SnapshotSequences {
|
||||
snapshot_seqs: HashMap::from([(raw.physical_metadata.region_id.as_u64(), 41)]),
|
||||
sst_min_sequences: HashMap::from([(
|
||||
raw.physical_metadata.region_id.as_u64(),
|
||||
35,
|
||||
)]),
|
||||
}),
|
||||
extensions: HashMap::from([
|
||||
(
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(),
|
||||
raw.to_extension_value().unwrap(),
|
||||
),
|
||||
("unrelated.extension".to_string(), "retained".to_string()),
|
||||
]),
|
||||
explain: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(take_raw_series_request(&mut header).unwrap().is_some());
|
||||
let cleaned = header.as_ref().unwrap().query_context.as_ref().unwrap();
|
||||
assert!(
|
||||
!cleaned
|
||||
.extensions
|
||||
.contains_key(RAW_SERIES_REQUEST_EXTENSION_KEY)
|
||||
);
|
||||
assert_eq!(
|
||||
cleaned
|
||||
.extensions
|
||||
.get("unrelated.extension")
|
||||
.map(String::as_str),
|
||||
Some("retained")
|
||||
);
|
||||
let converted = SessionQueryContext::try_from(cleaned.clone()).unwrap();
|
||||
let roundtrip: ApiQueryContext = converted.into();
|
||||
assert_eq!(roundtrip.current_catalog, "catalog_a");
|
||||
assert_eq!(roundtrip.current_schema, "schema_b");
|
||||
assert_eq!(roundtrip.timezone, "UTC");
|
||||
assert_eq!(
|
||||
roundtrip.channel,
|
||||
session::context::Channel::Internal as u32
|
||||
);
|
||||
assert_eq!(
|
||||
roundtrip
|
||||
.snapshot_seqs
|
||||
.unwrap()
|
||||
.snapshot_seqs
|
||||
.get(&raw.physical_metadata.region_id.as_u64()),
|
||||
Some(&41)
|
||||
);
|
||||
assert!(
|
||||
!roundtrip
|
||||
.extensions
|
||||
.contains_key(RAW_SERIES_REQUEST_EXTENSION_KEY)
|
||||
);
|
||||
assert_eq!(
|
||||
roundtrip
|
||||
.extensions
|
||||
.get("unrelated.extension")
|
||||
.map(String::as_str),
|
||||
Some("retained")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_remote_raw_read_rejects_contaminated_context_before_decode() {
|
||||
let server = mock_region_server();
|
||||
let mut query_ctx = QueryContextBuilder::default().build();
|
||||
query_ctx.set_extension(RAW_SERIES_REQUEST_EXTENSION_KEY, "reserved");
|
||||
let request = api::v1::region::QueryRequest {
|
||||
header: Some(RegionRequestHeader::default()),
|
||||
region_id: raw_series_fixture().physical_metadata.region_id.as_u64(),
|
||||
plan: Vec::new(),
|
||||
};
|
||||
let err = server
|
||||
.handle_remote_read(request, Arc::new(query_ctx))
|
||||
.await
|
||||
.err()
|
||||
.expect("expected early raw-series rejection");
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidQueryContext { reason, .. } if reason.contains("reserved raw-series extension")
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_remote_raw_read_rejects_region_and_dynamic_intent_before_decode() {
|
||||
let server = mock_region_server();
|
||||
let mut raw = raw_series_fixture();
|
||||
raw.physical_metadata.region_id = RegionId::new(2, 1);
|
||||
let mut header = RegionRequestHeader::default();
|
||||
header.query_context = Some(ApiQueryContext {
|
||||
extensions: HashMap::from([(
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(),
|
||||
raw.to_extension_value().unwrap(),
|
||||
)]),
|
||||
..Default::default()
|
||||
});
|
||||
let request = api::v1::region::QueryRequest {
|
||||
header: Some(header),
|
||||
region_id: RegionId::new(1, 1).as_u64(),
|
||||
plan: Vec::new(),
|
||||
};
|
||||
let err = server
|
||||
.handle_remote_read(request, SessionQueryContext::arc())
|
||||
.await
|
||||
.err()
|
||||
.expect("expected early raw-series rejection");
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidQueryContext { reason, .. } if reason.contains("region does not match")
|
||||
));
|
||||
|
||||
let raw = raw_series_fixture();
|
||||
let mut header = RegionRequestHeader::default();
|
||||
header.query_context = Some(ApiQueryContext {
|
||||
extensions: HashMap::from([
|
||||
(
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(),
|
||||
raw.to_extension_value().unwrap(),
|
||||
),
|
||||
(
|
||||
INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY.to_string(),
|
||||
"{}".to_string(),
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
});
|
||||
let request = api::v1::region::QueryRequest {
|
||||
header: Some(header),
|
||||
region_id: raw.physical_metadata.region_id.as_u64(),
|
||||
plan: Vec::new(),
|
||||
};
|
||||
let err = server
|
||||
.handle_remote_read(request, SessionQueryContext::arc())
|
||||
.await
|
||||
.err()
|
||||
.expect("expected early raw-series rejection");
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidQueryContext { reason, .. } if reason.contains("initial remote dynamic filters")
|
||||
));
|
||||
|
||||
let raw = raw_series_fixture();
|
||||
let mut header = RegionRequestHeader::default();
|
||||
header.query_context = Some(ApiQueryContext {
|
||||
extensions: HashMap::from([(
|
||||
RAW_SERIES_REQUEST_EXTENSION_KEY.to_string(),
|
||||
raw.to_extension_value().unwrap(),
|
||||
)]),
|
||||
..Default::default()
|
||||
});
|
||||
let request = api::v1::region::QueryRequest {
|
||||
header: Some(header),
|
||||
region_id: raw.physical_metadata.region_id.as_u64(),
|
||||
plan: Vec::new(),
|
||||
};
|
||||
let mut supplied_ctx = QueryContextBuilder::default().build();
|
||||
supplied_ctx.set_extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, "{}");
|
||||
let err = server
|
||||
.handle_remote_read(request, Arc::new(supplied_ctx))
|
||||
.await
|
||||
.err()
|
||||
.expect("supplied context dynamic-filter intent should be rejected");
|
||||
assert!(matches!(
|
||||
err,
|
||||
Error::InvalidQueryContext { reason, .. } if reason.contains("initial remote dynamic filters")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_ingest_request() {
|
||||
let rows = || Rows {
|
||||
|
||||
+221
-11
@@ -29,18 +29,26 @@ use common_catalog::consts::is_readonly_table;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_function::function::FunctionContext;
|
||||
use common_function::function_factory::ScalarFunctionFactory;
|
||||
use common_query::request::{
|
||||
INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, RawSeriesRequest,
|
||||
};
|
||||
use common_query::{Output, OutputData, OutputMeta};
|
||||
use common_recordbatch::adapter::{RecordBatchStreamAdapter, RegionQueryStatCounters};
|
||||
use common_recordbatch::adapter::{
|
||||
RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME,
|
||||
};
|
||||
use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
|
||||
use common_telemetry::tracing;
|
||||
use datafusion::catalog::TableFunction;
|
||||
use datafusion::dataframe::DataFrame;
|
||||
use datafusion::datasource::DefaultTableSource;
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::physical_plan::analyze::AnalyzeExec;
|
||||
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
|
||||
use datafusion_common::ResolvedTableReference;
|
||||
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datafusion_expr::{
|
||||
AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WindowUDF, WriteOp,
|
||||
AggregateUDF, DmlStatement, Expr, LogicalPlan as DfLogicalPlan, LogicalPlan, Volatility,
|
||||
WindowUDF, WriteOp,
|
||||
};
|
||||
use datatypes::prelude::VectorRef;
|
||||
use datatypes::schema::Schema;
|
||||
@@ -50,7 +58,7 @@ use snafu::{OptionExt, ResultExt, ensure};
|
||||
use sqlparser::ast::AnalyzeFormat;
|
||||
use table::TableRef;
|
||||
use table::requests::{DeleteRequest, InsertRequest};
|
||||
use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec};
|
||||
use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec, SeriesScanExec};
|
||||
use tracing::Span;
|
||||
|
||||
use crate::analyze::DistAnalyzeExec;
|
||||
@@ -82,15 +90,57 @@ pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
|
||||
/// Whether to fallback to the original plan when failed to push down.
|
||||
pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
|
||||
|
||||
fn raw_expr_supported(expr: &Expr) -> bool {
|
||||
let mut supported = true;
|
||||
let _ = expr.apply(|node| {
|
||||
match node {
|
||||
Expr::Column(_) | Expr::Literal(_, _) => {}
|
||||
Expr::ScalarFunction(function)
|
||||
if function.func.signature().volatility == Volatility::Immutable => {}
|
||||
Expr::BinaryExpr(_)
|
||||
| Expr::Like(_)
|
||||
| Expr::SimilarTo(_)
|
||||
| Expr::Not(_)
|
||||
| Expr::IsNotNull(_)
|
||||
| Expr::IsNull(_)
|
||||
| Expr::IsTrue(_)
|
||||
| Expr::IsFalse(_)
|
||||
| Expr::IsUnknown(_)
|
||||
| Expr::IsNotTrue(_)
|
||||
| Expr::IsNotFalse(_)
|
||||
| Expr::IsNotUnknown(_)
|
||||
| Expr::Negative(_)
|
||||
| Expr::Between(_)
|
||||
| Expr::Case(_)
|
||||
| Expr::Cast(_)
|
||||
| Expr::TryCast(_)
|
||||
| Expr::InList(_) => {}
|
||||
_ => supported = false,
|
||||
}
|
||||
Ok(if supported {
|
||||
TreeNodeRecursion::Continue
|
||||
} else {
|
||||
TreeNodeRecursion::Stop
|
||||
})
|
||||
});
|
||||
supported
|
||||
}
|
||||
|
||||
fn query_load_region_id(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
|
||||
let mut region_id = None;
|
||||
let mut stack = vec![plan.clone()];
|
||||
|
||||
while let Some(plan) = stack.pop() {
|
||||
if plan.name() == REGION_SCAN_EXEC_NAME
|
||||
&& let Some(scan) = plan.downcast_ref::<RegionScanExec>()
|
||||
&& let Some(scan_region_id) = scan.query_load_region_id()
|
||||
{
|
||||
let scan_region_id = if plan.name() == REGION_SCAN_EXEC_NAME {
|
||||
plan.downcast_ref::<RegionScanExec>()
|
||||
.and_then(RegionScanExec::query_load_region_id)
|
||||
} else if plan.name() == SERIES_SCAN_EXEC_NAME {
|
||||
plan.downcast_ref::<SeriesScanExec>()
|
||||
.and_then(SeriesScanExec::query_load_region_id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(scan_region_id) = scan_region_id {
|
||||
match region_id {
|
||||
Some(region_id) if region_id != scan_region_id => return None,
|
||||
Some(_) => {}
|
||||
@@ -116,10 +166,16 @@ fn query_stat_counters(plan: &Arc<dyn ExecutionPlan>) -> Option<RegionQueryStatC
|
||||
let mut stack = vec![plan.clone()];
|
||||
|
||||
while let Some(plan) = stack.pop() {
|
||||
if plan.name() == REGION_SCAN_EXEC_NAME
|
||||
&& let Some(scan) = plan.downcast_ref::<RegionScanExec>()
|
||||
&& let Some(scan_counters) = scan.query_stat_counters()
|
||||
{
|
||||
let scan_counters = if plan.name() == REGION_SCAN_EXEC_NAME {
|
||||
plan.downcast_ref::<RegionScanExec>()
|
||||
.and_then(RegionScanExec::query_stat_counters)
|
||||
} else if plan.name() == SERIES_SCAN_EXEC_NAME {
|
||||
plan.downcast_ref::<SeriesScanExec>()
|
||||
.and_then(SeriesScanExec::query_stat_counters)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(scan_counters) = scan_counters {
|
||||
match &counters {
|
||||
Some(counters)
|
||||
if !Arc::ptr_eq(&counters.query_cpu_time, &scan_counters.query_cpu_time)
|
||||
@@ -523,6 +579,98 @@ impl QueryEngine for DatafusionQueryEngine {
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_raw_series(
|
||||
&self,
|
||||
plan: LogicalPlan,
|
||||
query_ctx: QueryContextRef,
|
||||
binding: RawSeriesRequest,
|
||||
) -> Result<Output> {
|
||||
use crate::dummy_catalog::DummyTableProvider;
|
||||
use crate::error::{QueryExecutionSnafu, UnimplementedSnafu};
|
||||
|
||||
let unsupported = || {
|
||||
UnimplementedSnafu {
|
||||
operation: "unsupported native raw-series plan".to_string(),
|
||||
}
|
||||
.build()
|
||||
};
|
||||
if let Some(hint) = query_ctx.extension(QUERY_PARALLELISM_HINT)
|
||||
&& hint.parse::<usize>().ok() != Some(1)
|
||||
{
|
||||
return Err(unsupported());
|
||||
}
|
||||
if query_ctx
|
||||
.extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY)
|
||||
.is_some()
|
||||
{
|
||||
return Err(unsupported());
|
||||
}
|
||||
let LogicalPlan::TableScan(scan) = &plan else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
if scan.fetch.is_some()
|
||||
|| scan.projection.is_none()
|
||||
|| !scan.statistics_requests.is_empty()
|
||||
|| scan.filters.iter().any(|e| !raw_expr_supported(e))
|
||||
{
|
||||
return Err(unsupported());
|
||||
}
|
||||
let Some(source) = scan.source.downcast_ref::<DefaultTableSource>() else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
let Some(provider) = source.table_provider.downcast_ref::<DummyTableProvider>() else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
let Some(provider) = provider.clone_for_raw_series() else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
let replacement = Arc::new(provider);
|
||||
let new_source = Arc::new(DefaultTableSource::new(replacement));
|
||||
let mut scan = scan.clone();
|
||||
scan.source = new_source;
|
||||
let plan = LogicalPlan::TableScan(scan);
|
||||
|
||||
let normal_ctx = self.engine_context(query_ctx.clone());
|
||||
let mut state = normal_ctx.state().clone();
|
||||
let config = state.config().clone().with_target_partitions(1);
|
||||
*state.config_mut() = config;
|
||||
let mut ctx = QueryEngineContext::new(state, query_ctx.clone());
|
||||
let physical = self.create_physical_plan(&mut ctx, &plan).await?;
|
||||
let physical = self.optimize_physical_plan(&mut ctx, physical)?;
|
||||
if physical.name() != REGION_SCAN_EXEC_NAME {
|
||||
return Err(unsupported());
|
||||
}
|
||||
let Some(scan) = physical.downcast_ref::<RegionScanExec>() else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
let ranges = scan.get_partition_ranges();
|
||||
let prepared = Arc::new(
|
||||
scan.with_new_partitions(vec![ranges], 1)
|
||||
.map_err(BoxedError::new)
|
||||
.context(QueryExecutionSnafu)?,
|
||||
);
|
||||
let Some(native) = prepared.clone().try_to_bound_series_scan(&binding)? else {
|
||||
return Err(unsupported());
|
||||
};
|
||||
let native_plan: Arc<dyn ExecutionPlan> = native;
|
||||
let wrapped = if let Some(wrapper) = self.plugins.get::<PhysicalPlanWrapperRef>() {
|
||||
wrapper.wrap(native_plan.clone(), query_ctx)
|
||||
} else {
|
||||
native_plan.clone()
|
||||
};
|
||||
if !Arc::ptr_eq(&native_plan, &wrapped)
|
||||
|| native_plan.schema() != wrapped.schema()
|
||||
|| wrapped.properties().output_partitioning().partition_count() != 1
|
||||
{
|
||||
return Err(unsupported());
|
||||
}
|
||||
let stream = self.execute_stream(&ctx, &wrapped)?;
|
||||
Ok(Output::new(
|
||||
OutputData::Stream(stream),
|
||||
OutputMeta::new_with_plan(wrapped),
|
||||
))
|
||||
}
|
||||
|
||||
/// Note in SQL queries, aggregate names are looked up using
|
||||
/// lowercase unless the query uses quotes. For example,
|
||||
///
|
||||
@@ -764,6 +912,7 @@ mod tests {
|
||||
use datafusion::prelude::{col, lit};
|
||||
use datafusion_common::{JoinType, NullEquality, ScalarValue};
|
||||
use datafusion_physical_expr::expressions::Column;
|
||||
use datatypes::arrow::datatypes::{DataType, Field};
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, SchemaRef};
|
||||
use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
|
||||
@@ -1042,6 +1191,67 @@ mod tests {
|
||||
.query_engine()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_entrypoint_rejects_parent_plans_and_invalid_parallel_hints() {
|
||||
let engine = create_test_engine().await;
|
||||
let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1));
|
||||
let metadata = provider.region_metadata();
|
||||
let source = Arc::new(DefaultTableSource::new(Arc::new(provider)));
|
||||
let scan = datafusion_expr::LogicalPlanBuilder::scan("raw", source, Some(vec![2]))
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let binding = RawSeriesRequest {
|
||||
version: 1,
|
||||
physical_metadata: metadata.as_ref().clone(),
|
||||
metric_name: "m".to_string(),
|
||||
logical_tags: vec![],
|
||||
field_ids: vec![3],
|
||||
};
|
||||
for hint in ["invalid", "0", "2"] {
|
||||
let ctx = Arc::new(
|
||||
QueryContextBuilder::default()
|
||||
.set_extension(QUERY_PARALLELISM_HINT.to_string(), hint.to_string())
|
||||
.build(),
|
||||
);
|
||||
let error = match engine
|
||||
.execute_raw_series(scan.clone(), ctx, binding.clone())
|
||||
.await
|
||||
{
|
||||
Err(error) => error,
|
||||
Ok(_) => panic!("invalid parallelism hint was accepted"),
|
||||
};
|
||||
assert!(matches!(
|
||||
error,
|
||||
crate::error::Error::Unimplemented { operation, .. }
|
||||
if operation == "unsupported native raw-series plan"
|
||||
));
|
||||
}
|
||||
assert!(raw_expr_supported(&lit(1_i64).eq(lit(2_i64))));
|
||||
assert!(!raw_expr_supported(&Expr::ScalarVariable(
|
||||
Arc::new(Field::new("v", DataType::Int64, true)),
|
||||
vec!["v".into()],
|
||||
)));
|
||||
|
||||
let parent = datafusion_expr::LogicalPlanBuilder::from(scan.clone())
|
||||
.filter(col("v0").gt(lit(0.0)))
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let error = match engine
|
||||
.execute_raw_series(parent, QueryContext::arc(), binding)
|
||||
.await
|
||||
{
|
||||
Err(error) => error,
|
||||
Ok(_) => panic!("a parent logical plan was accepted"),
|
||||
};
|
||||
assert!(matches!(
|
||||
error,
|
||||
crate::error::Error::Unimplemented { operation, .. }
|
||||
if operation == "unsupported native raw-series plan"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sql_to_plan() {
|
||||
let engine = create_test_engine().await;
|
||||
|
||||
@@ -286,6 +286,19 @@ impl DummyTableProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clones this provider for a trusted raw-series scan, unless it carries a
|
||||
/// row selector which changes the requested rows.
|
||||
pub(crate) fn clone_for_raw_series(&self) -> Option<Self> {
|
||||
let provider = self.clone_for_scan();
|
||||
let mut request = provider.scan_request.lock().unwrap();
|
||||
if request.series_row_selector.is_some() {
|
||||
return None;
|
||||
}
|
||||
request.distribution = Some(TimeSeriesDistribution::PerSeries);
|
||||
drop(request);
|
||||
Some(provider)
|
||||
}
|
||||
|
||||
pub fn with_sequence(&self, sequence: u64) {
|
||||
self.scan_request.lock().unwrap().memtable_max_sequence = Some(sequence);
|
||||
}
|
||||
@@ -653,6 +666,32 @@ mod tests {
|
||||
FLOW_RETURN_REGION_SEQ, FLOW_SINK_TABLE_ID,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn raw_provider_clone_sets_per_series_without_mutating_shared_request() {
|
||||
let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1));
|
||||
let original = provider.scan_request();
|
||||
let raw = provider.clone_for_raw_series().unwrap();
|
||||
assert_eq!(
|
||||
raw.scan_request().distribution,
|
||||
Some(TimeSeriesDistribution::PerSeries)
|
||||
);
|
||||
assert_eq!(provider.scan_request(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_provider_clone_rejects_selector_and_preserves_snapshot_intent() {
|
||||
let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1));
|
||||
provider
|
||||
.with_time_series_selector_hint(TimeSeriesRowSelector::LastRow { after_merge: false });
|
||||
assert!(provider.clone_for_raw_series().is_none());
|
||||
|
||||
let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1));
|
||||
provider.with_sequence(42);
|
||||
let raw = provider.clone_for_raw_series().unwrap();
|
||||
assert_eq!(raw.scan_request().memtable_max_sequence, Some(42));
|
||||
assert_eq!(provider.scan_request().distribution, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nullable_label_filter_pushdown() {
|
||||
use datafusion_expr::{Cast, col, lit};
|
||||
|
||||
@@ -29,6 +29,7 @@ use common_function::handlers::{
|
||||
FlowServiceHandlerRef, ProcedureServiceHandlerRef, TableMutationHandlerRef,
|
||||
};
|
||||
use common_query::Output;
|
||||
use common_query::request::RawSeriesRequest;
|
||||
use datafusion::catalog::TableFunction;
|
||||
use datafusion::dataframe::DataFrame;
|
||||
use datafusion_expr::{AggregateUDF, LogicalPlan, WindowUDF};
|
||||
@@ -77,6 +78,19 @@ pub trait QueryEngine: Send + Sync {
|
||||
/// Execute the given [`LogicalPlan`].
|
||||
async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output>;
|
||||
|
||||
/// Execute a native single-region raw-series scan.
|
||||
async fn execute_raw_series(
|
||||
&self,
|
||||
_plan: LogicalPlan,
|
||||
_query_ctx: QueryContextRef,
|
||||
_binding: RawSeriesRequest,
|
||||
) -> Result<Output> {
|
||||
crate::error::UnimplementedSnafu {
|
||||
operation: "native raw-series query",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
/// Register an aggregate function.
|
||||
///
|
||||
/// # Panics
|
||||
|
||||
@@ -21,7 +21,9 @@ use api::v1::SemanticType;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_query::request::RawSeriesRequest;
|
||||
use common_query::series_frame::pack_raw_series;
|
||||
use common_recordbatch::adapter::{RecordBatchStreamAdapter, RegionQueryStatCounters};
|
||||
use common_recordbatch::adapter::{
|
||||
RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME,
|
||||
};
|
||||
use common_recordbatch::{
|
||||
DfRecordBatch, DfSendableRecordBatchStream, MemoryTrackedStream, QueryMemoryTracker,
|
||||
RecordBatch, SendableRecordBatchStream,
|
||||
@@ -526,6 +528,14 @@ impl SeriesScanExec {
|
||||
pub fn series_schema(&self) -> &Arc<SeriesSchema> {
|
||||
&self.series_schema
|
||||
}
|
||||
|
||||
pub fn query_load_region_id(&self) -> Option<u64> {
|
||||
self.scan.query_load_region_id()
|
||||
}
|
||||
|
||||
pub fn query_stat_counters(&self) -> Option<RegionQueryStatCounters> {
|
||||
self.scan.query_stat_counters()
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_label_mode(source: &RawLabelSource) -> RawLabelMode {
|
||||
@@ -603,7 +613,7 @@ impl ExecutionPlan for SeriesScanExec {
|
||||
Ok(self)
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
"SeriesScanExec"
|
||||
SERIES_SCAN_EXEC_NAME
|
||||
}
|
||||
fn metrics(&self) -> Option<MetricsSet> {
|
||||
Some(self.scan.metric.clone_inner())
|
||||
|
||||
@@ -892,6 +892,27 @@ async fn memory_quota_failure_does_not_replay_raw_scan() {
|
||||
assert_eq!(tracker_for_assertion.current(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_series_scan_forwards_query_load_region_id() {
|
||||
let schema = series_schema();
|
||||
let (scan, _) = fixture(Some(schema), vec![]);
|
||||
let region_id = RegionId::new(1, 99);
|
||||
scan.scanner
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_query_load_region_id(region_id);
|
||||
let plan = scan
|
||||
.try_to_series_scan(RawLabelSource::Explicit)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(plan.query_load_region_id(), Some(region_id.as_u64()));
|
||||
assert_eq!(
|
||||
plan.name(),
|
||||
common_recordbatch::adapter::SERIES_SCAN_EXEC_NAME
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bound_series_scan_uses_open_scanner_metadata_without_execution() {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
|
||||
Reference in New Issue
Block a user