mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
fix(query): preserve raw scan lifecycle and frame-only reads
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
Generated
+1
@@ -4528,6 +4528,7 @@ dependencies = [
|
||||
"snafu 0.8.6",
|
||||
"store-api",
|
||||
"strum 0.27.1",
|
||||
"substrait 1.4.0-alpha.0",
|
||||
"table",
|
||||
"tokio",
|
||||
"toml 0.8.23",
|
||||
|
||||
@@ -77,9 +77,11 @@ tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
cache.workspace = true
|
||||
catalog = { workspace = true, features = ["testing"] }
|
||||
common-meta = { workspace = true, features = ["testing"] }
|
||||
common-query.workspace = true
|
||||
common-test-util.workspace = true
|
||||
datafusion-common.workspace = true
|
||||
mito2 = { workspace = true, features = ["test"] }
|
||||
session.workspace = true
|
||||
substrait.workspace = true
|
||||
|
||||
@@ -40,8 +40,11 @@ use common_error::status_code::StatusCode;
|
||||
use common_meta::datanode::TopicStatsReporter;
|
||||
use common_query::OutputData;
|
||||
use common_query::request::{QueryRequest, RAW_SERIES_READ_EXTENSION_KEY, RegionReadKind};
|
||||
use common_query::series_frame::raw_series_frame_ordering;
|
||||
use common_recordbatch::adapter::RecordBatchMetrics;
|
||||
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream};
|
||||
use common_recordbatch::{
|
||||
DfRecordBatch, OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream,
|
||||
};
|
||||
use common_runtime::Runtime;
|
||||
use common_telemetry::tracing::{self, info_span};
|
||||
use common_telemetry::tracing_context::{FutureExt, TracingContext};
|
||||
@@ -51,6 +54,10 @@ use datafusion::datasource::TableProvider;
|
||||
use datafusion_common::tree_node::TreeNode;
|
||||
use datafusion_expr::LogicalPlan;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use datatypes::series::frame::{
|
||||
RawLabelMode, RawSeriesFrameDecoder, raw_series_frame_label_decode,
|
||||
raw_series_frame_series_schema,
|
||||
};
|
||||
use either::Either;
|
||||
use futures_util::future::try_join_all;
|
||||
use futures_util::{Stream, StreamExt};
|
||||
@@ -105,7 +112,9 @@ use crate::error::{
|
||||
};
|
||||
use crate::event_listener::RegionServerEventListenerRef;
|
||||
use crate::query_stream::QueryRuntimeStream;
|
||||
use crate::region_server::catalog::{NameAwareCatalogList, NameAwareDataSourceInjectorBuilder};
|
||||
use crate::region_server::catalog::{
|
||||
InternalTableKind, NameAwareCatalogList, NameAwareDataSourceInjectorBuilder,
|
||||
};
|
||||
use crate::region_server::registrations::RemoteDynFilterRegistry;
|
||||
use crate::region_server::remote_dyn_filter::wrap_remote_dyn_filter_guarded_stream;
|
||||
|
||||
@@ -160,12 +169,27 @@ fn validate_raw_series_request(request: &QueryRequest) -> Result<()> {
|
||||
let LogicalPlan::TableScan(scan) = &request.plan else {
|
||||
unreachable!("plan was checked to be a TableScan");
|
||||
};
|
||||
// A bare scan may carry an empty table name, and an empty name is also the sentinel the
|
||||
// region's table provider reads as "no metric": such a read would silently be answered
|
||||
// with rows. A frame names the series it frames, so an unnamed scan is rejected here.
|
||||
ensure!(
|
||||
!scan.table_name.table().is_empty(),
|
||||
UnexpectedSnafu {
|
||||
violated: "RawSeries read requires a named table scan",
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
scan.fetch.is_none(),
|
||||
UnexpectedSnafu {
|
||||
violated: "RawSeries read does not support fetch",
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
InternalTableKind::from_table_name(scan.table_name.table()).is_none(),
|
||||
UnexpectedSnafu {
|
||||
violated: "RawSeries read does not support inspection tables",
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2003,6 +2027,10 @@ impl RegionServerInner {
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
// TODO(ruihang): add metrics and set trace id
|
||||
//
|
||||
// Captured before the plan moves into the engine: the answer to a raw-series read is
|
||||
// checked against the frame contract below.
|
||||
let raw_series = request.read_kind == RegionReadKind::RawSeries;
|
||||
|
||||
let result = self
|
||||
.query_engine
|
||||
@@ -2014,7 +2042,42 @@ impl RegionServerInner {
|
||||
OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => {
|
||||
UnsupportedOutputSnafu { expected: "stream" }.fail()
|
||||
}
|
||||
OutputData::Stream(stream) => Ok(stream),
|
||||
OutputData::Stream(stream) if !raw_series => Ok(stream),
|
||||
OutputData::Stream(stream) => {
|
||||
// The table provider comes from configuration, so the request being a bare scan
|
||||
// says nothing about the answer's shape: a factory could serve an ordinary row
|
||||
// table for the same name. The declared Arrow schema must therefore be a raw
|
||||
// series frame. The empty batch is decoded to compare the exact fields, types and
|
||||
// order; no row is polled. Rows are left untouched.
|
||||
let arrow = stream.schema().arrow_schema().clone();
|
||||
raw_series_frame_label_decode(&arrow)
|
||||
.and_then(|decode| {
|
||||
let mode = if decode.is_some() {
|
||||
RawLabelMode::Key
|
||||
} else {
|
||||
RawLabelMode::Explicit
|
||||
};
|
||||
let series = raw_series_frame_series_schema(&arrow)?;
|
||||
RawSeriesFrameDecoder::try_new(&series, mode)?
|
||||
.decode(&DfRecordBatch::new_empty(arrow.clone()))?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| {
|
||||
UnexpectedSnafu {
|
||||
violated: format!(
|
||||
"RawSeries read answered with a non-frame stream: {e}"
|
||||
),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
raw_series_frame_ordering(&arrow).map_err(|e| {
|
||||
UnexpectedSnafu {
|
||||
violated: format!("RawSeries read answered with unusable ordering: {e}"),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
Ok(stream)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2135,21 +2198,42 @@ mod tests {
|
||||
|
||||
use api::v1::{Rows, SemanticType};
|
||||
use common_error::ext::{ErrorExt, RetryHint};
|
||||
use common_query::series_frame::unpack_raw_series;
|
||||
use common_recordbatch::RecordBatches;
|
||||
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
|
||||
use common_recordbatch::adapter::{
|
||||
DfRecordBatchStreamAdapter, RecordBatchMetrics, RegionWatermarkEntry,
|
||||
};
|
||||
use common_recordbatch::util as recordbatch_util;
|
||||
use common_runtime::runtime::{BuilderBuild, RuntimeTrait};
|
||||
use datafusion::catalog::MemTable;
|
||||
use datatypes::arrow::array::{Array, Int32Array, UInt64Array};
|
||||
use datatypes::arrow::datatypes::Schema as ArrowSchema;
|
||||
use datatypes::prelude::{ConcreteDataType, VectorRef};
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use datatypes::vectors::Int32Vector;
|
||||
use futures_util::StreamExt;
|
||||
use mito2::test_util::CreateRequestBuilder;
|
||||
use query::options::FLOW_RETURN_REGION_SEQ;
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::{
|
||||
PathType, RegionCleanUpRequest, RegionCompactRequest, RegionDeleteRequest,
|
||||
RegionDropRequest, RegionOpenRequest, RegionPutRequest, RegionTruncateRequest,
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::frame::{
|
||||
LABEL_DECODE_VERSION, LabelDecodeEncoding, LabelDecodeSpec, LabelDecodeTag,
|
||||
};
|
||||
use datatypes::series::raw::RawSeriesChunk;
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, SeriesSchema};
|
||||
use datatypes::vectors::Int32Vector;
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
use mito2::config::MitoConfig;
|
||||
use mito2::test_util::{CreateRequestBuilder, TestEnv};
|
||||
use query::QueryEngineFactory;
|
||||
use query::options::{FLOW_RETURN_REGION_SEQ, QueryOptions};
|
||||
use query::query_engine::DefaultSerializer;
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder};
|
||||
use store_api::region_engine::{RegionEngine, RegionRole};
|
||||
use store_api::region_info::RegionInfoEntry;
|
||||
use store_api::region_request::{
|
||||
PathType, RegionCleanUpRequest, RegionCompactRequest, RegionCreateRequest,
|
||||
RegionDeleteRequest, RegionDropRequest, RegionOpenRequest, RegionPutRequest,
|
||||
RegionTruncateRequest,
|
||||
};
|
||||
use store_api::sst_entry::{ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEntry};
|
||||
use store_api::storage::RegionId;
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
|
||||
use super::*;
|
||||
use crate::tests::{MockRegionEngine, mock_region_server};
|
||||
@@ -3070,6 +3154,192 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A real Mito region behind a real query engine, so a read exercises the whole
|
||||
/// `RegionServer::handle_read` path instead of a mocked provider.
|
||||
struct RawSeriesFixture {
|
||||
server: RegionServer,
|
||||
engine: Arc<MitoEngine>,
|
||||
region_id: RegionId,
|
||||
create: RegionCreateRequest,
|
||||
arrow_schema: ArrowSchema,
|
||||
/// Kept last so the temporary storage outlives the server and engine that use it.
|
||||
_env: TestEnv,
|
||||
}
|
||||
|
||||
impl RawSeriesFixture {
|
||||
async fn new(prefix: &str, field_num: usize) -> Self {
|
||||
Self::with_factory(prefix, field_num, Arc::new(DummyTableProviderFactory)).await
|
||||
}
|
||||
|
||||
async fn with_factory(
|
||||
prefix: &str,
|
||||
field_num: usize,
|
||||
table_provider_factory: TableProviderFactoryRef,
|
||||
) -> Self {
|
||||
let mut env = TestEnv::with_prefix(prefix).await;
|
||||
let engine = Arc::new(env.create_engine(MitoConfig::default()).await);
|
||||
let query_engine = QueryEngineFactory::new(
|
||||
::catalog::memory::MemoryCatalogManager::new(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
QueryOptions::default(),
|
||||
)
|
||||
.query_engine();
|
||||
let mut server = RegionServer::with_table_provider(
|
||||
query_engine,
|
||||
Runtime::builder().build().unwrap(),
|
||||
Box::new(crate::event_listener::NoopRegionServerEventListener),
|
||||
table_provider_factory,
|
||||
0,
|
||||
Duration::from_millis(0),
|
||||
FlightCompression::default(),
|
||||
);
|
||||
server.register_engine(engine.clone());
|
||||
let region_id = RegionId::new(2048, 1);
|
||||
let create = CreateRequestBuilder::new().field_num(field_num).build();
|
||||
server
|
||||
.handle_request(region_id, RegionRequest::Create(create.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
server
|
||||
.set_region_role(region_id, RegionRole::Leader)
|
||||
.unwrap();
|
||||
let arrow_schema = Schema::new(
|
||||
create
|
||||
.column_metadatas
|
||||
.iter()
|
||||
.map(|column| column.column_schema.clone())
|
||||
.collect(),
|
||||
)
|
||||
.arrow_schema()
|
||||
.as_ref()
|
||||
.clone();
|
||||
Self {
|
||||
server,
|
||||
engine,
|
||||
region_id,
|
||||
create,
|
||||
arrow_schema,
|
||||
_env: env,
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_plan(&self, table: &str, projection: Option<Vec<usize>>) -> LogicalPlan {
|
||||
datafusion_expr::table_scan(Some(table), &self.arrow_schema, projection)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn request(&self, plan: LogicalPlan, read_kind: RegionReadKind) -> QueryRequest {
|
||||
QueryRequest {
|
||||
header: None,
|
||||
region_id: self.region_id,
|
||||
plan,
|
||||
read_kind,
|
||||
}
|
||||
}
|
||||
|
||||
async fn put(&self, key: &str, timestamps: &[i64], fields: &[(Option<i64>, Option<i64>)]) {
|
||||
mito2::test_util::put_rows(
|
||||
&self.engine,
|
||||
self.region_id,
|
||||
Rows {
|
||||
schema: mito2::test_util::rows_schema(&self.create),
|
||||
rows: mito2::test_util::build_rows_with_fields(key, timestamps, fields),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn stop(&self) {
|
||||
self.server.stop().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A configured table provider factory that always serves one ordinary row table.
|
||||
///
|
||||
/// `RegionServer::with_table_provider` accepts such factories from configuration, so the
|
||||
/// region's metadata does not determine the answer's shape on its own.
|
||||
struct RowsTableProviderFactory(Arc<dyn TableProvider>);
|
||||
|
||||
#[async_trait]
|
||||
impl query::dummy_catalog::TableProviderFactory for RowsTableProviderFactory {
|
||||
async fn create(
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
_engine: RegionEngineRef,
|
||||
_ctx: Option<QueryContextRef>,
|
||||
) -> query::error::Result<Arc<dyn TableProvider>> {
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a region read into validated raw-series chunks and the layout it declared.
|
||||
async fn unpack_frames(
|
||||
stream: SendableRecordBatchStream,
|
||||
fields: &[&str],
|
||||
) -> (
|
||||
Vec<String>,
|
||||
LabelDecodeSpec,
|
||||
SeriesOrdering,
|
||||
Vec<RawSeriesChunk>,
|
||||
) {
|
||||
let expected = Arc::new(SeriesSchema {
|
||||
fields: fields
|
||||
.iter()
|
||||
.map(|name| FieldSpec {
|
||||
name: Arc::from(*name),
|
||||
})
|
||||
.collect(),
|
||||
eval_grid: None,
|
||||
});
|
||||
let frames = unpack_raw_series(
|
||||
Box::pin(DfRecordBatchStreamAdapter::new(stream)),
|
||||
Some(expected),
|
||||
)
|
||||
.unwrap();
|
||||
let field_names = frames
|
||||
.schema()
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.name.to_string())
|
||||
.collect();
|
||||
let decode = frames
|
||||
.label_decode_spec()
|
||||
.cloned()
|
||||
.expect("a key-encoded frame declares its label decode description");
|
||||
let ordering = frames.ordering();
|
||||
let chunks = frames.try_collect::<Vec<_>>().await.unwrap();
|
||||
(field_names, decode, ordering, chunks)
|
||||
}
|
||||
|
||||
fn float_at(chunk: &RawSeriesChunk, field: usize, row: usize) -> Option<f64> {
|
||||
match chunk.fields.as_slice()[field].sample(row) {
|
||||
SampleRef::Float(value) => Some(value),
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Histogram(_) => panic!("the fixture stores float samples"),
|
||||
}
|
||||
}
|
||||
|
||||
fn timestamps(chunk: &RawSeriesChunk) -> Vec<i64> {
|
||||
chunk.time.as_buffer().iter().copied().collect()
|
||||
}
|
||||
|
||||
fn inspection_scan_plan() -> LogicalPlan {
|
||||
datafusion_expr::table_scan(
|
||||
Some(RegionInfoEntry::reserved_table_name_for_inspection()),
|
||||
RegionInfoEntry::schema().arrow_schema().as_ref(),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn query_request(plan: LogicalPlan, read_kind: RegionReadKind) -> QueryRequest {
|
||||
QueryRequest {
|
||||
header: None,
|
||||
@@ -3079,6 +3349,388 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_inspection_table_is_rejected_but_rows_read_region_info() {
|
||||
let fixture = RawSeriesFixture::new("raw-series-inspection", 1).await;
|
||||
let plan = inspection_scan_plan();
|
||||
|
||||
// The same bare scan that is a valid inspection read as rows must not be answered as a
|
||||
// frame: the reserved table is replaced by a row `MemTable`, so no frame can come back.
|
||||
let Err(err) = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(plan.clone(), RegionReadKind::RawSeries))
|
||||
.await
|
||||
else {
|
||||
panic!("a RawSeries read of an inspection table must be rejected");
|
||||
};
|
||||
let crate::error::Error::Unexpected { violated, .. } = &err else {
|
||||
panic!("expected an inspection-specific rejection, got {err}");
|
||||
};
|
||||
assert!(
|
||||
violated.contains("inspection tables"),
|
||||
"unexpected rejection cause: {violated}"
|
||||
);
|
||||
|
||||
let rows = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(plan, RegionReadKind::Rows))
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = recordbatch_util::collect(rows).await.unwrap();
|
||||
assert_eq!(1, batches.len());
|
||||
let batch = &batches[0];
|
||||
assert_eq!(
|
||||
batch
|
||||
.schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| (column.name.clone(), column.data_type.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
RegionInfoEntry::schema()
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| (column.name.clone(), column.data_type.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(1, batch.num_rows());
|
||||
let region_id_column: &dyn Array = batch.column(0).as_ref();
|
||||
let region_ids = region_id_column
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(fixture.region_id.as_u64(), region_ids.value(0));
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_handle_read_answers_region_frames() {
|
||||
let fixture = RawSeriesFixture::new("raw-series-handle-read", 2).await;
|
||||
fixture
|
||||
.put(
|
||||
"host-a",
|
||||
&[1, 2],
|
||||
&[(Some(1), Some(10)), (Some(2), Some(20))],
|
||||
)
|
||||
.await;
|
||||
fixture
|
||||
.put("host-b", &[1, 2], &[(Some(3), None), (Some(4), Some(40))])
|
||||
.await;
|
||||
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(
|
||||
fixture.scan_plan("cpu_usage", None),
|
||||
RegionReadKind::RawSeries,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let (fields, decode, ordering, chunks) =
|
||||
unpack_frames(stream, &["field_0", "field_1"]).await;
|
||||
|
||||
assert_eq!(vec!["field_0".to_string(), "field_1".to_string()], fields);
|
||||
assert_eq!(SeriesOrdering::KeyThenTime, ordering);
|
||||
assert_eq!(LABEL_DECODE_VERSION, decode.version);
|
||||
assert_eq!("cpu_usage", decode.metric_name);
|
||||
assert_eq!(LabelDecodeEncoding::Dense, decode.encoding);
|
||||
assert_eq!(1, decode.primary_key.len());
|
||||
assert_eq!(0, decode.primary_key[0].column_id);
|
||||
assert_eq!("tag_0", decode.primary_key[0].name);
|
||||
assert_eq!(
|
||||
ConcreteDataType::string_datatype(),
|
||||
decode.primary_key[0].physical_type
|
||||
);
|
||||
assert_eq!(
|
||||
vec![LabelDecodeTag {
|
||||
column_id: 0,
|
||||
name: "tag_0".to_string(),
|
||||
}],
|
||||
decode.logical_tags
|
||||
);
|
||||
|
||||
// A producer may split a series across chunks, so group by encoded key and compare the
|
||||
// complete per-series payload rather than assuming one chunk per series.
|
||||
let mut by_key: HashMap<Vec<u8>, Vec<&RawSeriesChunk>> = HashMap::new();
|
||||
for chunk in &chunks {
|
||||
assert!(chunk.metric.is_none(), "key labels stay undecoded");
|
||||
assert!(!chunk.primary_key.is_empty());
|
||||
assert_eq!(2, chunk.fields.len());
|
||||
by_key
|
||||
.entry(chunk.primary_key.to_vec())
|
||||
.or_default()
|
||||
.push(chunk);
|
||||
}
|
||||
assert_eq!(2, by_key.len(), "each series keeps its own encoded key");
|
||||
let series_values = |group: &[&RawSeriesChunk], field: usize| {
|
||||
group
|
||||
.iter()
|
||||
.flat_map(|chunk| (0..chunk.time.len()).map(move |row| float_at(chunk, field, row)))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let mut payloads = Vec::new();
|
||||
for group in by_key.values() {
|
||||
assert!(group.last().unwrap().is_last);
|
||||
assert_eq!(
|
||||
vec![1000, 2000],
|
||||
group
|
||||
.iter()
|
||||
.flat_map(|chunk| timestamps(chunk))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
payloads.push((series_values(group, 0), series_values(group, 1)));
|
||||
}
|
||||
payloads.sort_by(|left, right| left.0[0].unwrap().total_cmp(&right.0[0].unwrap()));
|
||||
assert_eq!(
|
||||
vec![
|
||||
(vec![Some(1.0), Some(2.0)], vec![Some(10.0), Some(20.0)]),
|
||||
(vec![Some(3.0), Some(4.0)], vec![None, Some(40.0)]),
|
||||
],
|
||||
payloads
|
||||
);
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_handle_read_answers_empty_region_with_its_layout() {
|
||||
let fixture = RawSeriesFixture::new("raw-series-handle-read-empty", 2).await;
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(
|
||||
fixture.scan_plan("cpu_usage", None),
|
||||
RegionReadKind::RawSeries,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let (fields, decode, ordering, chunks) =
|
||||
unpack_frames(stream, &["field_0", "field_1"]).await;
|
||||
|
||||
assert_eq!(vec!["field_0".to_string(), "field_1".to_string()], fields);
|
||||
assert_eq!(SeriesOrdering::KeyThenTime, ordering);
|
||||
assert_eq!("cpu_usage", decode.metric_name);
|
||||
assert!(chunks.is_empty(), "an empty region frames no chunk");
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_handle_read_applies_projection_order_and_pushed_predicate() {
|
||||
let fixture = RawSeriesFixture::new("raw-series-handle-read-projection", 2).await;
|
||||
fixture
|
||||
.put(
|
||||
"host-a",
|
||||
&[1, 2],
|
||||
&[(Some(1), Some(10)), (Some(2), Some(20))],
|
||||
)
|
||||
.await;
|
||||
fixture
|
||||
.put("host-b", &[1, 2], &[(Some(3), None), (Some(4), Some(40))])
|
||||
.await;
|
||||
|
||||
// Read the unfiltered frames once to learn host-a's encoded key.
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(
|
||||
fixture.scan_plan("cpu_usage", None),
|
||||
RegionReadKind::RawSeries,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let (_, _, _, all) = unpack_frames(stream, &["field_0", "field_1"]).await;
|
||||
let host_a_key = all
|
||||
.iter()
|
||||
.find(|chunk| float_at(chunk, 0, 0) == Some(1.0))
|
||||
.expect("host-a's unfiltered chunk")
|
||||
.primary_key
|
||||
.to_vec();
|
||||
|
||||
// A reordered projection selects field_1 before field_0, and a pushed-down tag predicate
|
||||
// keeps only host-a, whose frame must still carry the same complete encoded key.
|
||||
let mut plan = fixture.scan_plan("cpu_usage", Some(vec![3, 2, 1, 0]));
|
||||
let LogicalPlan::TableScan(scan) = &mut plan else {
|
||||
panic!("the fixture builds a table scan");
|
||||
};
|
||||
scan.filters = vec![datafusion_expr::col("tag_0").eq(datafusion_expr::lit("host-a"))];
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(plan, RegionReadKind::RawSeries))
|
||||
.await
|
||||
.unwrap();
|
||||
let (fields, _, _, chunks) = unpack_frames(stream, &["field_1", "field_0"]).await;
|
||||
|
||||
assert_eq!(vec!["field_1".to_string(), "field_0".to_string()], fields);
|
||||
assert!(!chunks.is_empty(), "the pushed predicate keeps one series");
|
||||
assert!(chunks.last().unwrap().is_last);
|
||||
for chunk in &chunks {
|
||||
assert_eq!(host_a_key, chunk.primary_key.to_vec());
|
||||
}
|
||||
let times = chunks
|
||||
.iter()
|
||||
.flat_map(|chunk| timestamps(chunk))
|
||||
.collect::<Vec<_>>();
|
||||
let field_1 = chunks
|
||||
.iter()
|
||||
.flat_map(|chunk| (0..chunk.time.len()).map(move |row| float_at(chunk, 0, row)))
|
||||
.collect::<Vec<_>>();
|
||||
let field_0 = chunks
|
||||
.iter()
|
||||
.flat_map(|chunk| (0..chunk.time.len()).map(move |row| float_at(chunk, 1, row)))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(vec![1000, 2000], times);
|
||||
assert_eq!(vec![Some(10.0), Some(20.0)], field_1);
|
||||
assert_eq!(vec![Some(1.0), Some(2.0)], field_0);
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
/// A configured factory can serve ordinary rows for the same table name, so a raw-series read
|
||||
/// must reject the answer by its declared shape instead of returning rows.
|
||||
#[tokio::test]
|
||||
async fn raw_series_read_rejects_a_configured_factory_that_answers_with_rows() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"v",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
true,
|
||||
)]));
|
||||
let values: VectorRef = Arc::new(Int32Vector::from_slice([42]));
|
||||
let batch = RecordBatch::new(schema.clone(), vec![values]).unwrap();
|
||||
let table = MemTable::try_new(
|
||||
schema.arrow_schema().clone(),
|
||||
vec![vec![batch.into_df_record_batch()]],
|
||||
)
|
||||
.unwrap();
|
||||
let fixture = RawSeriesFixture::with_factory(
|
||||
"raw-series-row-factory",
|
||||
2,
|
||||
Arc::new(RowsTableProviderFactory(Arc::new(table))),
|
||||
)
|
||||
.await;
|
||||
|
||||
// `scan_plan`'s single Int32 column `v` is exactly the row table's schema.
|
||||
let plan = scan_plan("cpu");
|
||||
let Err(err) = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(plan.clone(), RegionReadKind::RawSeries))
|
||||
.await
|
||||
else {
|
||||
panic!("a row answer must not satisfy a raw-series read");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("non-frame stream"),
|
||||
"unexpected rejection cause: {err}"
|
||||
);
|
||||
|
||||
// The identical request as an ordinary read keeps the configured provider's row.
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_read(fixture.request(plan, RegionReadKind::Rows))
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(1, batches.iter().count());
|
||||
let batch = batches.iter().next().unwrap();
|
||||
assert_eq!(1, batch.num_rows());
|
||||
let column: &dyn Array = batch.column(0).as_ref();
|
||||
assert_eq!(
|
||||
42,
|
||||
column
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap()
|
||||
.value(0)
|
||||
);
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
/// A remote read is sanitized from its own context, never from the caller's extensions: even a
|
||||
/// context that already names a raw-series metric must receive ordinary rows.
|
||||
#[tokio::test]
|
||||
async fn remote_read_cannot_be_spoofed_into_raw_series() {
|
||||
let fixture = RawSeriesFixture::new("raw-series-remote-read", 2).await;
|
||||
fixture
|
||||
.put(
|
||||
"host-a",
|
||||
&[1, 2],
|
||||
&[(Some(1), Some(10)), (Some(2), Some(20))],
|
||||
)
|
||||
.await;
|
||||
fixture
|
||||
.put("host-b", &[1, 2], &[(Some(3), None), (Some(4), Some(40))])
|
||||
.await;
|
||||
|
||||
let plan = DFLogicalSubstraitConvertor
|
||||
.encode(&fixture.scan_plan("cpu_usage", None), DefaultSerializer)
|
||||
.unwrap();
|
||||
let spoofed = Arc::new(
|
||||
QueryContextBuilder::default()
|
||||
.extensions(HashMap::from([(
|
||||
RAW_SERIES_READ_EXTENSION_KEY.to_string(),
|
||||
"spoofed_metric".to_string(),
|
||||
)]))
|
||||
.build(),
|
||||
);
|
||||
let stream = fixture
|
||||
.server
|
||||
.handle_remote_read(
|
||||
api::v1::region::QueryRequest {
|
||||
header: None,
|
||||
region_id: fixture.region_id.as_u64(),
|
||||
plan: plan.to_vec(),
|
||||
},
|
||||
spoofed,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
|
||||
let schema = batches.schema();
|
||||
assert_eq!(
|
||||
vec!["tag_0", "field_0", "field_1", "ts"],
|
||||
schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| column.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
vec![
|
||||
ConcreteDataType::dictionary_datatype(
|
||||
ConcreteDataType::uint32_datatype(),
|
||||
ConcreteDataType::string_datatype(),
|
||||
),
|
||||
ConcreteDataType::float64_datatype(),
|
||||
ConcreteDataType::float64_datatype(),
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
],
|
||||
schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| column.data_type.clone())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert!(
|
||||
schema
|
||||
.arrow_schema()
|
||||
.metadata()
|
||||
.keys()
|
||||
.all(|key| !key.starts_with("greptime.series.")),
|
||||
"a spoofed remote read must not answer with a raw frame"
|
||||
);
|
||||
let expected = "\
|
||||
+--------+---------+---------+---------------------+
|
||||
| tag_0 | field_0 | field_1 | ts |
|
||||
+--------+---------+---------+---------------------+
|
||||
| host-a | 1.0 | 10.0 | 1970-01-01T00:00:01 |
|
||||
| host-a | 2.0 | 20.0 | 1970-01-01T00:00:02 |
|
||||
| host-b | 3.0 | | 1970-01-01T00:00:01 |
|
||||
| host-b | 4.0 | 40.0 | 1970-01-01T00:00:02 |
|
||||
+--------+---------+---------+---------------------+";
|
||||
assert_eq!(expected, batches.pretty_print().unwrap());
|
||||
|
||||
fixture.stop().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_series_metric_is_the_table_scan_the_plan_is() {
|
||||
// An ordinary read names no metric, so the region keeps its row answer.
|
||||
@@ -3133,6 +3785,24 @@ mod tests {
|
||||
assert_eq!(ctx.extension(RAW_SERIES_READ_EXTENSION_KEY), Some(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_series_request_rejects_an_unnamed_scan() {
|
||||
// An empty table name is also the table provider's "no metric" sentinel, so answering it
|
||||
// would silently downgrade a frame request to rows. The plan builder refuses an empty name,
|
||||
// so this is the hand-built request the check exists for.
|
||||
let mut plan = scan_plan("cpu");
|
||||
let LogicalPlan::TableScan(scan) = &mut plan else {
|
||||
panic!("the fixture is a table scan");
|
||||
};
|
||||
scan.table_name = datafusion_common::TableReference::bare("");
|
||||
let request = query_request(plan, RegionReadKind::RawSeries);
|
||||
let err = validate_raw_series_request(&request).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("named table scan"),
|
||||
"unexpected rejection cause: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_series_request_rejects_a_plan_that_is_not_just_the_scan() {
|
||||
use datafusion_expr::LogicalPlanBuilder;
|
||||
@@ -3147,6 +3817,29 @@ mod tests {
|
||||
assert!(validate_raw_series_request(&request).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_series_request_rejects_every_inspection_table_name_case_insensitively() {
|
||||
for name in [
|
||||
ManifestSstEntry::reserved_table_name_for_inspection(),
|
||||
StorageSstEntry::reserved_table_name_for_inspection(),
|
||||
PuffinIndexMetaEntry::reserved_table_name_for_inspection(),
|
||||
RegionInfoEntry::reserved_table_name_for_inspection(),
|
||||
] {
|
||||
for candidate in [name.to_string(), name.to_ascii_uppercase()] {
|
||||
let plan = scan_plan(&candidate);
|
||||
let request = query_request(plan.clone(), RegionReadKind::RawSeries);
|
||||
let err = validate_raw_series_request(&request).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("inspection tables"),
|
||||
"{candidate} must be rejected as an inspection table: {err}"
|
||||
);
|
||||
// The identical scan stays a valid ordinary row read.
|
||||
let request = query_request(plan, RegionReadKind::Rows);
|
||||
assert!(validate_raw_series_request(&request).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_series_request_rejects_a_scan_that_already_limits_its_rows() {
|
||||
// A pushed-down fetch cannot be honoured by a frame leaf and is rejected.
|
||||
|
||||
@@ -38,7 +38,7 @@ use crate::region_server::RegionServer;
|
||||
/// These are recognized by reserved table names and mapped to providers.
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Copy)]
|
||||
enum InternalTableKind {
|
||||
pub(crate) enum InternalTableKind {
|
||||
InspectSstManifest,
|
||||
InspectSstStorage,
|
||||
InspectSstIndexMeta,
|
||||
|
||||
@@ -118,6 +118,14 @@ mod tests {
|
||||
batches: Vec<RecordBatch>,
|
||||
fail_after_batches: bool,
|
||||
failed: bool,
|
||||
drops: Option<Arc<std::sync::atomic::AtomicUsize>>,
|
||||
}
|
||||
impl Drop for InputStream {
|
||||
fn drop(&mut self) {
|
||||
if let Some(drops) = &self.drops {
|
||||
drops.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Stream for InputStream {
|
||||
type Item = common_recordbatch::error::Result<RecordBatch>;
|
||||
@@ -158,6 +166,8 @@ mod tests {
|
||||
batches: Vec<Vec<RecordBatch>>,
|
||||
targets: Vec<RegionQueryTarget>,
|
||||
fail_after_batches: bool,
|
||||
drops: Option<Arc<std::sync::atomic::AtomicUsize>>,
|
||||
fail_get_at: Option<usize>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl RegionQueryHandler for Handler {
|
||||
@@ -180,6 +190,7 @@ mod tests {
|
||||
batches: self.batches.clone(),
|
||||
fail_after_batches: false,
|
||||
failed: false,
|
||||
drops: None,
|
||||
}))
|
||||
}
|
||||
async fn handle_remote_dyn_filter_update(
|
||||
@@ -215,6 +226,15 @@ mod tests {
|
||||
) -> crate::error::Result<common_recordbatch::SendableRecordBatchStream> {
|
||||
assert_eq!(request.read_kind, RegionReadKind::RawSeries);
|
||||
let index = request.region_id.region_number() as usize - 1;
|
||||
if self.fail_get_at == Some(index) {
|
||||
return Err(crate::error::Error::QueryPlan {
|
||||
source: BoxedError::new(PlainError::new(
|
||||
"later target acquisition failed".to_string(),
|
||||
common_error::status_code::StatusCode::Unexpected,
|
||||
)),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
let batches = self.batches.get(index).expect("route target has batches");
|
||||
let schema = batches[0].schema.clone();
|
||||
assert_eq!(target, &self.targets[index]);
|
||||
@@ -223,6 +243,7 @@ mod tests {
|
||||
batches: batches.clone(),
|
||||
fail_after_batches: self.fail_after_batches,
|
||||
failed: false,
|
||||
drops: self.drops.clone(),
|
||||
}))
|
||||
}
|
||||
async fn handle_remote_dyn_filter_update(
|
||||
@@ -385,6 +406,16 @@ mod tests {
|
||||
targets: vec![(RegionId::new(1, n), target())],
|
||||
}
|
||||
}
|
||||
fn caused_by(error: &(dyn std::error::Error + 'static), needle: &str) -> bool {
|
||||
let mut current = Some(error);
|
||||
while let Some(error) = current {
|
||||
if error.to_string().contains(needle) {
|
||||
return true;
|
||||
}
|
||||
current = error.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_target_chunks_remain_contiguous_and_ordered() {
|
||||
@@ -414,6 +445,8 @@ mod tests {
|
||||
batches: vec![b, a],
|
||||
targets: targets.clone(),
|
||||
fail_after_batches: false,
|
||||
drops: None,
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
@@ -452,6 +485,57 @@ mod tests {
|
||||
assert_eq!(is_last, vec![false, true, false, true]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn identical_keys_merge_interleaved_timestamps_with_one_final_marker() {
|
||||
let targets = vec![target_with_peer(2), target_with_peer(1)];
|
||||
let handler: crate::region_query::RegionQueryHandlerRef = Arc::new(PerTargetHandler {
|
||||
// Each region closes its own copy of the same key; only the merged view decides which
|
||||
// chunk is globally final.
|
||||
batches: vec![
|
||||
[frame(b"same", &[1], false), frame(b"same", &[3], true)].concat(),
|
||||
[frame(b"same", &[2], false), frame(b"same", &[4], true)].concat(),
|
||||
],
|
||||
targets: targets.clone(),
|
||||
fail_after_batches: false,
|
||||
drops: None,
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
targets: vec![
|
||||
(RegionId::new(1, 1), targets[0].clone()),
|
||||
(RegionId::new(1, 2), targets[1].clone()),
|
||||
],
|
||||
};
|
||||
let table = table::table_name::TableName::new("catalog", "schema", "table");
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let chunks = merged_raw_series(source(&handler, &p, &r, &table, &ctx))
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(chunks.len(), 4);
|
||||
assert!(
|
||||
chunks
|
||||
.iter()
|
||||
.all(|chunk| chunk.primary_key.as_slice() == b"same\0\0")
|
||||
);
|
||||
let samples: Vec<(i64, f64)> = chunks
|
||||
.iter()
|
||||
.map(|chunk| {
|
||||
let value = match chunk.fields.get(0).unwrap().sample(0) {
|
||||
datatypes::series::samples::SampleRef::Float(value) => value,
|
||||
_ => panic!("expected float sample"),
|
||||
};
|
||||
(chunk.time.timestamp(0).unwrap(), value)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(samples, vec![(1, 1.0), (2, 2.0), (3, 3.0), (4, 4.0)]);
|
||||
assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1);
|
||||
assert!(chunks.last().unwrap().is_last);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stream_error_after_a_batch_propagates() {
|
||||
let target = target_with_peer(7);
|
||||
@@ -459,6 +543,8 @@ mod tests {
|
||||
batches: vec![frame(b"a", &[1], false)],
|
||||
targets: vec![target.clone()],
|
||||
fail_after_batches: true,
|
||||
drops: None,
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
@@ -482,6 +568,139 @@ mod tests {
|
||||
panic!("original stream error was not preserved: {error}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn truncated_non_final_stream_is_rejected() {
|
||||
let target = target_with_peer(1);
|
||||
let handler: crate::region_query::RegionQueryHandlerRef = Arc::new(PerTargetHandler {
|
||||
// The fixture ends naturally after a chunk that is not final for its key.
|
||||
batches: vec![frame(b"a", &[1], false)],
|
||||
targets: vec![target.clone()],
|
||||
fail_after_batches: false,
|
||||
drops: None,
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
targets: vec![(RegionId::new(1, 1), target)],
|
||||
};
|
||||
let table = table::table_name::TableName::new("catalog", "schema", "table");
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let error = merged_raw_series(source(&handler, &p, &r, &table, &ctx))
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.expect_err("EOF before the final marker must be rejected");
|
||||
assert!(
|
||||
caused_by(&error, "raw series stream ended before key was final"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rows_schema_is_rejected() {
|
||||
let target = target_with_peer(1);
|
||||
let rows = ArrowSchema::new(vec![
|
||||
Field::new("ts", DataType::Int64, false),
|
||||
Field::new("value", DataType::Float64, true),
|
||||
]);
|
||||
let batch = RecordBatch::new_empty(Arc::new(Schema::try_from(rows).unwrap()));
|
||||
let handler: crate::region_query::RegionQueryHandlerRef = Arc::new(PerTargetHandler {
|
||||
batches: vec![vec![batch]],
|
||||
targets: vec![target.clone()],
|
||||
fail_after_batches: false,
|
||||
drops: None,
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
targets: vec![(RegionId::new(1, 1), target)],
|
||||
};
|
||||
let table = table::table_name::TableName::new("catalog", "schema", "table");
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let error = merged_raw_series(source(&handler, &p, &r, &table, &ctx))
|
||||
.await
|
||||
.err()
|
||||
.expect("a Rows schema is not a raw series frame");
|
||||
assert!(
|
||||
caused_by(&error, "raw frame schema declares no known label mode"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_consumer_drops_all_acquired_streams() {
|
||||
let targets = vec![target_with_peer(1), target_with_peer(2)];
|
||||
let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let handler: crate::region_query::RegionQueryHandlerRef = Arc::new(PerTargetHandler {
|
||||
// Every target has a second key still queued, so both acquired streams are live when
|
||||
// the consumer stops after the first output.
|
||||
batches: vec![
|
||||
[frame(b"a", &[1], true), frame(b"c", &[1], true)].concat(),
|
||||
[frame(b"b", &[1], true), frame(b"d", &[1], true)].concat(),
|
||||
],
|
||||
targets: targets.clone(),
|
||||
fail_after_batches: false,
|
||||
drops: Some(drops.clone()),
|
||||
fail_get_at: None,
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
targets: vec![
|
||||
(RegionId::new(1, 1), targets[0].clone()),
|
||||
(RegionId::new(1, 2), targets[1].clone()),
|
||||
],
|
||||
};
|
||||
let table = table::table_name::TableName::new("catalog", "schema", "table");
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let mut stream = merged_raw_series(source(&handler, &p, &r, &table, &ctx))
|
||||
.await
|
||||
.unwrap();
|
||||
let first = stream.try_next().await.unwrap().expect("first chunk");
|
||||
assert_eq!(first.primary_key.as_slice(), b"a\0\0");
|
||||
assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 0);
|
||||
drop(stream);
|
||||
assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_acquisition_error_drops_prior_stream_and_is_preserved() {
|
||||
let targets = vec![target_with_peer(1), target_with_peer(2)];
|
||||
let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let handler: crate::region_query::RegionQueryHandlerRef = Arc::new(PerTargetHandler {
|
||||
batches: vec![
|
||||
[frame(b"a", &[1], true), frame(b"c", &[1], true)].concat(),
|
||||
[frame(b"b", &[1], true), frame(b"d", &[1], true)].concat(),
|
||||
],
|
||||
targets: targets.clone(),
|
||||
fail_after_batches: false,
|
||||
drops: Some(drops.clone()),
|
||||
fail_get_at: Some(1),
|
||||
});
|
||||
let p = plan();
|
||||
let r = CaptureNativeRawRoute {
|
||||
targets: vec![
|
||||
(RegionId::new(1, 1), targets[0].clone()),
|
||||
(RegionId::new(1, 2), targets[1].clone()),
|
||||
],
|
||||
};
|
||||
let table = table::table_name::TableName::new("catalog", "schema", "table");
|
||||
let ctx = session::context::QueryContext::arc();
|
||||
let error = merged_raw_series(source(&handler, &p, &r, &table, &ctx))
|
||||
.await
|
||||
.err()
|
||||
.expect("second do_get must fail");
|
||||
assert!(
|
||||
matches!(&error, crate::error::Error::QueryPlan { .. }),
|
||||
"original acquisition error must not be replaced: {error}"
|
||||
);
|
||||
assert!(
|
||||
caused_by(&error, "later target acquisition failed"),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_plan_that_is_not_a_bare_scan_is_rejected() {
|
||||
let handler: crate::region_query::RegionQueryHandlerRef =
|
||||
|
||||
+334
-82
@@ -143,6 +143,7 @@ impl ExecutionPlan for MergedSeriesScanExec {
|
||||
Ok(self)
|
||||
}
|
||||
fn reset_state(self: Arc<Self>) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
|
||||
self.input.clone().reset_state()?;
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -431,20 +432,9 @@ impl DummyTableProvider {
|
||||
/// cannot be split: there is no scanner to prepare before this point, and the leaf refuses an
|
||||
/// unprepared scan because its label binding resolves against prepared partition ranges.
|
||||
///
|
||||
/// **The single partition below is a limit of the named binding, not of the raw frame.** The
|
||||
/// conversion this leaf uses resolves authorized logical names against the prepared scanner, and
|
||||
/// that resolution declines any scan whose partition count is not exactly one
|
||||
/// (`resolve_named_series_binding` in `table::table::scan`). A frame stream is described
|
||||
/// per-series and needs no such reduction.
|
||||
///
|
||||
/// The alternative that would keep several partitions is [`RegionScanExec::try_to_series_scan`],
|
||||
/// which takes a [`RawLabelSource`] built here instead of resolving names. It cannot be used
|
||||
/// from this layer today: a scanner accepts that source only when its `physical_metadata` is
|
||||
/// the scanner's own snapshot by `Arc` identity, and this provider holds the metadata of the
|
||||
/// region engine, not the snapshot the acquired scanner bound — the named path exists to bridge
|
||||
/// exactly that gap, by binding against the scanner. So relaxing this needs a scanner-side
|
||||
/// binding, not a different call here; preparing more partitions here would only make the
|
||||
/// conversion decline, and the target stays one partition until then.
|
||||
/// The prepared scan retains its N assigned partitions. The named raw-series conversion binds
|
||||
/// against the scanner's metadata snapshot, and [`MergedSeriesScanExec`] restores ordered raw
|
||||
/// series at the single-stream region-read boundary.
|
||||
///
|
||||
/// This read asked for frames and is answered with frames or with an error naming why it could
|
||||
/// not be: it never silently receives rows. Answering with rows would be a different answer to
|
||||
@@ -498,8 +488,8 @@ impl DummyTableProvider {
|
||||
DataFusionError::NotImplemented(format!(
|
||||
"region {region_id} cannot answer a raw series request for metric \
|
||||
`{metric_name}`: engine `{}` declined to serve raw series from the prepared \
|
||||
scan (raw series unsupported, an unprepared or multi-partition scan, dynamic \
|
||||
filters, or requested names that do not bind)",
|
||||
scan (raw series unsupported, dynamic filters, or requested names that do not \
|
||||
bind)",
|
||||
self.engine.name(),
|
||||
))
|
||||
})?;
|
||||
@@ -1407,11 +1397,12 @@ mod tests {
|
||||
|
||||
// ---- raw series leaf selection ----
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use common_error::ext::{BoxedError, PlainError};
|
||||
use common_query::series_frame::{label_decode_spec, unpack_raw_series};
|
||||
use datafusion::execution::SessionStateBuilder;
|
||||
use datafusion::execution::context::TaskContext;
|
||||
use datafusion::execution::context::{SessionConfig, TaskContext};
|
||||
use datafusion::physical_plan::ExecutionPlanProperties;
|
||||
use datafusion::physical_plan::execution_plan::reset_plan_states;
|
||||
use datatypes::arrow::array::Float64Array;
|
||||
use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
@@ -1419,7 +1410,7 @@ mod tests {
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::frame::LabelDecodeSpec;
|
||||
use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
|
||||
use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema};
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, Samples, SeriesFields, SeriesSchema};
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RawSeriesStream,
|
||||
@@ -1442,6 +1433,12 @@ mod tests {
|
||||
Arc<Mutex<Vec<Option<TimeSeriesDistribution>>>>,
|
||||
);
|
||||
|
||||
/// Scripted raw-series chunks not yet yielded or released by the scan streams.
|
||||
type PendingChunks = Arc<Mutex<usize>>;
|
||||
|
||||
/// Suspends a scripted scan stream, once it has yielded this many chunks, until it is cleared.
|
||||
type PauseAfterChunks = Arc<Mutex<Option<usize>>>;
|
||||
|
||||
/// A region whose scan either can or cannot serve raw series frames.
|
||||
///
|
||||
/// The engine reports the metadata and hands out one scanner; whether that scanner has a raw
|
||||
@@ -1452,17 +1449,30 @@ mod tests {
|
||||
distributions: Arc<Mutex<Vec<Option<TimeSeriesDistribution>>>>,
|
||||
prepares: Arc<Mutex<Vec<usize>>>,
|
||||
partition_chunks: Arc<Vec<Vec<RawSeriesChunk>>>,
|
||||
pending: PendingChunks,
|
||||
pause_after: PauseAfterChunks,
|
||||
}
|
||||
|
||||
impl FrameRegionEngine {
|
||||
/// The engine as a test builds it, with the chunks each scan partition emits.
|
||||
fn with_partition_chunks(
|
||||
serves_frames: bool,
|
||||
///
|
||||
/// The returned counter holds the scripted chunks owned by live scan streams; it is zero
|
||||
/// when every stream has yielded or released its chunks. The returned pause handle
|
||||
/// suspends every scan stream once it has yielded the configured number of chunks.
|
||||
fn with_scripted_chunks(
|
||||
partition_chunks: Vec<Vec<RawSeriesChunk>>,
|
||||
) -> FrameRegionSetup {
|
||||
let (mut engine, metadata, prepares, distributions) = Self::new(serves_frames);
|
||||
) -> (FrameRegionSetup, PendingChunks, PauseAfterChunks) {
|
||||
let (mut engine, metadata, prepares, distributions) = Self::new(true);
|
||||
let pending = Arc::new(Mutex::new(0));
|
||||
let pause_after = Arc::new(Mutex::new(None));
|
||||
engine.partition_chunks = Arc::new(partition_chunks);
|
||||
(engine, metadata, prepares, distributions)
|
||||
engine.pending = pending.clone();
|
||||
engine.pause_after = pause_after.clone();
|
||||
(
|
||||
(engine, metadata, prepares, distributions),
|
||||
pending,
|
||||
pause_after,
|
||||
)
|
||||
}
|
||||
|
||||
fn new(serves_frames: bool) -> FrameRegionSetup {
|
||||
@@ -1476,6 +1486,8 @@ mod tests {
|
||||
distributions: distributions.clone(),
|
||||
prepares: prepares.clone(),
|
||||
partition_chunks: Arc::new(Vec::new()),
|
||||
pending: Arc::new(Mutex::new(0)),
|
||||
pause_after: Arc::new(Mutex::new(None)),
|
||||
},
|
||||
metadata,
|
||||
prepares,
|
||||
@@ -1569,6 +1581,9 @@ mod tests {
|
||||
prepares: Arc<Mutex<Vec<usize>>>,
|
||||
/// Chunks each scan partition emits, indexed by partition. Empty unless a test scripts it.
|
||||
partition_chunks: Arc<Vec<Vec<RawSeriesChunk>>>,
|
||||
executed_partitions: Arc<Mutex<Vec<bool>>>,
|
||||
pending: PendingChunks,
|
||||
pause_after: PauseAfterChunks,
|
||||
}
|
||||
|
||||
impl datafusion::physical_plan::DisplayAs for FrameScanner {
|
||||
@@ -1640,18 +1655,37 @@ mod tests {
|
||||
partition: usize,
|
||||
label_source: &RawLabelSource,
|
||||
) -> RegionResult<Option<SendableRawSeriesStream>> {
|
||||
Ok(Some(Box::pin(EmptyRawStream {
|
||||
{
|
||||
let mut executed = self.executed_partitions.lock().unwrap();
|
||||
if executed[partition] {
|
||||
return Err(BoxedError::new(PlainError::new(
|
||||
"partition executed twice without reset".to_string(),
|
||||
common_error::status_code::StatusCode::Unexpected,
|
||||
)));
|
||||
}
|
||||
executed[partition] = true;
|
||||
}
|
||||
let chunks = self
|
||||
.partition_chunks
|
||||
.get(partition)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
*self.pending.lock().unwrap() += chunks.len();
|
||||
Ok(Some(Box::pin(ScriptedRawStream {
|
||||
schema: frame_series_schema(&self.metadata, self.projection.as_ref()),
|
||||
source: label_source.clone(),
|
||||
decode: label_decode_spec(label_source),
|
||||
chunks: self
|
||||
.partition_chunks
|
||||
.get(partition)
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
chunks,
|
||||
yielded: 0,
|
||||
pending: self.pending.clone(),
|
||||
pause_after: self.pause_after.clone(),
|
||||
})))
|
||||
}
|
||||
|
||||
fn reset_state(&mut self) {
|
||||
self.executed_partitions.lock().unwrap().fill(false);
|
||||
}
|
||||
|
||||
fn has_predicate_without_region(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -1668,15 +1702,20 @@ mod tests {
|
||||
fn set_query_load_region_id(&mut self, _region_id: RegionId) {}
|
||||
}
|
||||
|
||||
/// A raw stream with no chunks that declares the same binding the scanner was asked for.
|
||||
struct EmptyRawStream {
|
||||
/// A raw stream over the chunks scripted for its scan partition.
|
||||
struct ScriptedRawStream {
|
||||
schema: Arc<SeriesSchema>,
|
||||
source: RawLabelSource,
|
||||
decode: Option<LabelDecodeSpec>,
|
||||
chunks: Vec<RawSeriesChunk>,
|
||||
yielded: usize,
|
||||
pending: PendingChunks,
|
||||
/// When set, poll suspends after that many chunks without waking, so the remaining chunks
|
||||
/// stay owned by the stream and a consumer can cancel it mid-scan.
|
||||
pause_after: PauseAfterChunks,
|
||||
}
|
||||
|
||||
impl RawSeriesStream for EmptyRawStream {
|
||||
impl RawSeriesStream for ScriptedRawStream {
|
||||
fn schema(&self) -> &Arc<SeriesSchema> {
|
||||
&self.schema
|
||||
}
|
||||
@@ -1694,7 +1733,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
impl futures::Stream for EmptyRawStream {
|
||||
impl futures::Stream for ScriptedRawStream {
|
||||
type Item = RegionResult<RawSeriesChunk>;
|
||||
|
||||
fn poll_next(
|
||||
@@ -1702,14 +1741,26 @@ mod tests {
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Option<Self::Item>> {
|
||||
let this = self.as_mut().get_mut();
|
||||
if !this.chunks.is_empty() && *this.pause_after.lock().unwrap() == Some(this.yielded) {
|
||||
return std::task::Poll::Pending;
|
||||
}
|
||||
if this.chunks.is_empty() {
|
||||
std::task::Poll::Ready(None)
|
||||
} else {
|
||||
this.yielded += 1;
|
||||
*this.pending.lock().unwrap() -= 1;
|
||||
std::task::Poll::Ready(Some(Ok(this.chunks.remove(0))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScriptedRawStream {
|
||||
fn drop(&mut self) {
|
||||
*self.pending.lock().unwrap() -= self.chunks.len();
|
||||
self.chunks.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RegionEngine for FrameRegionEngine {
|
||||
fn name(&self) -> &str {
|
||||
@@ -1741,6 +1792,12 @@ mod tests {
|
||||
&& request.distribution == Some(TimeSeriesDistribution::PerSeries),
|
||||
prepares: self.prepares.clone(),
|
||||
partition_chunks: self.partition_chunks.clone(),
|
||||
executed_partitions: Arc::new(Mutex::new(vec![
|
||||
false;
|
||||
frame_partition_ranges().len()
|
||||
])),
|
||||
pending: self.pending.clone(),
|
||||
pause_after: self.pause_after.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1828,6 +1885,29 @@ mod tests {
|
||||
(provider, prepares, distributions)
|
||||
}
|
||||
|
||||
/// Answers a frame read from a region whose scan streams are scripted.
|
||||
async fn scripted_plan(engine: FrameRegionEngine) -> Arc<dyn ExecutionPlan> {
|
||||
let provider = DummyTableProviderFactory
|
||||
.create_table_provider(
|
||||
RegionId::new(2048, 1),
|
||||
Arc::new(engine) as RegionEngineRef,
|
||||
Some(Arc::new(
|
||||
QueryContextBuilder::default()
|
||||
.extensions(HashMap::from([(
|
||||
RAW_SERIES_READ_EXTENSION_KEY.to_string(),
|
||||
"cpu_usage".to_string(),
|
||||
)]))
|
||||
.build(),
|
||||
)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
provider
|
||||
.scan(&test_session(), Some(&vec![2]), &[], None)
|
||||
.await
|
||||
.expect("an eligible region answers a frame read")
|
||||
}
|
||||
|
||||
fn frame_partition_ranges() -> Vec<Vec<PartitionRange>> {
|
||||
(0..3)
|
||||
.map(|i| {
|
||||
@@ -1856,7 +1936,9 @@ mod tests {
|
||||
}
|
||||
|
||||
fn test_session() -> datafusion::execution::SessionState {
|
||||
SessionStateBuilder::new().build()
|
||||
SessionStateBuilder::new()
|
||||
.with_config(SessionConfig::new().with_target_partitions(3))
|
||||
.build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1986,60 +2068,83 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The keys and closing flags of a packed frame stream, in the order it emits them.
|
||||
async fn frame_keys(plan: &Arc<dyn ExecutionPlan>) -> Vec<(Vec<u8>, bool)> {
|
||||
/// Drains a plan's packed frame stream into the raw-series chunks it carries.
|
||||
async fn frame_chunks(plan: &Arc<dyn ExecutionPlan>) -> Vec<RawSeriesChunk> {
|
||||
let context = Arc::new(TaskContext::default());
|
||||
let stream = plan.execute(0, context).unwrap();
|
||||
let unpacked = unpack_raw_series(stream, None).unwrap();
|
||||
let chunks = futures_util::TryStreamExt::try_collect::<Vec<_>>(unpacked)
|
||||
let unpacked = unpack_raw_series(plan.execute(0, context).unwrap(), None).unwrap();
|
||||
futures_util::TryStreamExt::try_collect::<Vec<_>>(unpacked)
|
||||
.await
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Joins an error and its sources, so an assertion can see a cause a consumer wrapped.
|
||||
fn error_chain(error: &dyn std::error::Error) -> String {
|
||||
let mut chain = vec![error.to_string()];
|
||||
let mut source = error.source();
|
||||
while let Some(error) = source {
|
||||
chain.push(error.to_string());
|
||||
source = error.source();
|
||||
}
|
||||
chain.join(": ")
|
||||
}
|
||||
|
||||
/// The complete payload of a raw-series stream: key, times, float samples and finality.
|
||||
fn frame_snapshot(chunks: &[RawSeriesChunk]) -> Vec<(Vec<u8>, Vec<i64>, Vec<f64>, bool)> {
|
||||
chunks
|
||||
.into_iter()
|
||||
.map(|chunk| (chunk.primary_key.to_vec(), chunk.is_last))
|
||||
.iter()
|
||||
.map(|chunk| {
|
||||
(
|
||||
chunk.primary_key.to_vec(),
|
||||
chunk.time.as_buffer().to_vec(),
|
||||
chunk
|
||||
.fields
|
||||
.get(0)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|sample| match sample {
|
||||
SampleRef::Float(value) => value,
|
||||
_ => panic!("the fixture stores float samples"),
|
||||
})
|
||||
.collect(),
|
||||
chunk.is_last,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Partitions that would interleave if simply concatenated are merged into one ordered stream.
|
||||
///
|
||||
/// Every partition is itself well formed: within it a series is closed before the next key
|
||||
/// starts, which is what `unpack_raw_series` requires of one stream. Partition 0 carries
|
||||
/// `a` in two chunks and then `c`; partition 1 carries `b`. Concatenating the partitions gives
|
||||
/// `a, a, c, b`, which breaks the `KeyThenTime` contract every raw-series consumer requires.
|
||||
/// The single region-read stream must instead be `a, a, b, c`, keeping `a`'s two chunks
|
||||
/// adjacent.
|
||||
/// starts, which is what `unpack_raw_series` requires of one stream. The encoded key `a` is
|
||||
/// split across partitions 0 and 1 with interleaved times and closed by both of them,
|
||||
/// partition 0 also carries `c`, and partition 1 also carries `b`. Concatenating the
|
||||
/// partitions gives `a, a, c, a, a, b`, which breaks the `KeyThenTime` contract every
|
||||
/// raw-series consumer requires. The single region-read stream must instead be
|
||||
/// `a@10, a@11, a@12, a@15, b@25, c@20`, keeping `a`'s chunks adjacent and closing it exactly
|
||||
/// once across both partitions.
|
||||
///
|
||||
/// The same plan then replays: an execution without a reset fails, a reset reproduces the
|
||||
/// complete payload, and a partially consumed stream that is dropped and reset reproduces it
|
||||
/// again. For the cancellation the fixture suspends its streams after two chunks without
|
||||
/// waking, so the dropped stream still owns undrained chunks when it is cancelled.
|
||||
#[tokio::test]
|
||||
async fn raw_series_partitions_merge_into_one_ordered_stream() {
|
||||
let region_id = RegionId::new(2048, 1);
|
||||
let chunks = vec![
|
||||
vec![
|
||||
frame_chunk(&[10], b"a", false),
|
||||
frame_chunk(&[11], b"a", true),
|
||||
frame_chunk(&[12], b"a", true),
|
||||
frame_chunk(&[20], b"c", true),
|
||||
],
|
||||
vec![frame_chunk(&[15], b"b", true)],
|
||||
vec![
|
||||
frame_chunk(&[11], b"a", false),
|
||||
frame_chunk(&[15], b"a", true),
|
||||
frame_chunk(&[25], b"b", true),
|
||||
],
|
||||
Vec::new(),
|
||||
];
|
||||
let (engine, _, _, _) = FrameRegionEngine::with_partition_chunks(true, chunks);
|
||||
let mut builder = QueryContextBuilder::default();
|
||||
builder = builder.extensions(HashMap::from([(
|
||||
RAW_SERIES_READ_EXTENSION_KEY.to_string(),
|
||||
"cpu_usage".to_string(),
|
||||
)]));
|
||||
let provider = DummyTableProviderFactory
|
||||
.create_table_provider(
|
||||
region_id,
|
||||
Arc::new(engine) as RegionEngineRef,
|
||||
Some(Arc::new(builder.build())),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = test_session();
|
||||
|
||||
let plan = provider
|
||||
.scan(&state, Some(&vec![2]), &[], None)
|
||||
.await
|
||||
.expect("an eligible region answers a frame read");
|
||||
let ((engine, _, _, _), pending, pause_after) =
|
||||
FrameRegionEngine::with_scripted_chunks(chunks);
|
||||
let plan = scripted_plan(engine).await;
|
||||
// The scan keeps its three partitions; the region-read boundary sees one.
|
||||
assert_eq!(
|
||||
plan.downcast_ref::<MergedSeriesScanExec>()
|
||||
@@ -2052,18 +2157,165 @@ mod tests {
|
||||
);
|
||||
assert_eq!(plan.output_partitioning().partition_count(), 1);
|
||||
|
||||
// The key bytes are the encoded primary key the fixture wrote (`key` + two padding
|
||||
// bytes), so compare the leading byte rather than the whole buffer.
|
||||
let emitted = frame_keys(&plan).await;
|
||||
let shape = emitted
|
||||
.iter()
|
||||
.map(|(key, last)| (key[0], *last))
|
||||
.collect::<Vec<_>>();
|
||||
let first = frame_snapshot(&frame_chunks(&plan).await);
|
||||
let expected = vec![
|
||||
(b"a\0\0".to_vec(), vec![10], vec![10.0], false),
|
||||
(b"a\0\0".to_vec(), vec![11], vec![11.0], false),
|
||||
(b"a\0\0".to_vec(), vec![12], vec![12.0], false),
|
||||
(b"a\0\0".to_vec(), vec![15], vec![15.0], true),
|
||||
(b"b\0\0".to_vec(), vec![25], vec![25.0], true),
|
||||
(b"c\0\0".to_vec(), vec![20], vec![20.0], true),
|
||||
];
|
||||
assert_eq!(
|
||||
shape,
|
||||
vec![(b'a', false), (b'a', true), (b'b', true), (b'c', true)],
|
||||
"the merged stream must be key ordered, keep each series' chunks adjacent, and close \
|
||||
every series exactly once: {emitted:?}"
|
||||
first, expected,
|
||||
"the merged stream must be ordered by key then time, keep each series' chunks \
|
||||
adjacent, and close every series exactly once"
|
||||
);
|
||||
// A scan that has ended is not replayable until it is reset: the hidden scanner refuses.
|
||||
let error = match plan.execute(0, task_context()) {
|
||||
Ok(_) => panic!("an unreset scan must not execute again"),
|
||||
Err(error) => error.to_string(),
|
||||
};
|
||||
assert!(
|
||||
error.contains("partition executed twice without reset"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
// Resetting the wrapper resets the scan it hides, so the whole stream replays.
|
||||
let replay = reset_plan_states(plan.clone()).unwrap();
|
||||
assert_eq!(frame_snapshot(&frame_chunks(&replay).await), first);
|
||||
|
||||
// A cancelled stream is dropped while the source still owns chunks, and the reset plan
|
||||
// replays the complete payload afterwards.
|
||||
*pause_after.lock().unwrap() = Some(2);
|
||||
let cancelled = reset_plan_states(replay).unwrap();
|
||||
let mut partial =
|
||||
unpack_raw_series(cancelled.execute(0, task_context()).unwrap(), None).unwrap();
|
||||
assert!(
|
||||
futures_util::TryStreamExt::try_next(&mut partial)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some(),
|
||||
"the cancelled stream must emit a chunk before cancellation"
|
||||
);
|
||||
let held = *pending.lock().unwrap();
|
||||
assert!(
|
||||
held > 0,
|
||||
"the paused stream still owns {held} undrained chunks"
|
||||
);
|
||||
drop(partial);
|
||||
assert_eq!(
|
||||
*pending.lock().unwrap(),
|
||||
0,
|
||||
"dropping the cancelled stream releases the rest of the source"
|
||||
);
|
||||
*pause_after.lock().unwrap() = None;
|
||||
let after_cancel = reset_plan_states(cancelled).unwrap();
|
||||
assert_eq!(frame_snapshot(&frame_chunks(&after_cancel).await), first);
|
||||
}
|
||||
|
||||
/// A failure acquiring a later partition releases the partition already acquired.
|
||||
///
|
||||
/// The wrapper acquires partitions in order, so a partition spent before it runs fails the
|
||||
/// read after an earlier partition was acquired. The acquired stream must be released with
|
||||
/// its chunks, the scan must stay one-shot until it is reset, and the reset plan must replay
|
||||
/// the complete payload from both partitions.
|
||||
#[tokio::test]
|
||||
async fn raw_series_later_partition_failure_releases_the_acquired_partition() {
|
||||
let chunks = vec![
|
||||
vec![frame_chunk(&[10], b"a", true)],
|
||||
vec![frame_chunk(&[20], b"b", true)],
|
||||
Vec::new(),
|
||||
];
|
||||
let ((engine, _, _, _), pending, _) = FrameRegionEngine::with_scripted_chunks(chunks);
|
||||
let plan = scripted_plan(engine).await;
|
||||
let input = plan
|
||||
.downcast_ref::<MergedSeriesScanExec>()
|
||||
.unwrap()
|
||||
.input
|
||||
.clone();
|
||||
|
||||
// Spend partition 1's single acquisition before the wrapper asks for it, then release it.
|
||||
drop(input.execute(1, task_context()).unwrap());
|
||||
assert_eq!(*pending.lock().unwrap(), 0);
|
||||
|
||||
let error = match plan.execute(0, task_context()) {
|
||||
Ok(_) => panic!("a partition spent before the wrapper runs must fail the read"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error_chain(&error).contains("partition executed twice without reset"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
*pending.lock().unwrap(),
|
||||
0,
|
||||
"the partition acquired before the failure must release its chunks"
|
||||
);
|
||||
// Partition 0 was really acquired: the scan refuses it instead of it never having run.
|
||||
let error = match input.execute(0, task_context()) {
|
||||
Ok(_) => panic!("the failed execution must have acquired partition 0"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error_chain(&error).contains("partition executed twice without reset"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
// Resetting the wrapper recovers the whole stream, including both partitions.
|
||||
let replay = reset_plan_states(plan).unwrap();
|
||||
assert_eq!(
|
||||
frame_snapshot(&frame_chunks(&replay).await),
|
||||
vec![
|
||||
(b"a\0\0".to_vec(), vec![10], vec![10.0], true),
|
||||
(b"b\0\0".to_vec(), vec![20], vec![20.0], true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A partition that ends before its final chunk fails the read and releases the rest.
|
||||
///
|
||||
/// Partition 1's series `b` never closes, so the partition's own packing rejects the truncated
|
||||
/// stream at EOF before the merge can judge it. Partition 0 is suspended after two chunks, so
|
||||
/// it still owns `d` when that error arrives: the failed read must release the chunk it never
|
||||
/// consumed rather than leave it behind in the scanner. The read is not claimed to be empty
|
||||
/// before the error, only to fail and to own nothing afterwards.
|
||||
#[tokio::test]
|
||||
async fn raw_series_truncated_partition_fails_and_releases_the_stream() {
|
||||
let chunks = vec![
|
||||
vec![
|
||||
frame_chunk(&[10], b"a", true),
|
||||
frame_chunk(&[30], b"c", true),
|
||||
frame_chunk(&[40], b"d", true),
|
||||
],
|
||||
vec![frame_chunk(&[20], b"b", false)],
|
||||
Vec::new(),
|
||||
];
|
||||
let ((engine, _, _, _), pending, pause_after) =
|
||||
FrameRegionEngine::with_scripted_chunks(chunks);
|
||||
let plan = scripted_plan(engine).await;
|
||||
assert_eq!(*pending.lock().unwrap(), 0, "nothing is acquired yet");
|
||||
|
||||
// Partition 0 yields `a` and `c`, then suspends while it still owns `d`; partition 1's
|
||||
// single open chunk is not held back, so its EOF reaches the read.
|
||||
*pause_after.lock().unwrap() = Some(2);
|
||||
let unpacked = unpack_raw_series(plan.execute(0, task_context()).unwrap(), None).unwrap();
|
||||
assert!(
|
||||
*pending.lock().unwrap() > 0,
|
||||
"the read must acquire partition 0's remaining chunks"
|
||||
);
|
||||
let error = match futures_util::TryStreamExt::try_collect::<Vec<_>>(unpacked).await {
|
||||
Ok(_) => panic!("a partition that ends before its final chunk must fail the read"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error_chain(&error).contains("raw series stream ended before key was final"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
*pending.lock().unwrap(),
|
||||
0,
|
||||
"the failed read must release the chunk it never consumed"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user