Files
greptimedb/src/mito2/src/engine/scan_test.rs
T
discord9 26508dcada fix(mito2): key a range-cache entry by the creator slices it was read under
A physical-sequence read selects rows by each creator piece's cursor and
until, but the range-cache fingerprint carried only the region-level
range, so a result built under one set of piece cursors was replayed
under another: rows the new range requires were omitted and rows above
its until were returned. Put the per-file candidate slices (identity,
cursor, until) and read_row_sequence into the key; a slice set that
cannot be stated makes the range uncacheable instead of caching under an
incomplete key.

Also take the least cursor among every candidate that selects a row,
where the SST path took the first match: a row a lower-cursor piece also
claims must be delivered, as the memtable and bulk paths already do.

Signed-off-by: discord9 <discord9@163.com>
2026-11-26 16:22:25 +08:00

10863 lines
395 KiB
Rust

// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::time::Duration;
use api::helper::encode_json_value;
use api::v1::helper::row;
use api::v1::region::{StrictWindow, compact_request};
use api::v1::value::ValueData;
use api::v1::{ArrowIpc, ColumnDataType, Rows, SemanticType, WriteHint};
use arrow_schema::extension::ExtensionType;
use common_base::readable_size::ReadableSize;
use common_error::ext::{ErrorExt, WhateverResult};
use common_error::status_code::StatusCode;
use common_recordbatch::{DfRecordBatch, RecordBatches};
use common_test_util::flight::encode_to_flight_data;
use common_time::Timestamp;
use datafusion::physical_plan::VerboseDisplay;
use datafusion::physical_plan::expressions::{
BinaryExpr, Column, DynamicFilterPhysicalExpr, lit as physical_lit,
};
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion_common::ScalarValue;
use datafusion_expr::{Operator, col, lit};
use datatypes::arrow::array::{
ArrayRef, AsArray, Float64Array, StringArray, TimestampMillisecondArray,
};
use datatypes::arrow::datatypes::{
DataType, Field, Float64Type, Schema, TimeUnit, TimestampMillisecondType, UInt32Type,
UInt64Type,
};
use datatypes::extension::json::{Json2ExtensionType, JsonMetadata};
use datatypes::json::JsonSettings;
use datatypes::json::value::JsonValue;
use datatypes::prelude::ConcreteDataType;
use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
use datatypes::vectors::json::array::JsonArray;
use futures::TryStreamExt;
use futures::future::try_join_all;
use serde_json::json;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metric_engine_consts::PRIMARY_KEY_ENCODING;
use store_api::region_engine::{PrepareRequest, RegionEngine, RegionScanner};
use store_api::region_request::{
AlterKind, RegionAlterRequest, RegionBulkInsertsRequest, RegionCompactRequest,
RegionOpenRequest, RegionPutRequest, RegionRequest, SetRegionOption,
};
use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
use store_api::storage::{
CursorShard, FileId, RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector,
};
use crate::config::MitoConfig;
use crate::error::Error;
use crate::manifest::action::RegionEdit;
use crate::read::read_columns::ReadColumns;
use crate::read::scan_region::Scanner;
use crate::sst::file::{FileHandle, FileMeta};
use crate::test_util;
use crate::test_util::batch_util::sort_batches_and_print;
use crate::test_util::sst_util::{new_sparse_primary_key, sst_region_metadata_with_encoding};
use crate::test_util::{CreateRequestBuilder, TestEnv, reopen_region};
#[tokio::test]
async fn test_sparse_upsert_after_adding_nullable_tag() -> WhateverResult<()> {
use datatypes::schema::ColumnSchema;
use store_api::metadata::ColumnMetadata;
use store_api::region_request::AddColumn;
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
let mut request = CreateRequestBuilder::new()
.tag_num(1)
.field_num(1)
.insert_option("primary_key_encoding", "sparse")
.build();
let reserved = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse);
request
.column_metadatas
.extend(reserved.column_metadatas.into_iter().take(2));
request
.primary_key
.splice(0..0, reserved.primary_key.into_iter().take(2));
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
let mut rows = Rows {
schema,
rows: vec![row(vec![
ValueData::StringValue("api".into()),
ValueData::F64Value(1.0),
ValueData::TimestampMillisecondValue(1000),
ValueData::U32Value(42),
ValueData::U64Value(7),
])],
};
test_util::put_rows(&engine, region_id, rows.clone()).await;
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::AddColumns {
columns: vec![AddColumn {
column_metadata: ColumnMetadata {
column_schema: ColumnSchema::new(
"zone",
ConcreteDataType::string_datatype(),
true,
),
semantic_type: SemanticType::Tag,
column_id: 3,
},
location: None,
}],
},
}),
)
.await?;
// The old SST and the new write must still identify the same series before compaction.
rows.rows[0].values[1].value_data = Some(ValueData::F64Value(2.0));
test_util::put_rows(&engine, region_id, rows).await;
for flush in [false, true] {
if flush {
test_util::flush_region(&engine, region_id, None).await;
}
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
projection: Some(vec![0, 1, 2, 5]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(stream).await?;
let expected = "\
+-------+---------+---------------------+------+
| tag_0 | field_0 | ts | zone |
+-------+---------+---------------------+------+
| api | 2.0 | 1970-01-01T00:00:01 | |
+-------+---------+---------------------+------+";
assert_eq!(batches.pretty_print()?, expected);
}
engine.stop().await?;
Ok(())
}
#[tokio::test]
async fn test_exemplar_sparse_storage_lifecycle() -> WhateverResult<()> {
use datatypes::schema::ColumnSchema;
use store_api::metadata::ColumnMetadata;
use store_api::region_request::AddColumn;
use store_api::storage::consts::ReservedColumnId;
for default_flat_format in [false, true] {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format,
..Default::default()
})
.await;
let region_id = RegionId::new(1024, 0);
let mut request = CreateRequestBuilder::new()
.tag_num(2)
.field_num(2)
.insert_option("primary_key_encoding", "sparse")
.insert_option("append_mode", "true")
.insert_option("sst_format", "primary_key")
.build();
request.column_metadatas[3].column_schema.data_type =
ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
request.column_metadatas[3]
.column_schema
.with_extension_type(&Json2ExtensionType::default());
for (name, column_id, data_type) in [
(
"__table_id",
ReservedColumnId::table_id(),
ConcreteDataType::uint32_datatype(),
),
(
"__tsid",
ReservedColumnId::tsid(),
ConcreteDataType::uint64_datatype(),
),
] {
request.column_metadatas.push(ColumnMetadata {
column_schema: ColumnSchema::new(name, data_type, false),
semantic_type: SemanticType::Tag,
column_id,
});
}
request.primary_key.splice(
0..0,
[ReservedColumnId::table_id(), ReservedColumnId::tsid()],
);
let table_dir = request.table_dir.clone();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
let mut rows = Rows {
schema: schema.clone(),
rows: vec![row(vec![
ValueData::StringValue("metric".into()),
ValueData::StringValue("api".into()),
ValueData::F64Value(1.5),
ValueData::JsonValue(encode_json_value(JsonValue::from(
json!({"trace_id":"abc"}),
))),
ValueData::TimestampMillisecondValue(1),
])],
};
rows.rows[0].values.extend([
ValueData::U32Value(42).into(),
ValueData::U64Value(7).into(),
]);
// Equal series/timestamp observations are preserved in append mode.
rows.rows.push(rows.rows[0].clone());
let mut null_row = rows.rows[0].clone();
null_row.values[0].value_data = None;
null_row.values[1].value_data = None;
// Different source metrics can have the same TSID.
null_row.values[5] = ValueData::U32Value(43).into();
rows.rows.push(null_row);
test_util::put_rows(&engine, region_id, rows.clone()).await;
// Reopen without encoding options, replaying raw rows from WAL.
reopen_region(&engine, region_id, table_dir.clone(), true, HashMap::new()).await;
assert_eq!(
engine.get_primary_key_encoding(region_id).unwrap(),
PrimaryKeyEncoding::Sparse
);
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::AddColumns {
columns: vec![AddColumn {
column_metadata: ColumnMetadata {
column_schema: ColumnSchema::new(
"new_tag",
ConcreteDataType::string_datatype(),
true,
),
semantic_type: SemanticType::Tag,
column_id: 5,
},
location: None,
}],
},
}),
)
.await?;
// A stale writer omits the newly added nullable tag.
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 86400,
}),
..Default::default()
}),
)
.await?;
reopen_region(
&engine,
region_id,
table_dir.clone(),
true,
HashMap::from([
("primary_key_encoding".into(), "dense".into()),
("sst_format".into(), "primary_key".into()),
]),
)
.await;
reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await;
assert_eq!(
engine.get_primary_key_encoding(region_id).unwrap(),
PrimaryKeyEncoding::Sparse
);
let mut cases = vec![
(vec![], 6),
(vec![col("tag_0").eq(lit("metric"))], 4),
(vec![col("tag_0").is_null()], 2),
];
cases.extend([
(vec![col("__table_id").eq(lit(42u32))], 4),
(vec![col("__table_id").eq(lit(43u32))], 2),
(vec![col("__tsid").eq(lit(7u64))], 6),
]);
for (filters, expected) in cases {
let scanner = engine
.scanner(
region_id,
ScanRequest {
filters,
json_type_hint: HashMap::from([(
"field_1".into(),
JsonNativeType::Variant,
)]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
assert_eq!(
batches.iter().map(|b| b.num_rows()).sum::<usize>(),
expected
);
for batch in batches.iter() {
let label_index = batch.schema.column_index_by_name("new_tag").unwrap();
assert_eq!(batch.column(label_index).null_count(), batch.num_rows());
}
}
}
Ok(())
}
#[tokio::test]
async fn test_nullable_label_filters_in_memtables_and_ssts() {
use datafusion_expr::{BinaryExpr as LogicalBinaryExpr, Cast, Expr};
for (flat, memtable) in [(false, "time_series"), (true, "bulk")] {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("memtable.type", memtable)
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = [None, Some(""), Some("tmpfs"), Some("ext4")]
.into_iter()
.enumerate()
.map(|(i, label)| {
let mut row = row(vec![
ValueData::StringValue(String::new()),
ValueData::F64Value(i as f64),
ValueData::TimestampMillisecondValue(i as i64),
]);
row.values[0].value_data = label.map(|v| ValueData::StringValue(v.into()));
row
})
.collect();
test_util::put_rows(&engine, region_id, Rows { schema, rows }).await;
for flushed in [false, true] {
if flushed {
test_util::flush_region(&engine, region_id, None).await;
}
let mut cases = Vec::new();
for (op, literal, include_null, expected) in [
(Operator::NotEq, "tmpfs", true, vec![0, 1, 3]),
(
Operator::RegexNotMatch,
"^(?:tmpfs|vfat)$",
true,
vec![0, 1, 3],
),
(Operator::Eq, "", true, vec![0, 1]),
(Operator::NotEq, "", false, vec![2, 3]),
(Operator::RegexMatch, "^(?:ext4)$", false, vec![3]),
] {
for cast in [false, true] {
let column = if cast {
Expr::Cast(Cast::new(Box::new(col("tag_0")), DataType::Utf8))
} else {
col("tag_0")
};
let comparison = Expr::BinaryExpr(LogicalBinaryExpr::new(
Box::new(column),
op,
Box::new(lit(literal)),
));
let filter = if include_null {
col("tag_0").is_null().or(comparison)
} else {
comparison
};
cases.push((filter, expected.clone()));
}
}
let column = col("tag_0");
cases.extend([
(column.clone().is_null(), vec![0]),
(column.clone().is_not_null(), vec![1, 2, 3]),
(
column
.clone()
.is_null()
.or(column.clone().not_eq(lit("tmpfs")))
.and(column.clone().is_null().or(column.clone().not_eq(lit("")))),
vec![0, 3],
),
(
column.clone().eq(lit("ext4")).or(column.eq(lit("tmpfs"))),
vec![2, 3],
),
]);
for (filter, expected) in cases {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![filter.clone()],
distribution: flat.then_some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let mut actual = Vec::new();
for batch in batches.iter() {
let ts = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
actual.extend(ts.values().iter().copied());
}
actual.sort_unstable();
assert_eq!(actual, expected, "flat={flat}, flushed={flushed}, {filter}");
}
}
}
}
#[tokio::test]
async fn test_compound_time_filters_before_last_row() {
for (flat, memtable) in [
(false, "time_series"),
(true, "time_series"),
(true, "bulk"),
] {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("memtable.type", memtable)
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = (0..5)
.map(|i| {
row(vec![
ValueData::StringValue("series".into()),
ValueData::F64Value(i as f64),
ValueData::TimestampMillisecondValue(i),
])
})
.collect();
test_util::put_rows(&engine, region_id, Rows { schema, rows }).await;
let ts = |value| lit(ScalarValue::TimestampMillisecond(Some(value), None));
let cases = [
(col("ts").eq(ts(1)).or(col("ts").eq(ts(3))), vec![1, 3]),
(col("ts").gt_eq(ts(1)).and(col("ts").lt(ts(3))), vec![1, 2]),
(col("ts").is_null().or(col("ts").lt(ts(2))), vec![0, 1]),
];
for flushed in [false, true] {
if flushed {
test_util::flush_region(&engine, region_id, None).await;
}
for (filter, expected) in &cases {
for selector in [
None,
Some(TimeSeriesRowSelector::LastRow { after_merge: false }),
Some(TimeSeriesRowSelector::LastRow { after_merge: true }),
] {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![
col("tag_0").is_null().or(col("tag_0").eq(lit("series"))),
filter.clone(),
],
distribution: flat.then_some(TimeSeriesDistribution::PerSeries),
series_row_selector: selector,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let mut actual = Vec::new();
for batch in batches.iter() {
actual.extend(
batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>()
.values()
.iter()
.copied(),
);
}
actual.sort_unstable();
let expected = if selector.is_some() {
expected.last().copied().into_iter().collect::<Vec<_>>()
} else {
expected.clone()
};
assert_eq!(
actual, expected,
"flat={flat}, memtable={memtable}, flushed={flushed}, selector={selector:?}, {filter}"
);
}
}
}
}
}
#[tokio::test]
async fn test_json_type_hint_pushdown_scanner_returns_batches() -> WhateverResult<()> {
// Create a region with a JSON2 field whose physical Parquet representation is a nested struct.
// The scan below will only ask for field_0.a.x.
let request = CreateRequestBuilder::new()
.field_datatype(ConcreteDataType::json2(JsonNativeType::Object(
JsonObjectType::from([
(
"a".to_string(),
JsonNativeType::Object(JsonObjectType::from([
("x".to_string(), JsonNativeType::i64()),
("y".to_string(), JsonNativeType::String),
])),
),
("b".to_string(), JsonNativeType::String),
]),
)))
.build();
let schema = test_util::rows_schema(&request);
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
// Write full JSON objects, then flush them so the scanner has an Parquet file where nested
// projection can be pushed down.
for values in [
vec![
ValueData::StringValue("tag-1".to_string()),
ValueData::JsonValue(encode_json_value(JsonValue::from(json!({
"a": { "x": 10, "y": "ignored-a" },
"b": "ignored-b"
})))),
ValueData::TimestampMillisecondValue(1000),
],
vec![
ValueData::StringValue("tag-2".to_string()),
ValueData::JsonValue(encode_json_value(JsonValue::from(json!({
"a": { "x": 20, "y": "ignored-c" },
"b": "ignored-d"
})))),
ValueData::TimestampMillisecondValue(2000),
],
] {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: vec![row(values)],
},
)
.await;
}
test_util::flush_region(&engine, region_id, None).await;
// Without a type hint, the scanner reads the whole JSON2 root column.
let request = ScanRequest {
projection: Some(vec![1, 0]),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await?;
let Scanner::Seq(seq_scan) = &scanner else {
unreachable!();
};
assert_eq!(
seq_scan.input().read_cols,
ReadColumns::new([1, 0])
.with_json_target_types(BTreeMap::from([(1, JsonNativeType::Variant)]))
);
let stream = scanner.scan().await?;
let batches = RecordBatches::try_collect(stream).await?;
let expected = r#"
+------------------------------------------------+-------+
| field_0 | tag_0 |
+------------------------------------------------+-------+
| {"a":{"x":10,"y":"ignored-a"},"b":"ignored-b"} | tag-1 |
| {"a":{"x":20,"y":"ignored-c"},"b":"ignored-d"} | tag-2 |
+------------------------------------------------+-------+
"#;
assert_eq!(batches.pretty_print()?, expected.trim());
// Simulate a query expression like json_get(field_0, 'a.x'): the logical projection still
// returns the JSON2 root column, while json_type_hint tells scan input construction which
// nested physical path is needed.
let json_type_hint = HashMap::from([(
"field_0".to_string(),
JsonNativeType::Object(JsonObjectType::from([(
"a".to_string(),
JsonNativeType::Object(JsonObjectType::from([(
"x".to_string(),
JsonNativeType::i64(),
)])),
)])),
)]);
let request = ScanRequest {
projection: Some(vec![1, 0]),
json_type_hint: json_type_hint.clone(),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await?;
let Scanner::Seq(seq_scan) = &scanner else {
unreachable!();
};
// Verify the scan input only asks storage for field_0.a.x instead of the
// whole JSON2 struct. tag_0 is still read as a normal root column.
assert_eq!(
seq_scan.input().read_cols,
ReadColumns::new([1, 0])
.with_json_target_types(BTreeMap::from([(1, json_type_hint["field_0"].clone())]))
);
// The scanner should still return a valid RecordBatch in the requested logical projection.
// Fields outside the pushed-down path are pruned from the returned JSON2 type and value.
let stream = scanner.scan().await?;
let batches = RecordBatches::try_collect(stream).await?;
let expected = r#"
+--------------+-------+
| field_0 | tag_0 |
+--------------+-------+
| {a: {x: 10}} | tag-1 |
| {a: {x: 20}} | tag-2 |
+--------------+-------+
"#;
assert_eq!(batches.pretty_print()?, expected.trim());
// A type hint only narrows a projected JSON2 root; it must not add an unprojected root.
let request = ScanRequest {
projection: Some(vec![0]),
json_type_hint,
..Default::default()
};
let scanner = engine.scanner(region_id, request).await?;
let Scanner::Seq(seq_scan) = &scanner else {
unreachable!();
};
assert_eq!(seq_scan.input().read_cols, ReadColumns::new([0]));
let stream = scanner.scan().await?;
let batches = RecordBatches::try_collect(stream).await?;
let expected = r#"
+-------+
| tag_0 |
+-------+
| tag-1 |
| tag-2 |
+-------+
"#;
assert_eq!(batches.pretty_print()?, expected.trim());
// JSON type hints are derived from the whole query plan, so they may include
// columns unrelated to this scan. Mito2 should ignore hints for unknown
// columns (`other_json`) instead of failing.
let request = ScanRequest {
projection: Some(vec![0]),
json_type_hint: HashMap::from([("other_json".to_string(), JsonNativeType::String)]),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await?;
let stream = scanner.scan().await?;
let batches = RecordBatches::try_collect(stream).await?;
assert_eq!(batches.pretty_print()?, expected.trim());
Ok(())
}
#[tokio::test]
async fn test_json2_v1_region_reopen_and_compaction() -> WhateverResult<()> {
let mut request = CreateRequestBuilder::new()
.field_datatype(ConcreteDataType::json2(JsonNativeType::Object(
JsonObjectType::new(),
)))
.insert_option("memtable.type", "bulk")
.build();
let settings = JsonSettings::default();
request.column_metadatas[1]
.column_schema
.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new_v1(
settings,
))));
let table_dir = request.table_dir.clone();
let schema = test_util::rows_schema(&request);
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
let values = [
json!({"route": 1}),
json!({"b": {"c": "x"}}),
json!({"route": 3, "written_after_reopen": true}),
];
for (i, value) in values[..2].iter().enumerate() {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: vec![row(vec![
ValueData::StringValue("tag".to_string()),
ValueData::JsonValue(encode_json_value(JsonValue::from(value.clone()))),
ValueData::TimestampMillisecondValue((i as i64 + 1) * 1000),
])],
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
reopen_region(
&engine,
region_id,
table_dir,
true,
HashMap::from([("memtable.type".to_string(), "bulk".to_string())]),
)
.await;
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let column = &version
.metadata
.column_by_name("field_0")
.unwrap()
.column_schema;
let extension = column.extension_type::<Json2ExtensionType>()?.unwrap();
assert!(extension.metadata().is_version_2());
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: vec![row(vec![
ValueData::StringValue("tag".to_string()),
ValueData::JsonValue(encode_json_value(JsonValue::from(values[2].clone()))),
ValueData::TimestampMillisecondValue(3000),
])],
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let region = engine.get_region(region_id).unwrap();
let input_files = region
.version()
.ssts
.levels()
.iter()
.map(|level| level.files.len())
.sum::<usize>();
assert_eq!(3, input_files);
// The same requested path is stored as a v1 explicit leaf in the first SST, is absent from
// the second SST, and lives in the v2 remainder in the third SST. A per-file route preserves
// those differences while exposing one logical query type to the merge reader.
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
json_type_hint: HashMap::from([(
"field_0".to_string(),
JsonNativeType::Object(JsonObjectType::from([(
"route".to_string(),
JsonNativeType::i64(),
)])),
)]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut routed = Vec::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
let json = JsonArray::from(&array);
for i in 0..array.len() {
routed.push(json.try_get_value(i)?);
}
}
assert_eq!(
[json!({"route": 1}), json!(null), json!({"route": 3})],
routed.as_slice()
);
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest::default()),
)
.await?;
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut actual = Vec::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
let json = JsonArray::from(&array);
for i in 0..array.len() {
actual.push(json.try_get_value(i)?);
}
}
assert_eq!(values, actual.as_slice());
Ok(())
}
#[tokio::test]
async fn test_json2_mixed_subject_compaction_preserves_values() -> WhateverResult<()> {
let request = CreateRequestBuilder::new()
.field_datatype(ConcreteDataType::json2(JsonNativeType::Object(
JsonObjectType::new(),
)))
.insert_option("append_mode", "true")
.insert_option("memtable.type", "bulk")
.insert_option("sst_format", "flat")
.build();
let table_dir = request.table_dir.clone();
let schema = test_util::rows_schema(&request);
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
min_compaction_interval: std::time::Duration::from_secs(3600),
..Default::default()
})
.await;
let region_id = RegionId::new(1027, 0);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
// #9133: the second SST stores a heterogeneous subject in its remainder.
let values = [
json!({"subject": {"cid": "first", "uri": "at://first"}}),
json!({"subject": "did:plc:x"}),
json!({"subject": {"cid": "last", "uri": "at://last"}}),
json!({"subject": {"cid": 42}}),
];
for (offset, batch) in [(0, &values[..1]), (1, &values[1..])] {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: batch
.iter()
.enumerate()
.map(|(i, value)| {
row(vec![
ValueData::StringValue("tag".into()),
ValueData::JsonValue(encode_json_value(JsonValue::from(value.clone()))),
ValueData::TimestampMillisecondValue((offset + i) as i64 * 1000),
])
})
.collect(),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
let old_ids = engine
.scanner(region_id, ScanRequest::default())
.await?
.file_ids();
assert_eq!(2, old_ids.len());
for _ in 0..2 {
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 86400,
}),
..Default::default()
}),
)
.await?;
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
..Default::default()
},
)
.await?;
assert_eq!(
1,
scanner.num_files(),
"a swallowed merge failure must not pass"
);
assert!(scanner.file_ids().iter().all(|id| !old_ids.contains(id)));
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut actual = Vec::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
for i in 0..array.len() {
actual.push(JsonArray::from(&array).try_get_value(i)?);
}
}
assert_eq!(values.as_slice(), actual.as_slice());
reopen_region(&engine, region_id, table_dir.clone(), true, HashMap::new()).await;
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
json_type_hint: HashMap::from([(
"field_0".into(),
JsonNativeType::Object(JsonObjectType::from([(
"subject".into(),
JsonNativeType::String,
)])),
)]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut subjects = Vec::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
for i in 0..array.len() {
subjects.push(JsonArray::from(&array).try_get_value(i)?);
}
}
let expected = values.iter().map(|value| {
let subject = &value["subject"];
json!({"subject": subject.as_str().map(str::to_string).unwrap_or_else(|| subject.to_string())})
}).collect::<Vec<_>>();
assert_eq!(
expected, subjects,
"projection must read values spilled to remainder"
);
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
json_type_hint: HashMap::from([(
"field_0".into(),
JsonNativeType::Object(JsonObjectType::from([(
"subject".into(),
JsonNativeType::Object(JsonObjectType::from([(
"cid".into(),
JsonNativeType::String,
)])),
)])),
)]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut cids = Vec::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
for i in 0..array.len() {
cids.push(JsonArray::from(&array).try_get_value(i)?["subject"]["cid"].clone());
}
}
assert_eq!(
vec![json!("first"), json!(null), json!("last"), json!("42")],
cids
);
}
Ok(())
}
#[tokio::test]
async fn test_flush_aligns_different_json2_layouts() -> WhateverResult<()> {
let mut request = CreateRequestBuilder::new()
.field_datatype(ConcreteDataType::json2(JsonNativeType::Object(
JsonObjectType::new(),
)))
.insert_option("append_mode", "true")
.insert_option("memtable.type", "bulk")
.build();
let settings = JsonSettings::try_new(vec![], Some(1))?;
request.column_metadatas[1]
.column_schema
.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new(
settings,
))));
let schema = test_util::rows_schema(&request);
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1025, 0);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
for (offset, name) in [(0, "a"), (1024, "b")] {
let rows = (0..1024)
.map(|i| {
row(vec![
ValueData::StringValue("tag".to_string()),
ValueData::JsonValue(encode_json_value(JsonValue::from(json!({(name): i})))),
ValueData::TimestampMillisecondValue(offset + i),
])
})
.collect();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows,
},
)
.await;
}
test_util::flush_region(&engine, region_id, None).await;
let scanner = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![1]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
let mut counts = HashMap::new();
for batch in batches.iter() {
let array = batch.column_by_name("field_0").unwrap().clone();
let json = JsonArray::from(&array);
for i in 0..array.len() {
let value = json.try_get_value(i)?;
let name = match (value.get("a"), value.get("b")) {
(Some(_), None) => "a",
(None, Some(_)) => "b",
_ => panic!("expected exactly one dynamic JSON2 field, got {value}"),
};
*counts.entry(name).or_insert(0) += 1;
}
}
assert_eq!(Some(&1024), counts.get("a"));
assert_eq!(Some(&1024), counts.get("b"));
Ok(())
}
/// A cursor below the flushed frontier is rejected by the **flushed-frontier fence**, not by
/// an edit boundary: `last_invalid_seq` is gone, so the `min_readable_seq` the error reports
/// is `flushed_sequence`. An incremental read at the frontier serves the rows above it.
#[tokio::test]
async fn test_incremental_read_below_flushed_frontier_is_rejected_by_the_frontier() {
let mut env = TestEnv::with_prefix("test_incremental_read_below_flushed_frontier").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
// A cursor at 0 is below the flushed frontier (3), so the frontier fence rejects it and
// names the frontier as the minimum readable sequence.
let flushed = engine
.get_region(region_id)
.unwrap()
.version()
.flushed_sequence;
assert_eq!(3, flushed);
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
..Default::default()
},
)
.await
.err()
.expect("a cursor below the flushed frontier is rejected by the frontier fence");
assert!(
matches!(
err,
Error::IncrementalQueryStale {
given_seq: 0,
min_readable_seq,
..
} if min_readable_seq == flushed
),
"the fence reports the flushed frontier, not an edit boundary: {err}"
);
assert_eq!(StatusCode::RequestOutdated, err.status_code());
let memtable_only_rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
};
test_util::put_rows(&engine, region_id, memtable_only_rows).await;
// An incremental read above the flushed frontier serves exactly the rows above it.
let scanner = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(flushed),
skip_sst_files: true,
..Default::default()
},
)
.await
.unwrap();
let stream = scanner.scan().await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
batches.pretty_print().unwrap(),
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
+-------+---------+---------------------+"
);
}
#[tokio::test]
async fn test_scan_with_min_sst_sequence() {
test_scan_with_min_sst_sequence_with_format(false).await;
test_scan_with_min_sst_sequence_with_format(true).await;
}
#[tokio::test]
async fn test_full_snapshot_upper_bound_returns_outdated_after_late_flush() {
let mut env =
TestEnv::with_prefix("test_full_snapshot_upper_bound_returns_outdated_after_late_flush")
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let first_rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, first_rows).await;
test_util::flush_region(&engine, region_id, None).await;
let snapshot_upper_bound = engine.get_committed_sequence(region_id).await.unwrap();
let second_rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
};
test_util::put_rows(&engine, region_id, second_rows).await;
test_util::flush_region(&engine, region_id, None).await;
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_max_sequence: Some(snapshot_upper_bound),
..Default::default()
},
)
.await
.err()
.expect("expect stale snapshot fence error");
assert_eq!(StatusCode::RequestOutdated, err.status_code());
let err_msg = err.to_string();
assert!(err_msg.contains("STALE_SNAPSHOT_FENCE"));
assert!(err_msg.contains(&region_id.to_string()));
assert!(err_msg.contains(&format!("given_seq: {snapshot_upper_bound}")));
}
/// A scan states the creators of the files another region left in its file list: a read that
/// prunes every file away still says which regions' rows the region may hold, and says the empty
/// set when every visible file is its own.
#[tokio::test]
async fn test_snapshot_identity_states_visible_foreign_file_creators() {
let mut env = TestEnv::with_prefix("test_snapshot_identity_file_creators").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let foreign_creator = RegionId::new(1, 2);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
// Every visible file was created by the region itself: a positive "nothing foreign" answer.
let own = engine
.handle_query(region_id, ScanRequest::default())
.await
.unwrap()
.snapshot_identity()
.expect("a mito scan states its snapshot identity");
assert_eq!(Some(Vec::new()), own.visible_foreign_file_creators);
// Publish a file another region created into this region's file list, which is what a
// repartition leaves behind.
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![FileMeta {
region_id: foreign_creator,
file_id: FileId::random(),
time_range: (
Timestamp::new_millisecond(0),
Timestamp::new_millisecond(1000),
),
level: 0,
file_size: 0,
max_row_group_uncompressed_size: 0,
available_indexes: Default::default(),
indexes: vec![],
index_file_size: 0,
index_version: 0,
num_rows: 0,
num_row_groups: 0,
sequence: None,
partition_expr: None,
num_series: 0,
preserve_row_sequence: true,
..Default::default()
}],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
// A read whose time range prunes everything still states the creator: the file list is read
// from the version in memory, before any pruning.
let pruned = engine
.handle_query(
region_id,
ScanRequest {
filters: vec![col("ts").gt(lit(Timestamp::new_millisecond(i64::MAX / 2).value()))],
..Default::default()
},
)
.await
.unwrap()
.snapshot_identity()
.expect("a mito scan states its snapshot identity");
assert_eq!(
Some(vec![foreign_creator.as_u64()]),
pruned.visible_foreign_file_creators
);
}
/// A scan states the partition expression of the **one** version whose `committed_sequence` it
/// bound as its upper bound, in the canonical form a flow cursor entry is keyed by - and states
/// the region's whole domain as `None` when that version has no expression.
#[tokio::test]
async fn test_snapshot_identity_states_the_partition_expr_of_the_bound_version() {
let mut env = TestEnv::with_prefix("test_snapshot_identity_partition_expr").await;
let engine = env.create_engine(MitoConfig::default()).await;
// Value-first shape: the identity a cursor entry keys must be canonicalized before it is
// stated, or the same slice would be keyed two ways.
let expr_json =
r#"{"Expr":{"lhs":{"Value":{"String":"k5"}},"op":"Gt","rhs":{"Column":"tag_0"}}}"#;
let partitioned = RegionId::new(1, 1);
let unpartitioned = RegionId::new(1, 2);
for (region_id, request) in [
(
partitioned,
CreateRequestBuilder::new()
.partition_expr_json(Some(expr_json.to_string()))
.build(),
),
(unpartitioned, CreateRequestBuilder::new().build()),
] {
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
}
let expected_snapshot = engine.get_committed_sequence(partitioned).await.unwrap();
let scanner = engine
.handle_query(
partitioned,
ScanRequest {
snapshot_on_scan: true,
..Default::default()
},
)
.await
.unwrap();
let identity = scanner
.snapshot_identity()
.expect("a mito scan states its snapshot identity");
let expected_identity = partition::expr::PartitionExpr::from_json_str(expr_json)
.unwrap()
.unwrap()
.as_json_str()
.unwrap();
assert_eq!(Some(expected_snapshot), identity.bound_sequence);
assert_eq!(Some(expected_identity), identity.partition_expr);
// One version, both fields: the sequence the trait reports is the identity's bound.
assert_eq!(scanner.snapshot_sequence(), identity.bound_sequence);
let whole_domain = engine
.handle_query(unpartitioned, ScanRequest::default())
.await
.unwrap()
.snapshot_identity()
.expect("a mito scan states its snapshot identity");
assert_eq!(None, whole_domain.partition_expr);
}
#[tokio::test]
async fn test_snapshot_bound_query_binds_memtable_upper_bound_at_scan_open() {
let mut env =
TestEnv::with_prefix("test_snapshot_bound_query_binds_memtable_upper_bound_at_scan_open")
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let first_rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, first_rows).await;
let expected_snapshot = engine.get_committed_sequence(region_id).await.unwrap();
let scanner = engine
.scanner(
region_id,
ScanRequest {
snapshot_on_scan: true,
..Default::default()
},
)
.await
.unwrap();
assert_eq!(scanner.snapshot_sequence(), Some(expected_snapshot));
let second_rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
};
test_util::put_rows(&engine, region_id, second_rows).await;
let stream = scanner.scan().await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
batches.pretty_print().unwrap(),
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
+-------+---------+---------------------+"
);
}
#[tokio::test]
async fn test_snapshot_bound_query_keeps_open_snapshot_after_late_flush() {
let mut env =
TestEnv::with_prefix("test_snapshot_bound_query_keeps_open_snapshot_after_late_flush")
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let first_rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, first_rows).await;
let expected_snapshot = engine.get_committed_sequence(region_id).await.unwrap();
let scanner = engine
.scanner(
region_id,
ScanRequest {
snapshot_on_scan: true,
..Default::default()
},
)
.await
.unwrap();
assert_eq!(scanner.snapshot_sequence(), Some(expected_snapshot));
let second_rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
};
test_util::put_rows(&engine, region_id, second_rows).await;
test_util::flush_region(&engine, region_id, None).await;
assert_eq!(scanner.snapshot_sequence(), Some(expected_snapshot));
}
#[tokio::test]
async fn test_snapshot_bound_query_keeps_correct_result_after_late_flush() {
let mut env =
TestEnv::with_prefix("test_snapshot_bound_query_keeps_correct_result_after_late_flush")
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let first_rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, first_rows).await;
let expected_snapshot = engine.get_committed_sequence(region_id).await.unwrap();
let scanner = engine
.scanner(
region_id,
ScanRequest {
snapshot_on_scan: true,
..Default::default()
},
)
.await
.unwrap();
assert_eq!(scanner.snapshot_sequence(), Some(expected_snapshot));
let second_rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
};
test_util::put_rows(&engine, region_id, second_rows).await;
test_util::flush_region(&engine, region_id, None).await;
assert_eq!(scanner.snapshot_sequence(), Some(expected_snapshot));
let stream = scanner.scan().await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
batches.pretty_print().unwrap(),
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
+-------+---------+---------------------+"
);
}
async fn test_scan_with_min_sst_sequence_with_format(flat_format: bool) {
let mut env = TestEnv::with_prefix("test_scan_with_min_sst_sequence").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat_format,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let put_rows = async |start, end| {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
};
// generates 3 SST files
put_rows(0, 3).await;
put_rows(3, 6).await;
put_rows(6, 9).await;
let scan_engine = async |file_min_sequence, expected_files, expected_data| {
let request = ScanRequest {
sst_min_sequence: file_min_sequence,
..Default::default()
};
let scanner = engine.scanner(region_id, request).await.unwrap();
assert_eq!(scanner.num_files(), expected_files);
let stream = scanner.scan().await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(batches.pretty_print().unwrap(), expected_data);
};
// scans with no sst minimal sequence limit
scan_engine(
None,
3,
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
| 6 | 6.0 | 1970-01-01T00:00:06 |
| 7 | 7.0 | 1970-01-01T00:00:07 |
| 8 | 8.0 | 1970-01-01T00:00:08 |
+-------+---------+---------------------+",
)
.await;
// scans with sst minimal sequence > 2
scan_engine(
Some(2),
3,
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
| 6 | 6.0 | 1970-01-01T00:00:06 |
| 7 | 7.0 | 1970-01-01T00:00:07 |
| 8 | 8.0 | 1970-01-01T00:00:08 |
+-------+---------+---------------------+",
)
.await;
// scans with sst minimal sequence > 3
scan_engine(
Some(3),
2,
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
| 6 | 6.0 | 1970-01-01T00:00:06 |
| 7 | 7.0 | 1970-01-01T00:00:07 |
| 8 | 8.0 | 1970-01-01T00:00:08 |
+-------+---------+---------------------+",
)
.await;
// scans with sst minimal sequence > 7
scan_engine(
Some(7),
1,
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 6 | 6.0 | 1970-01-01T00:00:06 |
| 7 | 7.0 | 1970-01-01T00:00:07 |
| 8 | 8.0 | 1970-01-01T00:00:08 |
+-------+---------+---------------------+",
)
.await;
// scans with sst minimal sequence > 9 (no sst files will be selected to scan)
scan_engine(
Some(9),
0,
"\
+-------+---------+----+
| tag_0 | field_0 | ts |
+-------+---------+----+
+-------+---------+----+",
)
.await;
}
#[tokio::test]
async fn test_max_concurrent_scan_files() {
test_max_concurrent_scan_files_with_format(false, false).await;
test_max_concurrent_scan_files_with_format(true, false).await;
}
#[tokio::test]
async fn test_scan_memory_limit_small_legacy_files() {
test_max_concurrent_scan_files_with_format(false, true).await;
test_max_concurrent_scan_files_with_format(true, true).await;
}
async fn test_max_concurrent_scan_files_with_format(flat_format: bool, estimated: bool) {
let mut env = TestEnv::with_prefix("test_max_concurrent_scan_files").await;
let config = MitoConfig {
default_flat_format: flat_format,
max_concurrent_scan_files: 2,
scan_memory_limit: if estimated {
common_base::memory_limit::MemoryLimit::Size(ReadableSize::mb(1))
} else {
common_base::memory_limit::MemoryLimit::Unlimited
},
..Default::default()
};
let engine = env.create_engine(config).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let put_and_flush = async |start, end| {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
};
// Write overlapping files.
put_and_flush(0, 4).await;
put_and_flush(3, 7).await;
put_and_flush(6, 9).await;
if estimated {
// Simulate SSTs created before the manifest recorded row-group sizes.
let region = engine.get_region(region_id).unwrap();
let version = region.version_control.current().version;
let legacy_files = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files())
.map(|file| {
let mut meta = file.meta_ref().clone();
meta.max_row_group_uncompressed_size = 0;
meta
})
.collect::<Vec<_>>();
let version = crate::region::version::VersionBuilder::from_version(version)
.clear_files()
.add_files(
Arc::new(crate::sst::file_purger::NoopFilePurger),
legacy_files.into_iter(),
)
.build();
region.version_control.overwrite_current(Arc::new(version));
}
let request = ScanRequest::default();
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Seq(scanner) = scanner else {
panic!("Scanner should be seq scan");
};
if estimated {
scanner.check_scan_limit().unwrap();
RecordBatches::try_collect(scanner.build_stream().unwrap())
.await
.unwrap();
} else {
let error = scanner.check_scan_limit().unwrap_err();
assert_eq!(StatusCode::RateLimited, error.status_code());
}
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(scanner) = scanner else {
panic!("Scanner should be series scan");
};
if estimated {
scanner.check_scan_limit().unwrap();
RecordBatches::try_collect(scanner.build_stream().await.unwrap())
.await
.unwrap();
} else {
let error = scanner.check_scan_limit().unwrap_err();
assert_eq!(StatusCode::RateLimited, error.status_code());
}
}
#[tokio::test]
async fn test_series_scan() {
test_series_scan_with_format(false).await;
test_series_scan_with_format(true).await;
}
async fn test_series_scan_with_format(flat_format: bool) {
let mut env = TestEnv::with_prefix("test_series_scan").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat_format,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.time_window", "1h")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let put_flush_rows = async |start, end| {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
};
// generates 3 SST files
put_flush_rows(0, 3).await;
put_flush_rows(2, 6).await;
put_flush_rows(3600, 3603).await;
// Put to memtable.
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(7200, 7203),
};
test_util::put_rows(&engine, region_id, rows).await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(mut scanner) = scanner else {
panic!("Scanner should be series scan");
};
assert_eq!("legacy", scanner.mode());
// 3 partition ranges for 3 time window.
assert_eq!(
3,
scanner.properties().partitions[0].len(),
"unexpected ranges: {:?}",
scanner.properties().partitions
);
let raw_ranges: Vec<_> = scanner
.properties()
.partitions
.iter()
.flatten()
.cloned()
.collect();
let mut new_ranges = Vec::with_capacity(3);
for range in raw_ranges {
new_ranges.push(vec![range]);
}
scanner
.prepare(PrepareRequest {
ranges: Some(new_ranges),
..Default::default()
})
.unwrap();
let actual_rows = collect_partition_rows_round_robin(&scanner, 3).await;
let mut expected_rows = Vec::new();
for value in [0_i64, 1, 2, 3, 4, 5, 3600, 3601, 3602, 7200, 7201, 7202] {
expected_rows.push((value.to_string(), value as f64, value * 1000));
}
expected_rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
assert_eq!(expected_rows, actual_rows);
scanner.reset_state();
assert_eq!("legacy", scanner.mode());
assert_eq!(
vec![1, 1, 1],
scanner
.properties()
.partitions
.iter()
.map(Vec::len)
.collect::<Vec<_>>()
);
assert_eq!(
expected_rows,
collect_partition_rows_round_robin(&scanner, 3).await
);
}
/// Cross-range merges split long series but preserve larger batches for short series.
#[tokio::test]
async fn test_series_scan_single_source_range_batches() {
for rows_per_series in [16, 49, 50, 64] {
check_series_scan_single_source_range_batches(rows_per_series).await;
}
}
async fn check_series_scan_single_source_range_batches(rows_per_series: usize) {
let mut env = TestEnv::with_prefix("test_series_scan_single_source_range_batches").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
range_result_cache_size: ReadableSize::mb(64),
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.time_window", "1h")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let mut expected = Vec::new();
for start in [0, 3600] {
let mut rows = Vec::new();
for key in ["a", "b", "c", "d"] {
rows.extend(test_util::build_rows_for_key(
key,
start,
start + rows_per_series,
0,
));
expected.extend(
(0..rows_per_series)
.map(|i| (key.to_string(), i as f64, (start + i) as i64 * 1000)),
);
}
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows,
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
expected.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
// Exercise both newly read and cached range streams at the same merge boundary.
for last_row in [false, true] {
let expected = if last_row {
expected
.iter()
.filter(|(_, _, ts)| *ts == (3600 + rows_per_series as i64 - 1) * 1000)
.cloned()
.collect::<Vec<_>>()
} else {
expected.clone()
};
for with_cache in [false, true] {
let request = ScanRequest {
series_row_selector: last_row
.then_some(TimeSeriesRowSelector::LastRow { after_merge: true }),
// Range caching requires a tag predicate; this one retains every row.
filters: if with_cache {
vec![col("tag_0").gt_eq(lit("a"))]
} else {
vec![]
},
..Default::default()
};
// Populate the ordinary scan cache first. Its unsplit batches must not
// replace the batches prepared for a later cross-range merge.
if with_cache {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let Scanner::Seq(scanner) =
engine.scanner(region_id, request.clone()).await.unwrap()
else {
panic!("expected sequential scan");
};
let ctx = store_api::region_engine::QueryScanContext {
explain_verbose: true,
..Default::default()
};
let stream = scanner
.scan_partition(&ctx, &ExecutionPlanMetricsSet::default(), 0)
.unwrap();
RecordBatches::try_collect(stream).await.unwrap();
if format!("{}", VerboseDisplay(scanner)).contains("\"range_cache_hit\":") {
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
let mut first_scan = true;
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let scanner = engine
.scanner(
region_id,
ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..request.clone()
},
)
.await
.unwrap();
let Scanner::Series(scanner) = scanner else {
panic!("expected series scan");
};
assert_eq!(2, scanner.properties().partitions[0].len());
let ctx = store_api::region_engine::QueryScanContext {
explain_verbose: true,
..Default::default()
};
let metrics = ExecutionPlanMetricsSet::default();
let stream = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let actual = collect_and_assert_partition_rows(
batches.schema(),
vec![batches.iter().cloned().collect()],
);
assert_eq!(expected, actual);
let display = format!("{}", VerboseDisplay(scanner));
let details: serde_json::Value =
serde_json::from_str(&display[display.find('{').unwrap()..]).unwrap();
let partitions = details["metrics_per_partition"].as_array().unwrap();
let rows: u64 = partitions
.iter()
.map(|p| {
p["metrics"]["merge_metrics"]["num_fetch_by_rows"]
.as_u64()
.unwrap_or(0)
})
.sum();
if last_row {
// LastRow coalesces the source splits before the cross-range
// merge. Do not turn its output into one batch per series.
let batches: u64 = partitions
.iter()
.map(|p| {
p["metrics"]["merge_metrics"]["num_fetch_by_batches"]
.as_u64()
.unwrap_or(0)
})
.sum();
assert!(batches <= 2, "{display}");
} else if rows_per_series >= 50 {
assert_eq!(0, rows, "{display}");
} else {
// Short series retain batches spanning multiple series instead
// of sending one tiny batch per series through the distributor.
assert!(rows > 0, "{display}");
}
if with_cache && first_scan {
assert!(
partitions.iter().all(|p| {
p["metrics"]["range_cache_hit"].as_u64().unwrap_or(0) == 0
}),
"ordinary scan cache was reused: {display}"
);
}
first_scan = false;
if !with_cache
|| partitions
.iter()
.any(|p| p["metrics"]["range_cache_hit"].as_u64().unwrap_or(0) > 0)
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
}
}
#[tokio::test]
async fn test_two_phase_series_scan() {
for use_index in [false, true] {
for use_range_index in [false, true] {
for mode in [
crate::config::ScanMemoryMode::Basic,
crate::config::ScanMemoryMode::Extended,
] {
check_two_phase_series_scan(use_index, use_range_index, true, mode).await;
}
}
check_two_phase_series_scan(use_index, true, false, crate::config::ScanMemoryMode::Basic)
.await;
}
}
async fn check_two_phase_series_scan(
use_index: bool,
use_range_index: bool,
enable_range_index: bool,
scan_memory_mode: crate::config::ScanMemoryMode,
) {
let mut env = TestEnv::with_prefix("test_two_phase_series_scan").await;
let engine = env
.create_engine(MitoConfig {
scan_memory_mode,
scan_memory_on_exhausted: common_memory_manager::OnExhaustedPolicy::Wait {
timeout: std::time::Duration::from_secs(30),
},
experimental_series_scan_v2: true,
experimental_enable_series_index: true,
experimental_enable_range_index: enable_range_index,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let metadata = Arc::new(sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
));
let mut request = CreateRequestBuilder::new().build();
request.column_metadatas = metadata.column_metadatas.clone();
request.primary_key = metadata.primary_key.clone();
request
.options
.insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string());
request
.options
.insert("memtable.type".to_string(), "bulk".to_string());
request
.options
.insert("sst_format".to_string(), "flat".to_string());
let full_row_schema = test_util::rows_schema(&request);
let mut encoded_primary_key_schema = full_row_schema[0].clone();
encoded_primary_key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string();
encoded_primary_key_schema.datatype = ColumnDataType::Binary.into();
encoded_primary_key_schema.semantic_type = SemanticType::Tag.into();
let row_schema = vec![
encoded_primary_key_schema,
full_row_schema[5].clone(),
full_row_schema[4].clone(),
];
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = |values: &[(u32, u64, &str, &str, u64, i64)]| Rows {
schema: row_schema.clone(),
rows: values
.iter()
.map(|(table_id, tsid, tag_0, tag_1, field, ts)| {
row(vec![
ValueData::BinaryValue(new_sparse_primary_key(
&[*tag_0, *tag_1],
&metadata,
*table_id,
*tsid,
)),
ValueData::TimestampMillisecondValue(*ts),
ValueData::U64Value(*field),
])
})
.collect(),
};
let put = |rows| {
RegionRequest::Put(RegionPutRequest {
skip_wal: false,
rows,
hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
}),
partition_expr_version: None,
})
};
engine
.handle_request(
region_id,
put(rows(&[
(10, 0, "a", "x", 10, 1000),
(10, u64::MAX, "b", "y", 20, 1000),
(20, 0, "c", "z", 30, 1000),
])),
)
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
if use_index || use_range_index {
use datatypes::arrow::array::{BinaryArray, UInt8Array, UInt64Array};
use crate::series_index::{
SeriesIndexEntry, SeriesIndexFileHandle, SeriesIndexVersion, SeriesIndexWriter,
SeriesIndexWriterOptions, series_index_channel, series_index_path,
};
let region = engine.find_region(region_id).unwrap();
let store = region.series_index_store.clone().unwrap();
let sequence = region.flushed_sequence();
let entry = SeriesIndexEntry {
artifact: None,
file_size: 0,
index_uuid: FileId::random(),
bucket_start: Timestamp::new_millisecond(0),
bucket_end: Timestamp::new_millisecond(2001),
source_file_ids: Vec::new(),
min_file_sequence: sequence,
max_file_sequence: sequence,
compaction_window_secs: 1,
window_sequences: Default::default(),
};
let keys = [
(10, 0, "a", "x"),
(10, u64::MAX, "b", "y"),
(20, 0, "c", "z"),
]
.map(|(table, tsid, a, b)| new_sparse_primary_key(&[a, b], &metadata, table, tsid));
let batch = DfRecordBatch::try_from_iter(vec![
(
"ts",
Arc::new(TimestampMillisecondArray::from(vec![1000; 3])) as ArrayRef,
),
(
"__primary_key",
Arc::new(BinaryArray::from_iter_values(&keys)),
),
("__sequence", Arc::new(UInt64Array::from_value(sequence, 3))),
("__op_type", Arc::new(UInt8Array::from_value(0, 3))),
])
.unwrap();
let mut index_version = SeriesIndexVersion::default();
if use_index {
let path = series_index_path(region_id, entry.index_uuid);
let mut writer = SeriesIndexWriter::try_new(
metadata.clone(),
store.clone(),
&path,
SeriesIndexWriterOptions::default(),
None,
)
.await
.unwrap();
writer.write(&batch).await.unwrap();
writer.finish().await.unwrap();
let (purger, _receiver) = series_index_channel(store.clone());
let handle = SeriesIndexFileHandle::new(region_id, entry.clone(), purger);
index_version
.series_indexes
.insert(entry.index_uuid, handle);
}
if use_range_index {
use crate::sst::range_index::{
SstRangeIndexWriter, SstRangeIndexWriterOptions, range_index_path,
};
let version = region.version();
let file = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.next()
.unwrap();
assert_eq!(1, file.meta_ref().num_row_groups);
let file_id = file.file_id().file_id();
let mut writer = SstRangeIndexWriter::try_new(
metadata.clone(),
store,
&range_index_path(region_id, file_id),
SstRangeIndexWriterOptions::default(),
)
.await
.unwrap();
writer.write(0, &batch).await.unwrap();
writer.finish().await.unwrap();
index_version.range_indexes.insert(
file_id,
crate::series_index::RangeIndexEntry {
file_id,
file_size: 0,
},
);
}
region
.series_index_version_control
.publish(Arc::new(index_version));
}
// A newer SST remains uncovered; the remaining writes stay in memory.
engine
.handle_request(region_id, put(rows(&[(10, 0, "a", "x", 11, 1000)])))
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
put(rows(&[
(10, 0, "a", "x", 12, 2000),
(10, u64::MAX, "b", "y", 21, 2000),
(20, u64::MAX, "d", "w", 40, 1000),
])),
)
.await
.unwrap();
let scanner = engine
.scanner(
region_id,
ScanRequest {
// Internal metric identifiers must still be read for candidate discovery.
projection: Some(vec![2, 4, 5]),
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
let Scanner::Series(mut scanner) = scanner else {
panic!("Scanner should be series scan");
};
assert_eq!("two_phase", scanner.mode());
let ranges = scanner
.properties()
.partitions
.iter()
.flatten()
.copied()
.collect::<Vec<_>>();
scanner
.prepare(
PrepareRequest::default()
.with_ranges(vec![ranges, Vec::new(), Vec::new()])
.with_target_partitions(3),
)
.unwrap();
let metrics_set = ExecutionPlanMetricsSet::default();
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1024 * 1024));
let context = store_api::region_engine::QueryScanContext {
memory_pool: pool.clone(),
..Default::default()
};
let partition_batches = try_join_all((0..3).map(|partition| {
let stream = scanner
.scan_partition(&context, &metrics_set, partition)
.unwrap();
async move { stream.try_collect::<Vec<_>>().await }
}))
.await
.unwrap();
let index_files = metrics_set
.clone_inner()
.sum_by_name("candidate_index_files")
.map_or(0, |value| value.as_usize());
assert_eq!(usize::from(use_index), index_files);
let mut series_to_partition = BTreeMap::new();
let mut actual_rows = Vec::new();
for (partition, batches) in partition_batches.into_iter().enumerate() {
for batch in batches {
let tags = batch.column_by_name("tag_0").unwrap();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<UInt64Type>();
let timestamps = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
let tag = datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string();
let previous = series_to_partition.insert(tag.clone(), partition);
if let Some(previous) = previous {
assert_eq!(previous, partition, "series {tag} moved partitions");
}
actual_rows.push((tag, fields.value(row), timestamps.value(row)));
}
}
}
actual_rows.sort();
assert_eq!(
vec![
("a".to_string(), 11, 1000),
("a".to_string(), 12, 2000),
("b".to_string(), 20, 1000),
("b".to_string(), 21, 2000),
("c".to_string(), 30, 1000),
("d".to_string(), 40, 1000),
],
actual_rows
);
assert_eq!(4, series_to_partition.len());
assert_eq!(Some(&0), series_to_partition.get("a"));
assert_eq!(Some(&0), series_to_partition.get("c"));
assert_eq!(Some(&2), series_to_partition.get("b"));
assert_eq!(Some(&2), series_to_partition.get("d"));
assert_eq!(0, pool.reserved());
// Existing query operators consume the same pool in either scan mode.
scanner.reset_state();
let other = MemoryConsumer::new("other-query-operator").register(&pool);
other.try_grow(1024 * 1024).unwrap();
let failed = try_join_all((0..3).map(|partition| {
let stream = scanner
.scan_partition(&context, &metrics_set, partition)
.unwrap();
async move { stream.try_collect::<Vec<_>>().await }
}))
.await;
assert!(failed.is_err());
other.free();
assert_eq!(0, pool.reserved());
// Exhausting the scan budget must fail even with an unbounded query pool.
scanner.reset_state();
let scan_tracker = &engine.inner.scan_memory_tracker;
// Cancelled background readers release their reservations asynchronously.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while scan_tracker.current() > 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let scan_guard = scan_tracker.reserve(scan_tracker.limit()).unwrap();
let fresh_context = store_api::region_engine::QueryScanContext::default();
let fresh_pool = Arc::downgrade(&fresh_context.memory_pool);
let failed = tokio::time::timeout(
std::time::Duration::from_secs(5),
try_join_all((0..3).map(|partition| {
let stream = scanner
.scan_partition(&fresh_context, &metrics_set, partition)
.unwrap();
async move { stream.try_collect::<Vec<_>>().await }
})),
)
.await
.expect("legacy wait policy must fail immediately on scan memory exhaustion");
assert!(failed.is_err());
drop(fresh_context);
// Keep the external quota occupied while failure tears down the distributor
// and readers. Cleanup must not depend on quota becoming available.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while fresh_pool.upgrade().is_some() {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(scan_tracker.limit(), scan_tracker.current());
drop(scan_guard);
assert_eq!(0, scan_tracker.current());
// Keep the previous execution's pool exhausted while replay uses a fresh pool.
other.try_grow(1024 * 1024).unwrap();
let context = store_api::region_engine::QueryScanContext::default();
scanner.reset_state();
assert_eq!("two_phase", scanner.mode());
assert_eq!(
vec![1, 0, 0],
scanner
.properties()
.partitions
.iter()
.map(Vec::len)
.collect::<Vec<_>>()
);
let replay_batches = try_join_all((0..3).map(|partition| {
let stream = scanner
.scan_partition(&context, &metrics_set, partition)
.unwrap();
async move { stream.try_collect::<Vec<_>>().await }
}))
.await
.unwrap();
let mut replay_rows = Vec::new();
for batches in replay_batches {
for batch in batches {
let tags = batch.column_by_name("tag_0").unwrap();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<UInt64Type>();
let timestamps = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
replay_rows.push((
datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string(),
fields.value(row),
timestamps.value(row),
));
}
}
}
replay_rows.sort();
assert_eq!(actual_rows, replay_rows);
// Dropping every partition must let the shared distributor release its pool.
scanner.reset_state();
let cancelled_context = store_api::region_engine::QueryScanContext::default();
let cancelled_pool = Arc::downgrade(&cancelled_context.memory_pool);
let streams = (0..3)
.map(|partition| {
scanner
.scan_partition(&cancelled_context, &metrics_set, partition)
.unwrap()
})
.collect::<Vec<_>>();
drop(streams);
drop(cancelled_context);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while cancelled_pool.upgrade().is_some() {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
scanner.reset_state();
let direct_batches = scanner
.build_stream()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert_eq!(
actual_rows.len(),
direct_batches
.iter()
.map(|batch| batch.num_rows())
.sum::<usize>()
);
// Exercise precise field/time filtering and candidate tag filtering on both paths.
let filtered = engine
.scanner(
region_id,
ScanRequest {
projection: Some(vec![2, 4, 5]),
filters: vec![
col("tag_0").eq(lit("a")),
col("field_0").eq(lit(11_u64)),
col("ts").eq(lit(ScalarValue::TimestampMillisecond(Some(1000), None))),
],
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
let batches = filtered
.scan()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert_eq!(
1,
batches.iter().map(|batch| batch.num_rows()).sum::<usize>()
);
if use_range_index {
// Enabled queries must read the cataloged index; disabled queries must
// succeed even when that file is unavailable.
let region = engine.find_region(region_id).unwrap();
let version = region.series_index_version_control.current();
let file_id = *version.range_indexes.keys().next().unwrap();
region
.series_index_store
.as_ref()
.unwrap()
.delete(&crate::sst::range_index::range_index_path(
region_id, file_id,
))
.await
.unwrap();
let scanner = engine
.scanner(
region_id,
ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
if enable_range_index {
if let Ok(stream) = scanner.scan().await {
assert!(stream.try_collect::<Vec<_>>().await.is_err());
}
} else {
let batches = scanner
.scan()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let mut rows = Vec::new();
for batch in batches {
let tags = batch.column_by_name("tag_0").unwrap();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<UInt64Type>();
let timestamps = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
rows.push((
datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string(),
fields.value(row),
timestamps.value(row),
));
}
}
rows.sort();
assert_eq!(actual_rows, rows);
}
}
}
/// Runs one two-phase series scan over `filters` and returns `(tag_0, field_0, ts)` per row.
async fn two_phase_sparse_rows(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
filters: Vec<datafusion_expr::Expr>,
) -> Vec<(String, u64, i64)> {
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
filters,
..Default::default()
};
let Scanner::Series(mut scanner) = engine.scanner(region_id, request).await.unwrap() else {
panic!("sparse PerSeries request must use SeriesScan");
};
assert_eq!("two_phase", scanner.mode());
let ranges = scanner
.properties()
.partitions
.iter()
.flatten()
.copied()
.collect::<Vec<_>>();
scanner
.prepare(
PrepareRequest::default()
.with_ranges(vec![ranges])
.with_target_partitions(1),
)
.unwrap();
let metrics_set = ExecutionPlanMetricsSet::default();
let context = store_api::region_engine::QueryScanContext::default();
let batches = scanner
.scan_partition(&context, &metrics_set, 0)
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let mut rows = Vec::new();
for batch in batches {
let tags = batch.column_by_name("tag_0").unwrap();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<UInt64Type>();
let timestamps = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
rows.push((
datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string(),
fields.value(row),
timestamps.value(row),
));
}
}
rows.sort();
rows
}
/// `tsid` is a hash, so two series that share one are still two series. Candidate discovery
/// collapses them into a single identifier, so the data read must apply the tag predicates
/// instead of trusting the assignment as an exact series name.
#[tokio::test]
async fn test_two_phase_series_scan_never_reads_a_colliding_partner() {
let mut env = TestEnv::with_prefix("test_two_phase_colliding_series").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await;
let rows = [
// One tsid, two label sets.
(
new_sparse_primary_key(&["host-a", "x"], &metadata, 10, 7),
1000,
1,
),
(
new_sparse_primary_key(&["host-b", "x"], &metadata, 10, 7),
2000,
2,
),
// A distinct tsid collides with nothing.
(
new_sparse_primary_key(&["host-c", "x"], &metadata, 10, 8),
3000,
3,
),
];
put_sparse_rows(&engine, region_id, &row_schema, rows.to_vec()).await;
test_util::flush_region(&engine, region_id, None).await;
// Selecting one owner must never return the colliding partner's rows.
assert_eq!(
vec![("host-a".to_string(), 1, 1000)],
two_phase_sparse_rows(&engine, region_id, vec![col("tag_0").eq(lit("host-a"))]).await
);
// A series without a collision still answers its own selection.
assert_eq!(
vec![("host-c".to_string(), 3, 3000)],
two_phase_sparse_rows(&engine, region_id, vec![col("tag_0").eq(lit("host-c"))]).await
);
// Without a predicate the path still serves the whole assignment, colliding partner
// included: the fix applies the predicates rather than disabling the scan.
assert_eq!(
vec![
("host-a".to_string(), 1, 1000),
("host-b".to_string(), 2, 2000),
("host-c".to_string(), 3, 3000),
],
two_phase_sparse_rows(&engine, region_id, Vec::new()).await
);
engine.stop().await.unwrap();
}
/// Scans all partitions in round-robin fashion and returns rows sorted by (tag, ts).
/// Also asserts that each series appears in only one partition.
async fn collect_partition_rows_round_robin(
scanner: &dyn RegionScanner,
num_partitions: usize,
) -> Vec<(String, f64, i64)> {
let metrics_set = ExecutionPlanMetricsSet::default();
let mut partition_batches = vec![vec![]; num_partitions];
let mut streams: Vec<_> = (0..num_partitions)
.map(|partition| {
let stream = scanner
.scan_partition(&Default::default(), &metrics_set, partition)
.unwrap();
Some(stream)
})
.collect();
let mut num_done = 0;
let mut schema = None;
// Pull streams in round-robin fashion to get the consistent output from the sender.
while num_done < num_partitions {
if schema.is_none() {
schema = Some(streams[0].as_ref().unwrap().schema().clone());
}
for i in 0..num_partitions {
let Some(mut stream) = streams[i].take() else {
continue;
};
let Some(rb) = stream.try_next().await.unwrap() else {
num_done += 1;
continue;
};
partition_batches[i].push(rb);
streams[i] = Some(stream);
}
}
let schema = schema.unwrap();
collect_and_assert_partition_rows(schema, partition_batches)
}
/// Collects rows sorted by (tag, ts) from partition batches.
/// Also asserts that each series appears in only one partition.
fn collect_and_assert_partition_rows(
schema: datatypes::schema::SchemaRef,
partition_batches: Vec<Vec<common_recordbatch::RecordBatch>>,
) -> Vec<(String, f64, i64)> {
let mut series_to_partition = BTreeMap::new();
let mut actual_rows = Vec::new();
for (partition, batches) in partition_batches.into_iter().enumerate() {
let batches = RecordBatches::try_new(schema.clone(), batches).unwrap();
let mut partition_series = Vec::new();
for batch in batches.iter() {
let tags = batch.column_by_name("tag_0").unwrap();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<Float64Type>();
let ts = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
let tag = datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string();
let field = fields.value(row);
let ts = ts.value(row);
partition_series.push(tag.clone());
actual_rows.push((tag, field, ts));
}
}
partition_series.sort();
partition_series.dedup();
for tag in partition_series {
let prev = series_to_partition.insert(tag.clone(), partition);
assert_eq!(
None, prev,
"series {tag} appears in multiple partitions: {prev:?} and {partition}"
);
}
}
actual_rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
actual_rows
}
/// Tests series scan with multiple partition ranges (each with multiple overlapping sources)
/// and small semaphore permits (controlled by num_partitions).
#[tokio::test]
async fn test_series_scan_flat_small_permits() {
let mut env = TestEnv::with_prefix("test_series_scan_small_permits").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.time_window", "1h")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Create overlapping SSTs in each time window so partition ranges have multiple sources.
let put_flush_rows = async |start, end| {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
};
// Window 0 (0s-999s): 3 overlapping SSTs
put_flush_rows(0, 3).await;
put_flush_rows(1, 5).await;
put_flush_rows(3, 7).await;
// Window 1 (3600s-4599s): 2 overlapping SSTs
put_flush_rows(3600, 3603).await;
put_flush_rows(3601, 3605).await;
// Window 2 (7200s-8199s): 2 overlapping SSTs
put_flush_rows(7200, 7203).await;
put_flush_rows(7201, 7204).await;
let mut expected_rows = Vec::new();
for value in [
0_i64, 1, 2, 3, 4, 5, 6, 3600, 3601, 3602, 3603, 3604, 7200, 7201, 7202, 7203,
] {
expected_rows.push((value.to_string(), value as f64, value * 1000));
}
expected_rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
// Test with different semaphore sizes (num_partitions controls Semaphore::new(num_partitions)).
for num_partitions in [1, 2] {
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(mut scanner) = scanner else {
panic!("Scanner should be series scan");
};
// Collect all partition ranges and redistribute into `num_partitions` partitions.
let raw_ranges: Vec<_> = scanner
.properties()
.partitions
.iter()
.flatten()
.cloned()
.collect();
assert!(
raw_ranges.len() >= 3,
"expected at least 3 partition ranges, got {}",
raw_ranges.len()
);
let mut new_ranges = vec![vec![]; num_partitions];
for (i, range) in raw_ranges.into_iter().enumerate() {
new_ranges[i % num_partitions].push(range);
}
scanner
.prepare(PrepareRequest {
ranges: Some(new_ranges),
..Default::default()
})
.unwrap();
let actual_rows = collect_partition_rows_round_robin(&scanner, num_partitions).await;
assert_eq!(
expected_rows, actual_rows,
"mismatch with num_partitions={num_partitions}"
);
}
}
/// Regression test: `ts = a OR ts = b` extracts to a `TimestampRange` that
/// `GenericRange::or` widens into `[min(a, b), max(a, b) + 1)`. Two such
/// predicates with different `a` values can both extract to ranges that cover
/// the same partition while selecting different (or no) rows. The previous
/// cover check would strip both predicates from the cache key, letting the
/// second scan return the first scan's cached row.
#[tokio::test]
async fn test_range_cache_separates_or_equality_time_filters() {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
// Explicitly enable the range result cache: the bug only reproduces
// when the second scan can replay the first scan's cached batches.
range_result_cache_size: ReadableSize::mb(64),
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Partition rows ts=5..10 (5000ms..9000ms), flushed to SST.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(5, 10),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let ts_lit = |ms: i64| lit(ScalarValue::TimestampMillisecond(Some(ms), None));
let tag_filter = || col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("0".to_string()))));
// First scan: (ts = 5000) OR (ts = 100000) -- extracts to `[5000, 100001)`,
// which covers the partition `[5000, 9000]`. Selects ts=5.
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![
tag_filter(),
col("ts").eq(ts_lit(5000)).or(col("ts").eq(ts_lit(100000))),
],
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let expected_first = "\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 5 | 5.0 | 1970-01-01T00:00:05 |
+-------+---------+---------------------+";
assert_eq!(expected_first, batches.pretty_print().unwrap());
// Second scan: (ts = 3000) OR (ts = 100000) -- extracts to `[3000, 100001)`,
// which also covers the partition. Selects nothing. With the buggy cover
// check both scans built the same cache key (tag filter only), so this scan
// would replay the first scan's cached row and incorrectly return ts=5.
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![
tag_filter(),
col("ts").eq(ts_lit(3000)).or(col("ts").eq(ts_lit(100000))),
],
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let row_count: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(
0,
row_count,
"expected empty result, got: {}",
batches.pretty_print().unwrap()
);
}
#[tokio::test]
async fn test_exact_sequence_read_compacted_sst_with_preserve_row_sequence() {
let mut env = TestEnv::new().await;
// Keep the explicit compaction below as the only compaction, so this test
// proves that the files are rewritten rather than observing an earlier
// background compaction.
let engine = env
.create_engine(MitoConfig {
min_compaction_interval: std::time::Duration::from_secs(60 * 60),
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
env.get_schema_metadata_manager()
.register_region_table_info(
region_id.table_id(),
"test_table",
"test_catalog",
"test_schema",
None,
env.get_kv_backend(),
)
.await;
let request = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "2")
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Flush 3 SSTs so the twcs compaction (trigger file num 2) can merge them.
for (start, end) in [(0, 3), (3, 6), (6, 9)] {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
}
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest::default()),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let output_files = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(1, output_files.len(), "three input SSTs must be rewritten");
assert!(output_files[0].meta_ref().preserve_row_sequence);
// The compacted SST still preserves per-row sequences: the exact (2, 7] range
// returns rows with sequence 3..=7 even though C and H are older than the
// flushed frontier (which would normally fail the stale fences).
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: Some(2),
memtable_max_sequence: Some(7),
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
batches.pretty_print().unwrap(),
"\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 2 | 2.0 | 1970-01-01T00:00:02 |
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
| 6 | 6.0 | 1970-01-01T00:00:06 |
+-------+---------+---------------------+"
);
}
/// P0 regression: historical MemtableOnly reads must keep every fence even when
/// the region preserves per-row sequences. The exact capability is only granted
/// to the explicit `sequence_range` mode; a memtable-only scan whose checkpoint
/// is behind the flushed frontier must stay stale instead of silently returning
/// an incomplete delta.
#[tokio::test]
async fn test_exact_sequence_read_memtable_only_keeps_fences_with_preserve_option() {
let mut env = TestEnv::with_prefix("test_exact_sequence_read_memtable_only_keeps_fences").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(3),
skip_sst_files: true,
..Default::default()
},
)
.await
.err()
.expect("expected stale cursor error for memtable-only after flush");
assert!(
matches!(err, Error::IncrementalQueryStale { .. }),
"unexpected err: {err}"
);
}
/// SequenceRange mode on a region without preserve_row_sequence:
/// the exact capability is unavailable, both bounds are enforceable, so the
/// engine must return a structured unsupported error instead of approximating.
#[tokio::test]
async fn test_exact_sequence_range_unsupported_when_option_off() {
let mut env = TestEnv::with_prefix("test_exact_sequence_range_unsupported_option_off").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
// Bounds (3, 4] are both >= flushed frontier (3), so neither fence fires;
// the region still cannot serve exact row-level filtering -> unsupported.
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(3),
memtable_max_sequence: Some(4),
exact_sequence_range: true,
..Default::default()
},
)
.await
.err()
.expect("expected sequence-range unsupported error");
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"unexpected err: {err}"
);
assert_eq!(err.status_code(), StatusCode::Unsupported);
// A stale checkpoint still yields the structured stale error (rebind path).
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(4),
exact_sequence_range: true,
..Default::default()
},
)
.await
.err()
.expect("expected stale cursor error");
assert!(
matches!(err, Error::IncrementalQueryStale { .. }),
"unexpected err: {err}"
);
}
/// SequenceRange mode when a legacy file without the preserved-sequence marker
/// is present: exact capability unavailable -> structured unsupported error.
#[tokio::test]
async fn test_exact_sequence_range_unsupported_when_legacy_file() {
let mut env = TestEnv::with_prefix("test_exact_sequence_range_unsupported_legacy_file").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
// Inject a legacy file without the preserved-sequence marker. The region
// edit handler fills its max sequence with `committed + 1` (4), which is
// greater than C=3: the unmarked file may still contain in-range rows, so
// the exact capability is unavailable and the scan must fail with the
// structured unsupported error. (An unmarked file with an unknown max
// sequence fails closed in `files_allow_exact_sequence_range`, covered by
// the unit test.)
let edit = RegionEdit {
files_to_add: vec![FileMeta {
region_id,
file_id: FileId::random(),
time_range: (
Timestamp::new_millisecond(0),
Timestamp::new_millisecond(1000),
),
level: 0,
file_size: 0,
max_row_group_uncompressed_size: 0,
available_indexes: Default::default(),
indexes: vec![],
index_file_size: 0,
index_version: 0,
num_rows: 0,
num_row_groups: 0,
sequence: None,
partition_expr: None,
num_series: 0,
preserve_row_sequence: false,
..Default::default()
}],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
};
// Absorb the file through a flush-shaped edit, which is how a legacy unmarked
// SST appears.
let region = engine.get_region(region_id).unwrap();
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(3),
memtable_max_sequence: Some(4),
exact_sequence_range: true,
..Default::default()
},
)
.await
.err()
.expect("expected sequence-range unsupported error");
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"unexpected err: {err}"
);
assert_eq!(err.status_code(), StatusCode::Unsupported);
}
/// Region edit assigns a target-local barrier to an imported foreign SST, so
/// exact sequence-range capability can admit it without trusting its source
/// region marker: below the barrier the edit layer cannot disprove that the rows
/// were renumbered, so the read stays unsupported; at the barrier the file is
/// provably consumed.
#[tokio::test]
async fn test_exact_sequence_range_gates_foreign_file_with_barrier() {
let mut env = TestEnv::with_prefix("test_exact_sequence_range_gates_foreign_file").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![FileMeta {
region_id: RegionId::new(1, 2),
file_id: FileId::random(),
time_range: (
Timestamp::new_millisecond(0),
Timestamp::new_millisecond(1000),
),
level: 0,
file_size: 0,
max_row_group_uncompressed_size: 0,
available_indexes: Default::default(),
indexes: vec![],
index_file_size: 0,
index_version: 0,
num_rows: 0,
num_row_groups: 0,
sequence: None,
partition_expr: None,
num_series: 0,
preserve_row_sequence: true,
..Default::default()
}],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
let version = engine.get_region(region_id).unwrap().version();
let foreign_file = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.find(|file| file.region_id() != region_id)
.expect("foreign file should remain source-owned");
assert!(
foreign_file.meta_ref().sequence.is_some(),
"region edit must assign a target-local barrier"
);
// The edit allocated `last_sequence + 1` = 4 as the file barrier: a cursor at 3
// cannot prove the adopted rows are consumed.
let boundary = foreign_file
.meta_ref()
.sequence
.map(|sequence| sequence.get())
.expect("region edit assigned the barrier");
assert_eq!(4, boundary);
engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(boundary - 1),
memtable_max_sequence: Some(boundary),
exact_sequence_range: true,
..Default::default()
},
)
.await
.expect("a cursor below the file barrier is served by row-level filtering");
// The stale-cursor rejection went away with `last_invalid_seq`: the adopted file's own
// barrier keeps the exact range available, so the rows are filtered row by row instead
// of the whole read being refused.
// At the boundary the foreign file is provably fully consumed, so it cannot
// break the exact capability even though its source marker is foreign.
engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(boundary),
memtable_max_sequence: Some(boundary + 1),
exact_sequence_range: true,
..Default::default()
},
)
.await
.expect("foreign file with target barrier should be exact-capable at the boundary");
}
/// Exact sequence-range reads only require preserved row sequences in the
/// SSTs selected by their time range. A legacy SST outside that range cannot
/// contain a row in `(C, H]` for this request.
#[tokio::test]
async fn test_exact_sequence_range_ignores_time_pruned_unmarked_sst() {
let mut env =
TestEnv::with_prefix("test_exact_sequence_range_ignores_time_pruned_unmarked_sst").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// The old, unmarked SST covers timestamps 0s..2s.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::SetRegionOptions {
options: vec![SetRegionOption::PreserveRowSequence(true)],
},
}),
)
.await
.unwrap();
// The selected SST covers timestamps 10s..12s and carries the marker.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(10, 13),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![
col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(10_000), None))),
],
memtable_min_sequence: Some(3),
memtable_max_sequence: Some(6),
exact_sequence_range: true,
..Default::default()
},
)
.await
.expect("time-pruned unmarked SST must not disable exact reads");
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
3,
batches.iter().map(|batch| batch.num_rows()).sum::<usize>()
);
}
/// Regression for #8865: a legacy (unmarked) SST written before the preserve
/// option was enabled is excluded from exact scans once Flow's cursor reaches
/// its admission barrier. A newer barrier still fails closed; normal scans
/// continue to return every row.
#[tokio::test]
async fn test_exact_sequence_after_enable_with_old_unmarked_sst() {
let mut env =
TestEnv::with_prefix("test_exact_sequence_after_enable_with_old_unmarked_sst").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Old data flushed while the option was off: unmarked SST with max seq 3.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
// Enable the preserve option; later flushes carry the marker.
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::SetRegionOptions {
options: vec![SetRegionOption::PreserveRowSequence(true)],
},
}),
)
.await
.unwrap();
// New marked data: seq 4..9 in two flushed SSTs.
for (start, end) in [(3, 6), (6, 9)] {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
let mut markers = engine
.get_region(region_id)
.unwrap()
.version()
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.map(|file| file.meta_ref().preserve_row_sequence)
.collect::<Vec<_>>();
markers.sort_unstable();
assert_eq!(vec![false, true, true], markers);
// The legacy file's barrier is 3, so C=9 excludes it and the marked SSTs
// are row-level filtered normally.
let scanner = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(9),
memtable_max_sequence: Some(10),
exact_sequence_range: true,
..Default::default()
},
)
.await
.expect("barrier should permit the exact scan");
assert_eq!(0, scanner.num_files(), "barrier file must be skipped");
// Normal scans still return everything.
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(9, batches.iter().map(|b| b.num_rows()).sum::<usize>());
}
/// Exact sequence-range mode must read every time-matching SST, so the legacy
/// `sst_min_sequence` file-pruning hint is incompatible: it could silently skip
/// a preserved file that still contains rows inside `(min, max]`. The request
/// must be rejected with the structured unsupported error, not approximated.
#[tokio::test]
async fn test_exact_sequence_range_rejects_sst_min_sequence_hint() {
let mut env =
TestEnv::with_prefix("test_exact_sequence_range_rejects_sst_min_sequence_hint").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
// Non-trivial `sst_min_sequence` hint combined with an exact range: the
// pruning hint could drop the preserved file (whose max sequence is 3)
// for lower thresholds, losing in-range rows, so reject explicitly.
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(1),
sst_min_sequence: Some(2),
exact_sequence_range: true,
..Default::default()
},
)
.await
.err()
.expect("expected sequence-range unsupported error");
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"unexpected err: {err}"
);
assert_eq!(err.status_code(), StatusCode::Unsupported);
// Without the hint the exact scan must still read the SST (no data loss).
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(1),
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let row_count: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(1, row_count, "expected seq 1 only");
}
/// Exact `(0, 1]` scans must not let the row-group-level `LastRow` shortcut drop
/// in-range rows: a series with seq 1 at t1 and seq 2 at t2 must return seq 1
/// (t1) instead of being reduced to seq 2 (t2) and then filtered out. Non-exact
/// `LastRow` scans keep their existing behavior (only the last row per series).
#[tokio::test]
async fn test_exact_sequence_read_with_last_row_selector_keeps_in_range_rows() {
let mut env = TestEnv::with_prefix("test_exact_sequence_read_with_last_row_selector").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Same series/tag: seq 1 at t1 (field 1.0), seq 2 at t2 (field 2.0).
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows_for_key("series", 1, 3, 1),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
let scan = async |request: ScanRequest| -> String {
let stream = engine.scan_to_stream(region_id, request).await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
batches.pretty_print().unwrap()
};
// Exact (0, 1] with the LastRow selector: seq 1 (t1) must survive the
// row-level sequence filter and be selected as the last row.
assert_eq!(
"\
+--------+---------+---------------------+
| tag_0 | field_0 | ts |
+--------+---------+---------------------+
| series | 1.0 | 1970-01-01T00:00:01 |
+--------+---------+---------------------+",
scan(ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(1),
exact_sequence_range: true,
series_row_selector: Some(TimeSeriesRowSelector::LastRow { after_merge: false }),
..Default::default()
})
.await
);
// Non-exact LastRow scan (no regression): still returns only the last row
// of the series, seq 2 (t2).
assert_eq!(
"\
+--------+---------+---------------------+
| tag_0 | field_0 | ts |
+--------+---------+---------------------+
| series | 2.0 | 1970-01-01T00:00:02 |
+--------+---------+---------------------+",
scan(ScanRequest {
series_row_selector: Some(TimeSeriesRowSelector::LastRow { after_merge: false }),
..Default::default()
})
.await
);
}
/// Exact delta spanning both SSTs and the memtable: rows after C that are partly
/// flushed and partly still in the memtable must all be returned, with the H
/// watermark respected.
#[tokio::test]
async fn test_exact_sequence_read_partial_sst_partial_memtable() {
let mut env =
TestEnv::with_prefix("test_exact_sequence_read_partial_sst_partial_memtable").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// seq 1..3 flushed into an SST.
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
// seq 4..6 stay in the memtable.
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 6),
};
test_util::put_rows(&engine, region_id, rows).await;
let scan_exact = async |min: Option<u64>, max: Option<u64>| -> String {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: min,
memtable_max_sequence: max,
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
batches.pretty_print().unwrap()
};
// The merged output order across SST + memtable sources is not guaranteed,
// and each source batch repeats the pretty-printed header row, so compare
// only the data rows (excluding header/separator lines).
let result = scan_exact(Some(2), Some(6)).await;
let mut rows = result
.lines()
.filter(|l| l.starts_with("| ") && !l.starts_with("| tag_0 "))
.collect::<Vec<_>>();
rows.sort_unstable();
assert_eq!(
vec![
"| 2 | 2.0 | 1970-01-01T00:00:02 |",
"| 3 | 3.0 | 1970-01-01T00:00:03 |",
"| 4 | 4.0 | 1970-01-01T00:00:04 |",
"| 5 | 5.0 | 1970-01-01T00:00:05 |",
],
rows,
"unexpected set for (2, 6]:\n{result}"
);
}
/// Builds a bulk insert request with rows `[start, end)` in the flat schema.
fn build_bulk_insert_request(
region_id: RegionId,
start: usize,
end: usize,
) -> RegionBulkInsertsRequest {
let schema = Arc::new(Schema::new(vec![
Field::new("tag_0", DataType::Utf8, true),
Field::new("field_0", DataType::Float64, true),
Field::new(
"ts",
DataType::Timestamp(TimeUnit::Millisecond, None),
false,
),
]));
let tag = Arc::new(StringArray::from_iter_values(
(start..end).map(|value| value.to_string()),
)) as ArrayRef;
let field = Arc::new(Float64Array::from_iter_values(
(start..end).map(|value| value as f64),
)) as ArrayRef;
let ts = Arc::new(TimestampMillisecondArray::from_iter_values(
(start..end).map(|value| value as i64 * 1000),
)) as ArrayRef;
let payload = DfRecordBatch::try_new(schema, vec![tag, field, ts]).unwrap();
let (schema, record_batch) = encode_to_flight_data(payload.clone());
RegionBulkInsertsRequest {
skip_wal: false,
region_id,
payload,
raw_data: ArrowIpc {
schema: schema.data_header,
data_header: record_batch.data_header,
payload: record_batch.data_body,
},
partition_expr_version: None,
aligned_schema_version: None,
}
}
#[tokio::test]
async fn test_bulk_skip_wal_recovery() {
check_bulk_skip_wal_recovery(false, false, false).await;
check_bulk_skip_wal_recovery(false, true, false).await;
check_bulk_skip_wal_recovery(true, false, false).await;
check_bulk_skip_wal_recovery(true, true, false).await;
}
#[tokio::test]
async fn test_bulk_skip_wal_close_recovery() {
check_bulk_skip_wal_recovery(false, false, true).await;
check_bulk_skip_wal_recovery(false, true, true).await;
check_bulk_skip_wal_recovery(true, false, true).await;
check_bulk_skip_wal_recovery(true, true, true).await;
}
async fn check_bulk_skip_wal_recovery(skip_wal: bool, flush: bool, close: bool) {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("memtable.type", "bulk")
.build();
let table_dir = request.table_dir.clone();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let mut request = build_bulk_insert_request(region_id, 0, 4);
request.skip_wal = skip_wal;
let affected = engine
.handle_request(region_id, RegionRequest::BulkInserts(request))
.await
.unwrap();
assert_eq!(affected.affected_rows, 4);
let region = engine.get_region(region_id).unwrap();
let current = region.version_control.current();
assert_eq!(current.committed_sequence, 4);
assert_eq!(current.last_entry_id, u64::from(!skip_wal));
assert_eq!(current.version.flushed_entry_id, 0);
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
assert_eq!(
RecordBatches::try_collect(stream)
.await
.unwrap()
.iter()
.map(|b| b.num_rows())
.sum::<usize>(),
4
);
if flush {
test_util::flush_region(&engine, region_id, None).await;
let current = region.version_control.current();
assert_eq!(current.last_entry_id, u64::from(!skip_wal));
assert_eq!(current.version.flushed_sequence, 4);
assert_eq!(
engine
.region_statistic(region_id)
.unwrap()
.manifest
.data_flushed_entry_id(),
u64::from(!skip_wal)
);
}
let engine = if close {
reopen_region(&engine, region_id, table_dir, false, HashMap::new()).await;
assert_eq!(
region.version().flushed_sequence,
if flush || skip_wal { 4 } else { 0 }
);
engine
} else {
// Stopping the engine directly exercises recovery without close-time flush.
let engine = env.reopen_engine(engine, MitoConfig::default()).await;
engine
.handle_request(
region_id,
RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir,
path_type: store_api::region_request::PathType::Bare,
options: HashMap::new(),
skip_wal_replay: false,
checkpoint: None,
requirements: Default::default(),
}),
)
.await
.unwrap();
engine
};
assert!(
!engine
.get_region(region_id)
.unwrap()
.version()
.memtables
.has_skip_wal_writes()
);
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
assert_eq!(
RecordBatches::try_collect(stream)
.await
.unwrap()
.iter()
.map(|b| b.num_rows())
.sum::<usize>(),
if skip_wal && !flush && !close { 0 } else { 4 }
);
}
#[tokio::test]
async fn test_bulk_skip_wal_flush_watermarks() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
engine
.handle_request(
region_id,
RegionRequest::Create(
CreateRequestBuilder::new()
.insert_option("memtable.type", "bulk")
.build(),
),
)
.await
.unwrap();
// Establish a persisted baseline, skip one bulk write, then resume WAL.
for (round, skip_wal) in [false, true, false].into_iter().enumerate() {
let region = engine.get_region(region_id).unwrap();
let before = region.version_control.current();
let mut request = build_bulk_insert_request(region_id, round * 4, (round + 1) * 4);
request.skip_wal = skip_wal;
let affected = engine
.handle_request(region_id, RegionRequest::BulkInserts(request))
.await
.unwrap();
assert_eq!(affected.affected_rows, 4);
let expected_entry_id = before.last_entry_id + u64::from(!skip_wal);
let after = region.version_control.current();
assert_eq!(after.last_entry_id, expected_entry_id);
assert_eq!(after.committed_sequence, before.committed_sequence + 4);
assert_eq!(
after.version.flushed_sequence,
before.version.flushed_sequence
);
assert_eq!(
engine
.region_statistic(region_id)
.unwrap()
.manifest
.data_flushed_entry_id(),
before.version.flushed_entry_id
);
test_util::flush_region(&engine, region_id, None).await;
let after = region.version_control.current();
assert_eq!(after.last_entry_id, expected_entry_id);
assert_eq!(after.version.flushed_sequence, (round as u64 + 1) * 4);
assert_eq!(
engine
.region_statistic(region_id)
.unwrap()
.manifest
.data_flushed_entry_id(),
expected_entry_id
);
}
}
/// Bulk parts fold per-part sequences (commit-unit granularity): an exact range
/// keeps or drops each whole part. The same set must hold before and after flush.
#[tokio::test]
async fn test_exact_sequence_read_bulk_parts() {
let mut env = TestEnv::with_prefix("test_exact_sequence_read_bulk_parts").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("memtable.type", "bulk")
.build();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Two bulk parts: [0,3) and [3,6). Each part carries one folded sequence.
engine
.handle_request(
region_id,
RegionRequest::BulkInserts(build_bulk_insert_request(region_id, 0, 3)),
)
.await
.unwrap();
engine
.handle_request(
region_id,
RegionRequest::BulkInserts(build_bulk_insert_request(region_id, 3, 6)),
)
.await
.unwrap();
let scan_exact = async |min: Option<u64>, max: Option<u64>| -> String {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: min,
memtable_max_sequence: max,
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
batches.pretty_print().unwrap()
};
let expected_all = "\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
+-------+---------+---------------------+";
// A wide range covering every folded part sequence returns all rows.
assert_eq!(expected_all, scan_exact(Some(0), Some(100)).await);
// Commit-unit granularity: a lower bound that excludes the first part's
// folded sequence drops the whole first part, keeps the second.
let scan = scan_exact(Some(2), Some(100)).await;
assert!(
!scan.contains("| 0 ") && !scan.contains("| 1 ") && !scan.contains("| 2 "),
"first bulk part should be fully excluded, got:\n{scan}"
);
assert!(scan.contains("| 3 "), "second bulk part missing:\n{scan}");
test_util::flush_region(&engine, region_id, None).await;
assert_eq!(scan_exact(Some(2), Some(100)).await, scan);
}
/// Bulk commit publication ordering: the committed sequence must never cover a
/// bulk part before its rows are physically installed in the memtable. A scan
/// opening in the window between ordinary-memtable handling and bulk
/// installation binds H to the pre-bulk committed sequence, sees no bulk rows,
/// and a follow-up exact scan over the fresh range returns the bulk rows once.
#[tokio::test]
async fn test_bulk_write_sequence_not_committed_before_install() {
let mut env =
TestEnv::with_prefix("test_bulk_write_sequence_not_committed_before_install").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("memtable.type", "bulk")
.build();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let committed_sequence = || {
engine
.find_region(region_id)
.unwrap()
.find_committed_sequence()
};
assert_eq!(0, committed_sequence());
let mut barrier = crate::region_write_ctx::test_hooks::arm_bulk_install_barrier(
region_id,
engine
.get_region(region_id)
.unwrap()
.version_control
.clone(),
);
// Start a bulk write in the background; it pauses before installation.
let engine_clone = engine.clone();
let write_handle = tokio::spawn(async move {
engine_clone
.handle_request(
region_id,
RegionRequest::BulkInserts(build_bulk_insert_request(region_id, 0, 3)),
)
.await
.unwrap();
});
// Wait until the write paused between memtable handling and bulk install.
tokio::time::timeout(
std::time::Duration::from_secs(10),
barrier.wait_until_reached(),
)
.await
.expect("bulk write never reached the install barrier");
// Open the snapshot-bound scanner while the write is still paused at the
// barrier: it must bind H to the pre-bulk committed sequence (0) because
// the bulk part is not installed yet.
let scanner = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
snapshot_on_scan: true,
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
assert_eq!(
Some(0),
scanner.snapshot_sequence(),
"snapshot-bound scan must bind H to the pre-bulk committed sequence"
);
// The committed sequence must still be the pre-bulk value: publication
// happens strictly after the bulk part is in the memtable.
assert_eq!(
0,
committed_sequence(),
"committed sequence leaked before the bulk part was installed"
);
// Release the barrier: the bulk part installs and the committed sequence
// advances to cover it.
barrier.release();
write_handle.await.expect("bulk write should complete");
assert_eq!(3, committed_sequence());
// The scanner opened while paused stays bound at the pre-bulk H and so
// sees no bulk rows.
let stream = scanner.scan().await.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
0,
batches.iter().map(|b| b.num_rows()).sum::<usize>(),
"bulk rows visible to a snapshot bound before installation:\n{}",
batches.pretty_print().unwrap()
);
// The follow-up exact scan over (pre_H, post_H] returns the bulk rows once.
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(3),
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
3,
batches.iter().map(|b| b.num_rows()).sum::<usize>(),
"bulk rows must be returned exactly once:\n{}",
batches.pretty_print().unwrap()
);
let pretty = batches.pretty_print().unwrap();
for tag in ["0", "1", "2"] {
assert!(
pretty.contains(&format!("| {tag} ")),
"bulk row {tag} missing from (0, 3]:\n{pretty}"
);
}
}
/// Compaction must not allocate a new sequence that can collide with the next
/// write. Preserve the input's effective row sequence and file-level bound.
#[tokio::test]
async fn test_non_preserve_compaction_sequence_collision() {
for flat_format in [false, true] {
test_non_preserve_compaction_sequence_collision_with_format(flat_format).await;
}
}
async fn test_non_preserve_compaction_sequence_collision_with_format(flat_format: bool) {
let mut env = TestEnv::with_prefix("test_non_preserve_compaction_sequence_collision").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat_format,
min_compaction_interval: std::time::Duration::from_secs(60 * 60),
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "2")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
async fn last_row(engine: &crate::engine::MitoEngine, region_id: RegionId) -> String {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
series_row_selector: Some(TimeSeriesRowSelector::LastRow {
after_merge: false,
}),
..Default::default()
},
)
.await
.unwrap();
RecordBatches::try_collect(stream)
.await
.unwrap()
.pretty_print()
.unwrap()
}
// SST1 and SST2 contain the same key and timestamp. Their physical/file
// sequences are 1 and 2, so ordinary LastRow selects value 2.
for value in [1, 2] {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key("a", 0, 1, value),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
let before = last_row(&engine, region_id).await;
assert!(
before.contains("| a | 2.0"),
"before compaction: {before}"
);
// Both current SSTs are compacted through the real picker, merger, writer,
// and manifest update. Both the row version and inherited file bound stay 2.
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest::default()),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let files = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(1, files.len(), "both input SSTs must be replaced");
let compacted = files[0];
assert_eq!(1, compacted.meta_ref().level);
assert!(!compacted.meta_ref().preserve_row_sequence);
assert_eq!(1, compacted.num_rows());
assert_eq!(
Some(std::num::NonZeroU64::new(2).unwrap()),
compacted.meta_ref().sequence,
"compaction must inherit the input bound without allocating a sequence"
);
// Hide FileMeta.sequence so this is a direct physical read, not a reader
// override. The output must contain physical sequence 2, not zero or 3.
let mut physical_meta = compacted.meta_ref().clone();
physical_meta.sequence = None;
let mut reader = region
.access_layer
.read_sst(FileHandle::new(
physical_meta,
Arc::new(crate::sst::file_purger::NoopFilePurger),
))
.build()
.await
.unwrap()
.expect("compaction output reader");
let batch = reader.next_record_batch().await.unwrap().unwrap();
let sequences = batch
.column(batch.num_columns() - 2)
.as_any()
.downcast_ref::<datatypes::arrow::array::UInt64Array>()
.unwrap();
assert_eq!(&[2], sequences.values());
let after_compaction = last_row(&engine, region_id).await;
assert!(
after_compaction.contains("| a | 2.0"),
"after compaction: {after_compaction}"
);
// The next write receives sequence 3 and must win. The old zero/barrier
// encoding promoted the compacted row to 3 and could incorrectly retain 2.
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: test_util::build_rows_for_key("a", 0, 1, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let files = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(2, files.len(), "compacted L1 plus newest L0 SST");
let newest = files
.iter()
.find(|file| file.meta_ref().level == 0)
.expect("newest L0 SST");
assert_eq!(1, newest.num_rows());
assert_eq!(
Some(std::num::NonZeroU64::new(3).unwrap()),
newest.meta_ref().sequence
);
let compacted = files
.iter()
.find(|file| file.meta_ref().level == 1)
.expect("compacted L1 SST");
assert_eq!(
Some(std::num::NonZeroU64::new(2).unwrap()),
compacted.meta_ref().sequence
);
let after_newer_write = last_row(&engine, region_id).await;
assert!(
after_newer_write.contains("| a | 3.0"),
"after newer sequence-3 write: {after_newer_write}"
);
}
/// A legacy input must retain its admission boundary without gaining row trust.
/// A later flush can advance beyond manifest.committed_sequence, so compaction
/// must inherit the maximum input bound rather than sample that stale frontier.
#[rstest::rstest]
#[tokio::test]
async fn test_compaction_output_non_preserve_not_laundered_from_legacy_input(
#[values(false, true)] flat_format: bool,
#[values(false, true)] flush_after_edit: bool,
) {
let mut env =
TestEnv::with_prefix("test_compaction_output_not_laundered_from_legacy_input").await;
// Suppress automatic edit-triggered compactions. The high TWCS trigger below
// also prevents flush-triggered compaction from consuming the inputs, so the
// explicit Compact below is the only compaction in flight (deterministic).
let config = MitoConfig {
default_flat_format: flat_format,
min_compaction_interval: std::time::Duration::from_secs(60 * 60),
schedule_compaction_after_edit: false,
..Default::default()
};
let engine = env.create_engine(config.clone()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "100")
.build();
let column_schemas = test_util::rows_schema(&request);
let table_dir = request.table_dir.clone();
let region_options = request.options.clone();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Two real marked SSTs on disk so the strict-window compaction rewrites them.
for (start, end) in [(0, 3), (3, 6)] {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
}
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let level0 = &version.ssts.levels()[0].files;
assert_eq!(2, level0.len());
let first_file = level0
.values()
.next()
.expect("flushed SST")
.meta_ref()
.clone();
assert!(first_file.preserve_row_sequence);
// Seed the first physical file as a legacy (unmarked) file: replace the
// version's FileMeta so the marker is false while the file stays on disk.
let mut unmarked = first_file.clone();
unmarked.preserve_row_sequence = false;
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![unmarked],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let level0 = &version.ssts.levels()[0].files;
assert_eq!(2, level0.len());
assert!(
level0
.values()
.any(|file| !file.meta_ref().preserve_row_sequence),
"seeded file should be unmarked"
);
let mut expected_sequences = vec![1, 2, 3, 4, 5, 6];
let expected_bound = if flush_after_edit {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(6, 9),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
expected_sequences.extend([8, 9, 10]);
10
} else {
7
};
let manifest = region.manifest_ctx.manifest().await;
assert_eq!(Some(7), manifest.committed_sequence);
assert_eq!(
if flush_after_edit { 10 } else { 6 },
manifest.flushed_sequence
);
// Compact: the rewritten output must NOT be laundered back to marked.
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 60,
}),
parallelism: None,
time_range: None,
}),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let outputs = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(
1,
outputs.len(),
"all inputs should rewrite into one output file"
);
assert!(
!outputs[0].meta_ref().preserve_row_sequence,
"legacy input must not be laundered into a marked output"
);
// Inherit the admitted legacy bound and, if present, the newer flush bound.
let barrier = outputs[0]
.meta_ref()
.sequence
.expect("compaction output barrier")
.get();
assert_eq!(expected_bound, barrier);
// Reinstalling the legacy input assigns its metadata sequence 7, but the
// existing rows keep sequences 1..=6. Compaction must not rewrite them to
// the metadata bound, including when newer flushed rows join the merge.
let mut sequence_meta = outputs[0].meta_ref().clone();
sequence_meta.sequence = None;
let sequence_handle = FileHandle::new(
sequence_meta,
Arc::new(crate::sst::file_purger::NoopFilePurger),
);
let mut reader = region
.access_layer
.read_sst(sequence_handle)
.build()
.await
.unwrap()
.expect("compaction output reader");
let mut sequences = Vec::new();
while let Some(batch) = reader.next_record_batch().await.unwrap() {
let sequence = batch
.column(batch.num_columns() - 2)
.as_any()
.downcast_ref::<datatypes::arrow::array::UInt64Array>()
.expect("sequence column");
sequences.extend_from_slice(sequence.values());
}
sequences.sort_unstable();
assert_eq!(expected_sequences, sequences);
// The inherited bound and untrusted marker must survive manifest recovery.
let engine = env.reopen_engine(engine, config).await;
test_util::reopen_region(&engine, region_id, table_dir, false, region_options).await;
let version = engine.get_region(region_id).unwrap().version();
let files: Vec<_> = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files())
.collect();
assert_eq!(1, files.len());
assert_eq!(
Some(expected_bound),
files[0].meta_ref().sequence.map(|s| s.get())
);
assert!(!files[0].meta_ref().preserve_row_sequence);
// A cursor before the barrier must fail closed.
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(barrier - 1),
memtable_max_sequence: Some(barrier),
exact_sequence_range: true,
..Default::default()
},
)
.await
.err()
.expect("newer barrier must disable exact scanning");
if flush_after_edit {
// Without exact capability, the lower-bound fence is checked first.
assert!(
matches!(
err,
Error::IncrementalQueryStale {
given_seq: 9,
min_readable_seq: 10,
..
}
),
"unexpected error: {err:?}"
);
} else {
// No flush after the edit, so the flushed frontier cannot fire. The
// edit-boundary rejection went away with `last_invalid_seq`; what is left
// is the exact-sequence rule: the adopted files carry no trusted per-row
// numbering, so the range stays unproven and the read fails closed.
assert!(
matches!(
err,
Error::SequenceRangeUnsupported {
min_seq: 6,
max_seq: 7,
..
}
),
"unexpected error: {err:?}"
);
assert_eq!(StatusCode::Unsupported, err.status_code());
}
// Once C reaches the barrier the untrusted file is skipped, so exact
// capability is restored without attempting row-level filtering.
let scanner = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(barrier),
memtable_max_sequence: Some(barrier + 1),
exact_sequence_range: true,
..Default::default()
},
)
.await
.expect("barrier should restore exact capability");
assert_eq!(0, scanner.num_files());
}
/// Multi-input primary-key-format compaction: two preserved pk-format files
/// rewrite into one output that still carries the marker, and an exact scan
/// over the compacted output returns every row in range.
#[tokio::test]
async fn test_exact_sequence_read_pk_format_compaction_multiple_inputs() {
let mut env =
TestEnv::with_prefix("test_exact_sequence_read_pk_format_compaction_multiple_inputs").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("sst_format", "primary_key")
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "100")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Two preserved pk-format input files: seq 1..3 and seq 4..6.
for (start, end) in [(0, 3), (3, 6)] {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(start, end),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
}
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 60,
}),
parallelism: None,
time_range: None,
}),
)
.await
.unwrap();
// The rewritten output still carries the preserved-sequence marker.
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let outputs = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(
1,
outputs.len(),
"two pk inputs should rewrite into one output file"
);
assert!(outputs[0].meta_ref().preserve_row_sequence);
// Exact scan over the compacted pk-format output returns all rows in range.
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: Some(1),
memtable_max_sequence: Some(5),
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let pretty = batches.pretty_print().unwrap();
for tag in ["1", "2", "3", "4"] {
assert!(
pretty.contains(&format!("| {tag} ")),
"row {tag} missing from compacted pk output:\n{pretty}"
);
}
assert_eq!(
4,
batches.iter().map(|b| b.num_rows()).sum::<usize>(),
"exact range rows:\n{pretty}"
);
assert!(
!pretty.contains("| 0 ") && !pretty.contains("| 5 "),
"rows outside (1, 5] leaked:\n{pretty}"
);
}
/// Exact sequence-range reads through the legacy `PerSeries` path: row-level
/// filtering must hold across the flushed SST and the memtable.
#[tokio::test]
async fn test_exact_sequence_read_series_scan_per_series() {
let mut env = TestEnv::with_prefix("test_exact_sequence_read_series_scan_per_series").await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// seq 1..3 flushed into an SST, seq 4..6 stay in the memtable.
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
let rows = Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 6),
};
test_util::put_rows(&engine, region_id, rows).await;
let scan_exact_series = async |min: Option<u64>, max: Option<u64>| -> String {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: min,
memtable_max_sequence: max,
exact_sequence_range: true,
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
batches.pretty_print().unwrap()
};
for (min, max) in [(Some(2), Some(6)), (Some(0), Some(2))] {
let result = scan_exact_series(min, max).await;
let mut rows = result
.lines()
.filter(|l| l.starts_with("| ") && !l.starts_with("| tag_0 "))
.collect::<Vec<_>>();
rows.sort_unstable();
let expected = if min == Some(2) {
vec![
"| 2 | 2.0 | 1970-01-01T00:00:02 |",
"| 3 | 3.0 | 1970-01-01T00:00:03 |",
"| 4 | 4.0 | 1970-01-01T00:00:04 |",
"| 5 | 5.0 | 1970-01-01T00:00:05 |",
]
} else {
vec![
"| 0 | 0.0 | 1970-01-01T00:00:00 |",
"| 1 | 1.0 | 1970-01-01T00:00:01 |",
]
};
assert_eq!(
expected, rows,
"unexpected set for ({min:?}, {max:?}]:\n{result}"
);
}
}
async fn build_sparse_exact_metric_engine(
prefix: &str,
experimental_series_scan_v2: bool,
range_result_cache_size: ReadableSize,
) -> (TestEnv, crate::engine::MitoEngine, RegionId) {
let mut env = TestEnv::with_prefix(prefix).await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2,
range_result_cache_size,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let metadata = Arc::new(sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
));
let mut request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
request.column_metadatas = metadata.column_metadatas.clone();
request.primary_key = metadata.primary_key.clone();
request
.options
.insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string());
request
.options
.insert("memtable.type".to_string(), "bulk".to_string());
request
.options
.insert("sst_format".to_string(), "flat".to_string());
let full_row_schema = test_util::rows_schema(&request);
let mut encoded_primary_key_schema = full_row_schema[0].clone();
encoded_primary_key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string();
encoded_primary_key_schema.datatype = ColumnDataType::Binary.into();
encoded_primary_key_schema.semantic_type = SemanticType::Tag.into();
let row_schema = vec![
encoded_primary_key_schema,
full_row_schema[5].clone(),
full_row_schema[4].clone(),
];
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows = |values: &[(u32, u64, &str, &str, u64, i64)]| Rows {
schema: row_schema.clone(),
rows: values
.iter()
.map(|(table_id, tsid, tag_0, tag_1, field, ts)| {
row(vec![
ValueData::BinaryValue(new_sparse_primary_key(
&[*tag_0, *tag_1],
&metadata,
*table_id,
*tsid,
)),
ValueData::TimestampMillisecondValue(*ts),
ValueData::U64Value(*field),
])
})
.collect(),
};
let put = |rows| {
RegionRequest::Put(RegionPutRequest {
skip_wal: false,
rows,
hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
}),
partition_expr_version: None,
})
};
// Older SST: sequences 1 and 2.
engine
.handle_request(
region_id,
put(rows(&[
(10, 0, "a", "x", 10, 1000),
(20, 0, "c", "z", 30, 1000),
])),
)
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
// Newer SST: sequences 3 and 4.
engine
.handle_request(
region_id,
put(rows(&[
(10, 0, "a", "x", 11, 2000),
(10, u64::MAX, "b", "y", 20, 1000),
])),
)
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
// Memtable: sequences 5 and 6.
engine
.handle_request(
region_id,
put(rows(&[
(10, 0, "a", "x", 12, 3000),
(20, u64::MAX, "d", "w", 40, 1000),
])),
)
.await
.unwrap();
(env, engine, region_id)
}
fn canonical_sparse_rows(batches: &RecordBatches) -> Vec<(u32, u64, String, String, u64, i64)> {
let schema = batches.schema();
// Verify the complete output schema before looking at batches so empty
// scans are checked too.
assert_eq!(6, schema.num_columns());
assert_eq!(
vec!["__table_id", "__tsid", "tag_0", "tag_1", "field_0", "ts"],
(0..schema.num_columns())
.map(|index| schema.column_name_by_index(index))
.collect::<Vec<_>>(),
);
let mut rows = Vec::new();
for batch in batches.iter() {
let table_id = batch
.column_by_name("__table_id")
.unwrap()
.as_primitive::<UInt32Type>();
let tsid = batch
.column_by_name("__tsid")
.unwrap()
.as_primitive::<UInt64Type>();
let tag_0 = batch.column_by_name("tag_0").unwrap();
let tag_1 = batch.column_by_name("tag_1").unwrap();
let field = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<UInt64Type>();
let ts = batch
.column_by_name("ts")
.unwrap()
.as_primitive::<TimestampMillisecondType>();
for row in 0..batch.num_rows() {
rows.push((
table_id.value(row),
tsid.value(row),
datatypes::arrow_array::string_array_value_at_index(tag_0, row)
.unwrap()
.to_string(),
datatypes::arrow_array::string_array_value_at_index(tag_1, row)
.unwrap()
.to_string(),
field.value(row),
ts.value(row),
));
}
}
rows.sort();
rows
}
async fn scan_sparse_exact_metric(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
min: Option<u64>,
max: Option<u64>,
selector: Option<TimeSeriesRowSelector>,
expected_mode: &str,
) -> (
datatypes::schema::SchemaRef,
Vec<(u32, u64, String, String, u64, i64)>,
) {
let scanner = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: min,
memtable_max_sequence: max,
exact_sequence_range: min.is_some(),
distribution: Some(TimeSeriesDistribution::PerSeries),
// A tag predicate is required for range-result-cache eligibility.
// It selects every fixture row while keeping cache keys comparable.
filters: vec![col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("a".to_string()))))],
series_row_selector: selector,
..Default::default()
},
)
.await
.unwrap();
let Scanner::Series(scanner) = scanner else {
panic!("sparse metric scan must use SeriesScan");
};
assert_eq!(expected_mode, scanner.mode());
let batches = RecordBatches::try_collect(scanner.build_stream().await.unwrap())
.await
.unwrap();
let schema = batches.schema();
(schema, canonical_sparse_rows(&batches))
}
/// Exact sparse-metric reads must use two-phase scanning and preserve the same
/// complete rows as the legacy series scanner at every sequence boundary.
#[tokio::test]
async fn test_two_phase_sparse_metric_exact_sequence_cases() {
let (_two_phase_env, two_phase, two_phase_region) = build_sparse_exact_metric_engine(
"test_two_phase_sparse_metric_exact_sequence_cases_two_phase",
true,
ReadableSize::mb(0),
)
.await;
let (_legacy_env, legacy, legacy_region) = build_sparse_exact_metric_engine(
"test_two_phase_sparse_metric_exact_sequence_cases_legacy",
false,
ReadableSize::mb(0),
)
.await;
let cases = [
// (min, max], selector, expected canonical rows.
(
"boundaries_and_newer_sst_outside",
Some(0),
Some(2),
None,
vec![("a", "x", 10, 1000), ("c", "z", 30, 1000)],
),
(
"lower_boundary_excluded_upper_boundary_included",
Some(2),
Some(4),
None,
vec![("a", "x", 11, 2000), ("b", "y", 20, 1000)],
),
// Candidates are present in the memtable but all are outside (4, 4].
(
"candidate_outside_only_empty",
Some(4),
Some(4),
None,
vec![],
),
// One delta spans the older SST, newer SST, and memtable.
(
"mixed_sst_mem_no_dropped_rows",
Some(1),
Some(5),
None,
vec![
("a", "x", 11, 2000),
("a", "x", 12, 3000),
("b", "y", 20, 1000),
("c", "z", 30, 1000),
],
),
// Selector is applied after the exact filter: a's newer seq 5 row is
// excluded, so its seq 3 row survives as the last selected row.
(
"last_row_selector_excludes_newer_sequence",
Some(0),
Some(4),
Some(TimeSeriesRowSelector::LastRow { after_merge: false }),
vec![
("a", "x", 11, 2000),
("b", "y", 20, 1000),
("c", "z", 30, 1000),
],
),
];
for (name, min, max, selector, expected) in cases {
let expected = expected
.into_iter()
.map(|(tag_0, tag_1, field, ts)| {
let (table_id, tsid) = match tag_0 {
"a" => (10, 0),
"b" => (10, u64::MAX),
"c" => (20, 0),
"d" => (20, u64::MAX),
_ => unreachable!("unknown fixture series: {tag_0}"),
};
(
table_id,
tsid,
tag_0.to_string(),
tag_1.to_string(),
field,
ts,
)
})
.collect::<Vec<_>>();
let (two_phase_schema, two_phase_rows) = scan_sparse_exact_metric(
&two_phase,
two_phase_region,
min,
max,
selector,
"two_phase",
)
.await;
let (legacy_schema, legacy_rows) =
scan_sparse_exact_metric(&legacy, legacy_region, min, max, selector, "legacy").await;
assert_eq!(expected, two_phase_rows, "two-phase {name}");
assert_eq!(expected, legacy_rows, "legacy {name}");
assert_eq!(
two_phase_schema, legacy_schema,
"schema mismatch for {name}"
);
}
}
/// A warmed exact series scan must hit the existing range-result cache; a
/// second upper bound over the same files and an unbounded scan must not reuse
/// its rows.
#[rstest::rstest]
#[case(true)]
#[case(false)]
#[tokio::test]
async fn test_sparse_metric_exact_sequence_cache_isolation(#[case] two_phase: bool) {
let (_env, engine, region_id) = build_sparse_exact_metric_engine(
"test_sparse_metric_exact_sequence_cache_isolation",
two_phase,
ReadableSize::mb(64),
)
.await;
// Make the fixture file-only so both series scan modes can cache their ranges.
test_util::flush_region(&engine, region_id, None).await;
let restrictive = ScanRequest {
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(4),
exact_sequence_range: true,
distribution: Some(TimeSeriesDistribution::PerSeries),
filters: vec![col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("a".to_string()))))],
..Default::default()
};
let scan = |request| async {
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(scanner) = scanner else {
panic!("sparse metric scan must use SeriesScan");
};
assert_eq!(
if two_phase { "two_phase" } else { "legacy" },
scanner.mode()
);
assert_eq!(1, scanner.properties().num_partitions());
let batches = RecordBatches::try_collect(scanner.build_stream().await.unwrap())
.await
.unwrap();
(
canonical_sparse_rows(&batches),
format!("{}", VerboseDisplay(scanner)),
)
};
let (cold, _) = scan(restrictive.clone()).await;
// Cache insertion is performed by the range stream's async concat task.
// The data reader uses partition 0 in two-phase mode and partition 1 in legacy mode.
let warm = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let (rows, verbose) = scan(restrictive.clone()).await;
// Inspect the data reader rather than candidate-stage cache hits.
let data_metrics = verbose
.split(if two_phase {
"\"partition\":0, \"metrics\":"
} else {
"\"partition\":1, \"metrics\":"
})
.nth(1)
.and_then(|metrics| metrics.split("\"partition\":").next())
.expect("missing output-partition metrics");
if data_metrics.contains("\"range_cache_hit\":") {
return rows;
}
tokio::task::yield_now().await;
}
})
.await
.expect("series-data range cache did not complete and replay within timeout");
assert_eq!(cold, warm);
assert_eq!(
vec![
(10, 0, "a".to_string(), "x".to_string(), 10, 1000),
(10, 0, "a".to_string(), "x".to_string(), 11, 2000),
(10, u64::MAX, "b".to_string(), "y".to_string(), 20, 1000),
(20, 0, "c".to_string(), "z".to_string(), 30, 1000),
],
cold,
"unexpected restrictive exact rows"
);
// (0, 5] selects the same three flushed files as (0, 4] but its output
// includes a's sequence-5 row, so it must not reuse the restrictive rows.
let (different_upper, _) = scan(ScanRequest {
memtable_max_sequence: Some(5),
..restrictive.clone()
})
.await;
assert_eq!(
vec![
(10, 0, "a".to_string(), "x".to_string(), 10, 1000),
(10, 0, "a".to_string(), "x".to_string(), 11, 2000),
(10, 0, "a".to_string(), "x".to_string(), 12, 3000),
(10, u64::MAX, "b".to_string(), "y".to_string(), 20, 1000),
(20, 0, "c".to_string(), "z".to_string(), 30, 1000),
],
different_upper,
"different upper bound reused restrictive rows"
);
let (unbounded, _) = scan(ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
filters: restrictive.filters.clone(),
..Default::default()
})
.await;
assert_eq!(
vec![
(10, 0, "a".to_string(), "x".to_string(), 10, 1000),
(10, 0, "a".to_string(), "x".to_string(), 11, 2000),
(10, 0, "a".to_string(), "x".to_string(), 12, 3000),
(10, u64::MAX, "b".to_string(), "y".to_string(), 20, 1000),
(20, 0, "c".to_string(), "z".to_string(), 30, 1000),
(20, u64::MAX, "d".to_string(), "w".to_string(), 40, 1000),
],
unbounded,
"unbounded scan reused exact rows"
);
}
/// Range-cache fingerprint: identical files and filters with different (C, H]
/// sequence ranges must never share a cache entry, otherwise the second scan
/// would replay the first scan's filtered rows.
#[tokio::test]
async fn test_range_cache_key_separates_sequence_ranges() {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
// Explicitly enable the range result cache: the sharing bug only
// reproduces when the second scan can replay the first scan's
// cached batches.
range_result_cache_size: ReadableSize::mb(64),
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Single flushed flat SST with rows seq 1..6.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 6),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let tag_filter = || col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("0".to_string()))));
let scan_exact = async |min: Option<u64>, max: Option<u64>| -> Vec<String> {
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
filters: vec![tag_filter()],
memtable_min_sequence: min,
memtable_max_sequence: max,
exact_sequence_range: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
let mut rows = batches
.pretty_print()
.unwrap()
.lines()
.filter(|l| l.starts_with("| ") && !l.starts_with("| tag_0 "))
.map(|l| l.to_string())
.collect::<Vec<_>>();
rows.sort_unstable();
rows
};
// (1, 3] -> rows with sequences 2..3: tags "1" and "2".
let first = scan_exact(Some(1), Some(3)).await;
assert_eq!(
vec![
"| 1 | 1.0 | 1970-01-01T00:00:01 |",
"| 2 | 2.0 | 1970-01-01T00:00:02 |",
],
first
);
// (3, 4] -> row with sequence 4: tag "3" only. If the cache key ignored
// the sequence range, this would replay the (1, 3] cached rows instead.
let second = scan_exact(Some(3), Some(4)).await;
assert_eq!(
vec!["| 3 | 3.0 | 1970-01-01T00:00:03 |"],
second,
"different (C, H] shared a range-cache entry"
);
}
/// A range result is only reusable for a read whose **per-piece** selection is the same.
///
/// A physical-sequence read decides each row of an adopted file by the creator cursor slice
/// that selects it, and bounds the file by `(least advanced cursor, least until]`. Neither is
/// stated by the file, so two reads of the same file under the same region-level `(C, H]`
/// deliver different rows once a piece cursor or an `until` advances; a cache key that only
/// records `(C, H]` replays the first read's rows to all of them.
///
/// The counterexample this pins: `(cursor 0, until 6]` caches the rows 1..6, `(cursor 3,
/// until 8]` requires the rows 4..8, and `(cursor 0, until 2]` requires the rows 1..2 and
/// nothing above its `until`. Replaying the first result delivers the rows 1..6 to all three:
/// rows an advanced piece already consumed, rows the new range requires that are missing, and
/// rows above the new `until`.
///
/// The `LastRow` selector is what puts this read on the sequential scan, the only path that
/// fills the range result cache: without it an append-only region reads through the unordered
/// scan, which bypasses the cache entirely.
#[tokio::test]
async fn test_range_cache_never_replays_a_range_read_under_other_creator_cursors() {
let mut env = TestEnv::with_prefix("test_range_cache_creator_cursor_slices").await;
let engine = env
.create_engine(MitoConfig {
// The flat format is the one the range result cache covers.
default_flat_format: true,
range_result_cache_size: ReadableSize::mb(64),
..Default::default()
})
.await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// Eight rows numbered 1..8, one per series, all of them in one file of the creator. The
// holder adopts that file as a foreign file.
let create = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&create);
engine
.handle_request(source, RegionRequest::Create(create))
.await
.unwrap();
let mut rows = Vec::new();
for series in 0..8_usize {
rows.extend(test_util::build_rows_for_key(
&series.to_string(),
series,
series + 1,
0,
));
}
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
test_util::flush_region(&engine, source, None).await;
let source_file = manifest_files(&engine, source)
.await
.into_values()
.next()
.expect("flushed file");
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 20, true, None);
// The `(cursor, until]` of the one piece the rows of the adopted file belong to. The
// region-level `(0, 20]` is the same in every read, so only the slice separates them; the
// tag filter is what makes the range eligible for the cache.
let request = |cursor: u64, until: u64| {
let mut request = creator_cursor_scan(
source,
vec![partition_str_slice_cursor("0", "9", cursor).with_until(until)],
0,
20,
);
request.filters = vec![col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("0".to_string()))))];
request.series_row_selector = Some(TimeSeriesRowSelector::LastRow { after_merge: false });
request
};
let first = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6))
.await
.0;
assert_eq!(
vec![0, 1000, 2000, 3000, 4000, 5000],
first,
"the first read delivers the rows above its cursor and up to its `until`"
);
// Wait for the completed range result: the same read then replays it, which it reports by
// saying that the files its rows came from are not readable from that call.
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let (rows, creators) =
scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6)).await;
assert_eq!(first, rows, "a replay delivers the rows it replayed");
if creators.is_none() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the range result cache did not replay the range within the timeout");
// An advanced piece cursor with a higher `until`: the rows 4..8 are what this range
// requires, and the rows 1..3 are already consumed.
let advanced = scan_partition_rows_and_foreign_creators(&engine, target, request(3, 8))
.await
.0;
assert_eq!(
vec![3000, 4000, 5000, 6000, 7000],
advanced,
"a read under an advanced piece cursor must not replay the rows of the earlier read: \
only its own `(cursor, until]` decides"
);
// A narrower `until`: no row above it may be delivered, whatever an earlier read of the
// same files cached.
let bounded = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 2))
.await
.0;
assert_eq!(
vec![0, 1000],
bounded,
"a range result must never deliver a row above the `until` of the read it serves"
);
}
#[tokio::test]
async fn test_single_source_ranges_preserve_batches() {
for (file_count, row_group_size) in [(1, 64), (1, 16), (2, 16)] {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("memtable.type", "bulk")
.insert_option("max_row_group_row_count", &row_group_size.to_string())
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let rows_per_file = 64 / file_count;
for file in 0..file_count {
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: test_util::build_rows(file * rows_per_file, (file + 1) * rows_per_file),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
let Scanner::Seq(scanner) = engine
.scanner(region_id, ScanRequest::default())
.await
.unwrap()
else {
panic!("expected a sequential scan");
};
assert_eq!(file_count, scanner.input().files.len());
assert_eq!(
64 / row_group_size,
scanner.properties().partitions[0].len()
);
let stream = scanner
.scan_partition(&Default::default(), &ExecutionPlanMetricsSet::default(), 0)
.unwrap();
let batches = stream.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(
vec![row_group_size; 64 / row_group_size],
batches
.iter()
.map(|batch| batch.num_rows())
.collect::<Vec<_>>()
);
let mut values = scan_field_values(&batches);
values.sort_by(f64::total_cmp);
assert_eq!((0..64).map(|i| i as f64).collect::<Vec<_>>(), values);
}
}
#[tokio::test]
async fn test_short_series_level_zero_merge_preserves_batches_and_latest_values() {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("memtable.type", "bulk")
.insert_option("max_row_group_row_count", "65536")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
for (start, end, offset) in [(0, 12_000, 0), (6_000, 18_000, 100_000)] {
let rows = (start..end)
.map(|i| {
row(vec![
ValueData::StringValue(format!("{i:05}")),
ValueData::F64Value((i + offset) as f64),
ValueData::TimestampMillisecondValue(0),
])
})
.collect();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows,
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
}
let Scanner::Seq(scanner) = engine
.scanner(region_id, ScanRequest::default())
.await
.unwrap()
else {
panic!("expected a sequential scan");
};
assert_eq!(2, scanner.input().files.len());
for file in &scanner.input().files {
assert_eq!(0, file.meta_ref().level);
assert_eq!(12_000, file.meta_ref().num_series);
}
let batches = scanner
.scan_partition(&Default::default(), &ExecutionPlanMetricsSet::default(), 0)
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert!(
batches.len() < 64,
"short series became {} batches",
batches.len()
);
assert_eq!(
(0..18_000)
.map(|i| if i < 6_000 {
i as f64
} else {
(i + 100_000) as f64
})
.collect::<Vec<_>>(),
scan_field_values(&batches),
);
}
#[tokio::test]
async fn test_reset_state_discards_dynamic_field_pruning() {
for (append_mode, expected_scanner_name) in [(false, "SeqScan"), (true, "UnorderedScan")] {
let mut env = TestEnv::with_prefix(if append_mode {
"test_reset_state_discards_dynamic_field_pruning_unordered"
} else {
"test_reset_state_discards_dynamic_field_pruning_seq"
})
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, u32::from(append_mode) + 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", &append_mode.to_string())
// Keep a third row group unconsumed after the first execution so its
// file-range builder remains cached by the old pruner.
.insert_option("max_row_group_row_count", "2")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 6),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let scanner = engine
.scanner(
region_id,
ScanRequest {
// The static physical-field predicate must survive reset.
filters: vec![col("field_0").gt_eq(lit(1.0_f64))],
..Default::default()
},
)
.await
.unwrap();
let mut scanner: Box<dyn RegionScanner> = match scanner {
Scanner::Seq(scanner) => {
assert_eq!(expected_scanner_name, "SeqScan");
assert_eq!(3, scanner.input().files[0].meta_ref().num_row_groups);
Box::new(scanner)
}
Scanner::Unordered(scanner) => {
assert_eq!(expected_scanner_name, "UnorderedScan");
assert_eq!(3, scanner.input().files[0].meta_ref().num_row_groups);
Box::new(scanner)
}
Scanner::Series(_) => panic!("scanner should not be a series scan"),
};
assert_eq!(expected_scanner_name, scanner.name());
let field = Arc::new(Column::new("field_0", 1));
let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(
vec![field.clone()],
physical_lit(true),
));
assert_eq!(
vec![true],
scanner.add_dyn_filter_to_predicate(vec![dynamic_filter.clone()])
);
dynamic_filter
.update(Arc::new(BinaryExpr::new(
field,
Operator::Gt,
physical_lit(2.0_f64),
)))
.unwrap();
// Dynamic pruning skips the first row group, and the dynamic prefilter prunes the
// row the producer rejects in the second. Only the row above the producer's
// threshold is left; the live filter above the scan still owns the final result.
// Drop before consuming the third row group.
let mut stream = scanner
.scan_partition(&Default::default(), &ExecutionPlanMetricsSet::default(), 0)
.unwrap();
let first_batch = stream.try_next().await.unwrap().unwrap();
assert_eq!(
vec![3.0],
scan_field_values(std::slice::from_ref(&first_batch))
);
drop(stream);
scanner.reset_state();
// This producer belongs to the old execution. Its later update must not
// affect the reset scanner or restore the old cached pruning decision.
dynamic_filter.update(physical_lit(false)).unwrap();
let mut values = Vec::new();
for partition in 0..scanner.properties().num_partitions() {
let stream = scanner
.scan_partition(
&Default::default(),
&ExecutionPlanMetricsSet::default(),
partition,
)
.unwrap();
values.extend(scan_field_values(
&stream.try_collect::<Vec<_>>().await.unwrap(),
));
}
values.sort_by(f64::total_cmp);
assert_eq!(vec![1.0, 2.0, 3.0, 4.0, 5.0], values);
}
}
fn scan_field_values(batches: &[common_recordbatch::RecordBatch]) -> Vec<f64> {
batches
.iter()
.flat_map(|batch| {
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<Float64Type>();
(0..batch.num_rows()).map(move |row| fields.value(row))
})
.collect()
}
/// A read that may cross an invalid boundary virtualizes every selected file's rows at
/// the file's own admission barrier, even for a local file whose
/// `preserve_row_sequence` marker is off: such a read must not depend on the file's
/// row-level sequences being trusted.
#[tokio::test]
async fn test_read_across_invalid_boundary_forces_sequence_override() {
let mut env =
TestEnv::with_prefix("test_read_across_invalid_boundary_forces_sequence_override").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
// Re-admit the same file id unmarked: the edit clears `preserve_row_sequence`
// and moves the barrier to the next sequence.
let region = engine.get_region(region_id).unwrap();
let file_meta = region
.version()
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.next()
.expect("flushed SST")
.meta_ref()
.clone();
let mut readmit = file_meta;
readmit.preserve_row_sequence = false;
readmit.sequence = None;
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![readmit],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
let version = engine.get_region(region_id).unwrap().version();
let file_barrier = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.next()
.expect("admitted SST")
.meta_ref()
.sequence
.expect("edit assigns a barrier")
.get();
assert!(file_barrier > 0);
assert!(
!version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.all(|file| file.meta_ref().preserve_row_sequence)
);
// Discovery reads the file anyway and every row's sequence is the barrier.
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
memtable_min_sequence: Some(file_barrier - 1),
exact_sequence_range: true,
read_across_invalid_boundary: true,
..Default::default()
},
)
.await
.expect("a read across an invalid boundary must admit an unmarked file");
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(
3,
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
"a read across an invalid boundary reads every row of the unmarked file instead of failing closed"
);
}
/// A read that may cross an invalid boundary must report an empty candidate set instead
/// of silently reporting "no window"; the caller decides whether to accept it or advance
/// the cursor instead.
#[tokio::test]
async fn test_read_across_invalid_boundary_reports_empty_candidates() {
let mut env =
TestEnv::with_prefix("test_read_across_invalid_boundary_reports_empty_candidates").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(0),
exact_sequence_range: true,
read_across_invalid_boundary: true,
..Default::default()
},
)
.await
.err()
.expect("an empty candidate set must be reported");
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"unexpected err: {err}"
);
let msg = err.to_string();
assert!(
msg.starts_with("exact sequence range unavailable:"),
"unexpected err msg: {msg}"
);
assert!(msg.contains("no candidate file above the cursor"), "{msg}");
}
/// A discovery read (`read_across_invalid_boundary`) applies no lower sequence bound to
/// memtables, while an ordinary incremental read keeps its own.
///
/// This is the shape a merge of regions produces: the merged region admits rows that the
/// old cursor cannot explain (staging writes that the old partition expression does not
/// select, or rows whose numbers the region can no longer vouch for). A lower bound of
/// `C` would hide exactly those rows, so their windows would never be reported and a
/// repair would advance the cursor past them. Discovery therefore reads them; the
/// ordinary delta keeps hiding everything at or below its cursor.
#[tokio::test]
async fn test_read_across_invalid_boundary_reads_memtable_rows_below_cursor() {
let mut env = TestEnv::with_prefix("test_read_across_invalid_boundary_memtable").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Rows 0..3 are flushed (their numbers are 1..3), rows 3..5 stay in the memtable
// with the numbers 4 and 5.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 5),
},
)
.await;
// The cursor is at 5: every memtable row is at or below it.
let ordinary = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(5),
skip_sst_files: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(ordinary.scan().await.unwrap())
.await
.unwrap();
assert_eq!(
0,
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
"an ordinary delta must not deliver rows its cursor already consumed"
);
// The same cursor as a discovery read: the memtable rows are exactly the rows whose
// windows the cursor can no longer explain, so they must be visible.
let discovery = engine
.scanner(
region_id,
ScanRequest {
memtable_min_sequence: Some(5),
skip_sst_files: true,
read_across_invalid_boundary: true,
..Default::default()
},
)
.await
.unwrap();
let batches = RecordBatches::try_collect(discovery.scan().await.unwrap())
.await
.unwrap();
assert_eq!(
vec![("3", 3.0), ("4", 4.0)],
batches
.iter()
.flat_map(|batch| {
let tags = batch.column_by_name("tag_0").unwrap().as_string::<i32>();
let fields = batch
.column_by_name("field_0")
.unwrap()
.as_primitive::<Float64Type>();
(0..batch.num_rows())
.map(|row| (tags.value(row), fields.value(row)))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>(),
"discovery must see the rows at or below the cursor, or their windows are never reported"
);
}
/// A fenced repair DML has no incremental lower bound and no exact sequence-range
/// mode, so `H` bounds memtables only. If `H` is behind the flushed frontier, a
/// flush that landed after `H` was frozen would be aggregated into the repaired
/// window and counted again by the next round; the SST upper-bound fence must stay
/// in force.
#[tokio::test]
async fn test_fenced_repair_rejects_upper_bound_behind_flushed_frontier() {
let mut env =
TestEnv::with_prefix("test_fenced_repair_rejects_upper_bound_behind_flushed").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// A high watermark frozen before the write, then the write is flushed.
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let frozen_high = 2;
let flushed_sequence = engine
.get_region(region_id)
.unwrap()
.version()
.flushed_sequence;
assert!(flushed_sequence > frozen_high);
let err = engine
.scanner(
region_id,
ScanRequest {
memtable_max_sequence: Some(frozen_high),
require_flushed_frontier: true,
..Default::default()
},
)
.await
.err()
.expect("a fenced repair behind the flushed frontier must be rejected");
assert!(
matches!(
err,
Error::SnapshotFenceStale {
given_seq,
min_enforceable_seq,
..
} if given_seq == frozen_high && min_enforceable_seq == flushed_sequence
),
"unexpected err: {err}"
);
assert_eq!(StatusCode::RequestOutdated, err.status_code());
}
/// A read that requires the flushed frontier recomputes a whole window under a frozen `H`,
/// so it reads as a plain scan: no exact sequence range is requested, which keeps every
/// candidate file (there is no file-granularity pruning by the cursor, even when a file's
/// own barrier is at or below it) and applies no row-level sequence range at all. Only a
/// read that may cross an invalid boundary forces a row-sequence override, so this read
/// reports the numbers its writer allocated instead of virtualizing every row at the file's
/// barrier: what a stale cursor can no longer explain is stated per file, so the rows under
/// the invalid boundary are read instead of being cut by a region-level boundary.
#[tokio::test]
async fn test_require_flushed_frontier_reads_the_complete_window() {
let mut env = TestEnv::with_prefix("test_require_flushed_frontier_reads_complete_window").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// Three rows land in an SST (sequences 1..=3, barrier 3) ...
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
// ... and three more stay in the memtable (sequences 4..=6).
test_util::put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: test_util::build_rows(3, 6),
},
)
.await;
let region = engine.get_region(region_id).unwrap();
let file_barrier = region
.version()
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.next()
.expect("flushed SST")
.meta_ref()
.sequence
.expect("a flush admits its file")
.get();
let frozen_high = region.version_control.current().last_sequence;
drop(region);
assert_eq!(
3, file_barrier,
"the flush's barrier is the last number it wrote"
);
assert!(
frozen_high > file_barrier,
"the memtable must hold rows above the file"
);
let mut rows = scan_flat_row_sequences(
&engine,
region_id,
ScanRequest {
// The cursor sits exactly on the file's barrier: an exact range would prune the
// whole file, and a read that requires the flushed frontier keeps it.
memtable_min_sequence: Some(file_barrier),
memtable_max_sequence: Some(frozen_high),
require_flushed_frontier: true,
..Default::default()
},
)
.await;
rows.sort_unstable();
assert_eq!(
vec![
(0, 1),
(1_000, 2),
(2_000, 3),
(3_000, 4),
(4_000, 5),
(5_000, 6)
],
rows,
"a read that requires the flushed frontier keeps the rows below it and reports the \
numbers their writer allocated, not the file's barrier"
);
}
/// Creates a source region, writes `num_rows` rows of one series, flushes them, and returns the
/// flushed file plus its source file id.
///
/// `preserve_row_sequence` selects the numbering the bytes carry: `true` gives every row the
/// number its writer allocated, `false` leaves the column at zero (a legacy import, which is
/// what a substituted cut of `Some(0)` describes). The returned handle is what a repartition
/// publishes in the target region: the bytes stay source-owned, so the target's reader has to
/// decide what to do with their sequence column.
async fn build_foreign_source_file(
engine: &crate::engine::MitoEngine,
source: RegionId,
num_rows: usize,
preserve_row_sequence: bool,
) -> (FileId, FileMeta) {
let mut request_builder = CreateRequestBuilder::new().insert_option("append_mode", "true");
if preserve_row_sequence {
request_builder = request_builder.insert_option("preserve_row_sequence", "true");
}
let request = request_builder.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
engine,
source,
Rows {
schema,
rows: test_util::build_rows_for_key("0", 0, num_rows, 0),
},
)
.await;
test_util::flush_region(engine, source, None).await;
let meta = engine
.get_region(source)
.unwrap()
.manifest_ctx
.manifest()
.await
.files
.values()
.next()
.expect("source file")
.as_ref()
.clone();
assert_eq!(
preserve_row_sequence, meta.preserve_row_sequence,
"the source file must state the numbering its bytes carry"
);
(meta.file_id, meta)
}
/// Adopts `source_file` into `target` the way a repartition publishes it: still source-owned,
/// re-marked at the holder's admission barrier, with `cut` as the substituted bound of the
/// bytes and `preserve_row_sequence` as the design's supported marker.
fn adopt_foreign_file(
engine: &crate::engine::MitoEngine,
target: RegionId,
source_file: FileMeta,
admission: u64,
preserve_row_sequence: bool,
cut: Option<u64>,
) -> FileHandle {
let region = engine.get_region(target).unwrap();
let mut adopted = source_file;
adopted.sequence = std::num::NonZeroU64::new(admission);
adopted.preserve_row_sequence = preserve_row_sequence;
adopted.substituted_up_to = cut;
adopted.level = 0;
let handle = FileHandle::new(adopted.clone(), region.file_purger.clone());
let edit = RegionEdit {
files_to_add: vec![adopted],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
};
// Applied as a flush-shaped edit: the tests below exercise the reader, not the cursor.
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
handle
}
/// Creates the target region of a repartition with the same preserved-sequence option.
async fn create_foreign_target(engine: &crate::engine::MitoEngine, target: RegionId) {
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
engine
.handle_request(target, RegionRequest::Create(request))
.await
.unwrap();
}
/// Scans one partition through the region-scan path a datanode uses and returns the
/// timestamps of the surviving rows plus the substituted row ranges the scan reported.
///
/// This is the path that carries proof with the result: `scan_partition`'s stream reports
/// its substituted ranges through `metrics()`, exactly like the snapshot watermark.
async fn scan_partition_substituted_row_ranges(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
request: ScanRequest,
) -> (
Vec<i64>,
Vec<common_recordbatch::adapter::SubstitutedRowRanges>,
) {
use store_api::region_engine::QueryScanContext;
let scanner = engine.handle_query(region_id, request).await.unwrap();
let mut stream = scanner
.scan_partition(
&QueryScanContext::default(),
&ExecutionPlanMetricsSet::new(),
0,
)
.unwrap();
let mut timestamps = Vec::new();
while let Some(batch) = stream.try_next().await.unwrap() {
let column = batch
.column_by_name("ts")
.expect("time index column")
.clone();
timestamps.extend_from_slice(crate::read::timestamp_array_to_i64_slice(&column));
}
let substituted = stream
.metrics()
.map(|metrics| metrics.substituted_row_ranges)
.unwrap_or_default();
(timestamps, substituted)
}
/// Scans one partition and returns the `(region, expression slice)` pairs the scan
/// reported as read.
async fn scan_partition_observed_slices(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
request: ScanRequest,
) -> Vec<common_recordbatch::adapter::ObservedPartitionExpr> {
use store_api::region_engine::QueryScanContext;
let scanner = engine.handle_query(region_id, request).await.unwrap();
let mut stream = scanner
.scan_partition(
&QueryScanContext::default(),
&ExecutionPlanMetricsSet::new(),
0,
)
.unwrap();
while stream.try_next().await.unwrap().is_some() {}
stream
.metrics()
.map(|metrics| metrics.observed_slices)
.unwrap_or_default()
}
/// Scans every partition through the batch path, whose flat batches still carry the
/// physical `__sequence` column, and returns `(timestamp, sequence)` per surviving row.
async fn scan_flat_row_sequences(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
request: ScanRequest,
) -> Vec<(i64, u64)> {
use crate::read::stream::ScanBatch;
let mut stream = engine.scan_batch(region_id, request, true).await.unwrap();
let mut rows = Vec::new();
while let Some(batch) = stream.try_next().await.unwrap() {
let ScanBatch::RecordBatch(batch) = batch else {
panic!("a flat scan yields record batches");
};
let num_columns = batch.num_columns();
let timestamps = crate::read::timestamp_array_to_i64_slice(batch.column(num_columns - 4));
let sequences = batch
.column(num_columns - 2)
.as_any()
.downcast_ref::<datatypes::arrow::array::UInt64Array>()
.expect("sequence column");
for (idx, sequence) in sequences.values().iter().enumerate() {
rows.push((timestamps[idx], *sequence));
}
}
rows
}
/// The exact `(C, H]` delta a physical-sequence read asks for: it needs a lower bound to
/// select files and an upper bound to prove the range.
///
/// A physical-sequence read of a *foreign* file must carry the creator's cursor slices
/// ([`creator_cursor_scan`]); without them the read fails closed, because this region's
/// own bound does not describe the numbers in that file.
fn physical_sequence_scan(read_row_sequence: bool) -> ScanRequest {
ScanRequest {
exact_sequence_range: true,
read_row_sequence,
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(4),
..Default::default()
}
}
/// The exact `(creator cursor, H]` delta a physical-sequence read of an adopted file asks
/// for: the lower bound comes from the slices the *creator* region allocated, the upper
/// bound is this scan's own snapshot.
fn creator_cursor_scan(
creator: RegionId,
shards: Vec<CursorShard>,
min: u64,
max: u64,
) -> ScanRequest {
ScanRequest {
exact_sequence_range: true,
read_row_sequence: true,
memtable_min_sequence: Some(min),
memtable_max_sequence: Some(max),
creator_cursor_shards: Some(Arc::new(BTreeMap::from([(creator.as_u64(), shards)]))),
..Default::default()
}
}
/// The same read with a creator cursor that consumed nothing yet: what a scan of adopted
/// files carries, and what makes their rows comparable with the creator's domain at all.
fn adopted_physical_sequence_scan(creator: RegionId) -> ScanRequest {
creator_cursor_scan(creator, vec![CursorShard::whole_domain(0)], 0, 4)
}
/// The partition expression a file states: `tag_0 >= lo AND tag_0 < hi`.
///
/// The bounds are zero padded so that their lexicographic order (the order the string tag
/// column has) is their numeric order: the expression comparison normalizes each column's
/// values in that order, and `"100" < "50"` would otherwise make the range inverted.
fn partition_slice(lo: u64, hi: u64) -> partition::expr::PartitionExpr {
partition_str_slice(&format!("{lo:03}"), &format!("{hi:03}"))
}
/// The partition expression `tag_0 >= lo AND tag_0 < hi` over the string tag column of the
/// test schema.
///
/// The bounds are strings because the reader compiles a partition expression into a row
/// filter of the column's own type: the tag column `k0` of the test schema is a string, so a
/// numeric bound would not be evaluable at all.
fn partition_str_slice(lo: &str, hi: &str) -> partition::expr::PartitionExpr {
use datatypes::value::Value;
use partition::expr::{Operand, col as partition_col};
// `tag_0` is the string tag of the test schema (`[tag_0, field_0, ts]`).
partition_col("tag_0")
.gt_eq(Operand::Value(Value::String(lo.into())))
.and(partition_col("tag_0").lt(Operand::Value(Value::String(hi.into()))))
}
/// The identity a cursor slice carries for the expression `partition_slice(lo, hi)`.
fn partition_slice_identity(lo: u64, hi: u64) -> String {
partition_slice(lo, hi).as_json_str().unwrap()
}
/// The cursor slice of `partition_slice(lo, hi)` consumed up to `seq`.
fn partition_slice_cursor(lo: u64, hi: u64, seq: u64) -> CursorShard {
CursorShard::new(Some(partition_slice_identity(lo, hi)), seq)
}
/// The cursor slice of `partition_str_slice(lo, hi)` consumed up to `seq`.
fn partition_str_slice_cursor(lo: &str, hi: &str, seq: u64) -> CursorShard {
CursorShard::new(
Some(partition_str_slice(lo, hi).as_json_str().unwrap()),
seq,
)
}
/// An adopted file is filtered by the cursor of the region that allocated its numbers, not
/// by this region's own `(C, H]`: the numbers in its column never belonged to this region's
/// sequence space. Without that filter the file would be read whole and every row above its
/// substituted cut delivered again on every round.
#[tokio::test]
async fn test_read_row_sequence_filters_adopted_rows_by_creator_cursor() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_by_creator_cursor").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// The creator's file states the numbers 1, 2 and 3, and the cut 2 says a substitution
// produced the first two of them, so only the third is this file's own.
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 4, true, Some(2));
// The region-keyed form of the cursor (one whole-domain slice) with cursor 1: every row
// the cut leaves is above it, so the cut alone decides what is delivered.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 1, 10),
)
.await;
assert_eq!(
vec![(2000, 3)],
rows,
"the substituted rows are dropped and the row above the cursor is delivered"
);
// A cursor at 3 consumes the only row above the cut: the file delivers nothing. The
// reader before this change could not express that at all — it skipped the row filter
// of every adopted file because the holder's cursor does not bound these numbers.
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(3)], 1, 10),
)
.await;
assert!(
timestamps.is_empty(),
"a row at or below the creator's cursor is already consumed"
);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 1000,
}],
}],
substituted,
"the rows the cut hides are still reported for recomputation"
);
// Without a creator cursor the read fails closed instead of falling back to this
// region's own `(C, H]`: comparing the creator's numbers with a bound of another domain
// silently drops live rows, and reading the file unfiltered delivers every consumed row
// again. `test_read_row_sequence_fails_closed_without_creator_cursor` covers the error.
}
/// The cursor is keyed by `(region, expression slice)`: a file is filtered by the slice it
/// belongs to, not by the region projection of the creator's slices.
#[tokio::test]
async fn test_read_row_sequence_picks_the_intersecting_creator_slice() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_picks_intersecting_slice").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// The creator's file states the numbers 1..12 and belongs to its `[50, 100)` slice; the
// cut 3 says a substitution produced the first three of them.
let (_, mut source_file) = build_foreign_source_file(&engine, source, 12, true).await;
source_file.partition_expr = Some(partition_slice(50, 100).into());
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 4, true, Some(3));
// `[0, 50)` is at 3 and the file's own `[50, 100)` at 10: the lower bound is 10, so only
// the rows 11 and 12 are delivered. The region projection of the same cursor (`min` = 3)
// would deliver the rows 4..12 again, which is exactly the duplication this keying
// removes.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_slice_cursor(0, 50, 3),
partition_slice_cursor(50, 100, 10),
],
1,
20,
),
)
.await;
assert_eq!(vec![(10_000, 11), (11_000, 12)], rows);
// The mirror image: `[0, 50)` at 10 and the file's own `[50, 100)` at 3. The lower bound
// is the file's slice, so the rows 4..12 are delivered — the other slice's cursor must
// not be applied to a file it does not cover.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_slice_cursor(0, 50, 10),
partition_slice_cursor(50, 100, 3),
],
1,
20,
),
)
.await;
let expected = (4_u64..=12)
.map(|seq| (((seq - 1) * 1000) as i64, seq))
.collect::<Vec<(i64, u64)>>();
assert_eq!(expected, rows);
}
/// Reads the manifest files of `region`.
async fn manifest_files(
engine: &crate::engine::MitoEngine,
region: RegionId,
) -> HashMap<FileId, FileMeta> {
engine
.get_region(region)
.unwrap()
.manifest_ctx
.manifest()
.await
.files
.iter()
.map(|(id, file)| (*id, file.as_ref().clone()))
.collect()
}
/// Two files of **one** creator region, each stating a different expression of its domain,
/// with different consumed progress on the two expressions: a merged read delivers exactly
/// the rows above the cursor of the expression each file states.
///
/// The numbers are allocated in write order, so the slices are cross-wired on purpose: the
/// right slice (`k0 >= 50`) holds the *older* numbers (1..6) while the left slice
/// (`k0 < 50`) holds the newer ones (7..12). A read that applied the left cursor to both
/// files would lose the right slice's rows 3..6 (the left cursor is higher than the right
/// one), and a read that applied the region projection (`min` = 2) to both would deliver
/// the left slice's 7..10 again. Only selecting the slice each file belongs to delivers
/// both correctly.
#[tokio::test]
async fn test_read_row_sequence_filters_each_creator_expression_by_its_own_cursor() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_each_expression").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
source,
Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key("0", 0, 6, 0),
},
)
.await;
test_util::flush_region(&engine, source, None).await;
let mut right_file = manifest_files(&engine, source)
.await
.into_values()
.next()
.expect("first flushed file");
assert_eq!(None, right_file.partition_expr);
right_file.partition_expr = Some(partition_slice(50, 100).into());
test_util::put_rows(
&engine,
source,
Rows {
schema,
rows: test_util::build_rows_for_key("0", 6, 12, 0),
},
)
.await;
test_util::flush_region(&engine, source, None).await;
let mut left_file = manifest_files(&engine, source)
.await
.into_values()
.find(|file| file.file_id != right_file.file_id)
.expect("second flushed file");
assert_eq!(None, left_file.partition_expr);
left_file.partition_expr = Some(partition_slice(0, 50).into());
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, right_file, 13, true, None);
adopt_foreign_file(&engine, target, left_file, 14, true, None);
// The left expression was consumed up to 10, the right one only up to 2.
let mut rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_slice_cursor(0, 50, 10),
partition_slice_cursor(50, 100, 2),
],
1,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![
(2000, 3),
(3000, 4),
(4000, 5),
(5000, 6),
(10000, 11),
(11000, 12)
],
rows,
"each file is filtered by the cursor of the expression it states: the right slice \
keeps the rows above 2 (no loss) and the left slice starts above 10 (no duplicate)"
);
}
/// The counterexample per-row selection exists for: **one** file of one creator holds rows
/// of two of its expressions, and the two cursors advanced differently.
///
/// The file was written under the coarse expression `k0 >= "0" AND k0 < "9"`, which the
/// creator's domain has since been split out of. Its rows belong to `k0 < "5"` (consumed up
/// to 5) and to `k0 >= "5"` (consumed up to 2). The least advanced cursor of the file is 2,
/// so a file-level bound would deliver the already consumed rows 3, 4 and 5 again; the most
/// advanced one (5) would drop the live row 6. Only splitting the rows by the expression
/// each of them satisfies delivers the row at 6 and nothing else.
#[tokio::test]
async fn test_read_row_sequence_splits_one_file_by_the_expression_of_each_row() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_by_row_expression").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// One file of the creator: five rows of the left expression (numbers 1..5) and one row
// of the right one (number 6).
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
let mut rows = test_util::build_rows_for_key("1", 0, 5, 0);
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
test_util::flush_region(&engine, source, None).await;
let mut source_file = manifest_files(&engine, source)
.await
.into_values()
.next()
.expect("flushed file");
// The coarse expression the file was written under: it holds rows of both slices.
source_file.partition_expr = Some(partition_str_slice("0", "9").into());
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 7, true, None);
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("0", "5", 5),
partition_str_slice_cursor("5", "9", 2),
],
1,
20,
),
)
.await;
assert_eq!(
vec![(5000, 6)],
rows,
"the row at 6 belongs to the slice consumed up to 2 and must be delivered; the rows \
at 3, 4 and 5 belong to the slice consumed up to 5 and must not be delivered again"
);
// The same read with only `field_0` projected: the tag column the slice expressions
// reference is added to the read columns as an internal column, so the per-row decision
// still works and the output schema stays the projected one.
let mut request = creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("0", "5", 5),
partition_str_slice_cursor("5", "9", 2),
],
1,
20,
);
request.projection = Some(vec![1]);
let rows = scan_flat_row_sequences(&engine, target, request).await;
assert_eq!(
vec![(5000, 6)],
rows,
"the partition column is read even though the scan does not project it"
);
}
/// Several candidate slices may select one row, and then the **least advanced** of their
/// cursors decides it — exactly like the time-series and bulk memtable filters
/// (`Batch::filter_by_creator_slices`, `creator_slice_mask`), which take the minimum over the
/// candidates that select a row. Taking the first match instead drops the rows a less advanced
/// piece still holds.
///
/// The counterexample this pins: the retired records `A = [0,8): 1` and `B = [5,9): 0` — the
/// domain was not split cleanly, so both select a row at `k0 = 7` — and a merged holder file
/// holding one row at `k0 = 7, sequence = 1`. The row is required because
/// `1 > min(1, 0) = 0`; taking `A` first, as the reader did, drops it. It matches candidates,
/// so the fail-closed rule for a row no candidate selects does not apply.
#[tokio::test]
async fn test_read_row_sequence_takes_the_least_cursor_when_several_slices_select_a_row() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_least_cursor_of_several").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// One file of the creator holding one row of the series `k0 = "7"`, numbered 1, under a
// coarse statement (`k0 >= "0" AND k0 < "9"`) that covers both retired records: the file
// merges the rows of both pieces. The bounds are single characters, so their lexicographic
// order (the order of the string tag column) is the numeric order of the tag values.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
source,
Rows {
schema,
rows: test_util::build_rows_for_key("7", 0, 1, 0),
},
)
.await;
test_util::flush_region(&engine, source, None).await;
let mut source_file = manifest_files(&engine, source)
.await
.into_values()
.next()
.expect("flushed file");
source_file.partition_expr = Some(partition_str_slice("0", "9").into());
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 2, true, None);
// `A` is consumed up to 1, `B` only up to 0, and the row at 7 falls into both domains.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("0", "8", 1),
partition_str_slice_cursor("5", "9", 0),
],
0,
10,
),
)
.await;
assert_eq!(
vec![(0, 1)],
rows,
"the row at sequence 1 is above the least advanced of the slices that select it (0), so \
it must be delivered even though the first matching slice is consumed up to 1"
);
}
/// The same per-row rule for a **memtable** of this region: a memtable row is filtered by
/// the cursor of the piece its own tag values fall into, not by the single floor of the
/// region.
///
/// The region's own pieces are the only candidates, because a memtable holds the rows this
/// region allocated. The rows of the piece consumed up to 5 (the rows at 3, 4 and 5) are
/// not delivered again, and the row at 6 of the piece consumed up to 2 still is.
#[tokio::test]
async fn test_read_row_sequence_splits_memtable_rows_by_the_expression_of_each_row() {
let mut env =
TestEnv::with_prefix("test_read_row_sequence_splits_memtable_rows_by_expression").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region = RegionId::new(1, 1);
// Five rows of the left expression (numbers 1..5) and one row of the right one
// (number 6), all of them in the memtable: no flush, so no file takes part in the read.
// The primary-key SST format keeps the time-series memtable (the flat format would put
// the rows in the bulk memtable, which does not apply the per-piece rule), and
// `preserve_row_sequence` keeps the exact `(C, H]` delta admissible.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("sst_format", "primary_key")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region, RegionRequest::Create(request))
.await
.unwrap();
let mut rows = test_util::build_rows_for_key("1", 0, 5, 0);
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
test_util::put_rows(&engine, region, Rows { schema, rows }).await;
// One cursor value for every piece: the delivered rows are exactly the rows above the
// region-level floor 2, which is what the read delivered before the per-row rule.
let mut rows = scan_flat_row_sequences(
&engine,
region,
creator_cursor_scan(
region,
vec![
partition_str_slice_cursor("0", "5", 2),
partition_str_slice_cursor("5", "9", 2),
],
2,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)],
rows,
"one cursor value for every piece is the region-level floor of the whole read"
);
// The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed,
// the row at 6 belongs to the right one and stays live.
let mut rows = scan_flat_row_sequences(
&engine,
region,
creator_cursor_scan(
region,
vec![
partition_str_slice_cursor("0", "5", 5),
partition_str_slice_cursor("5", "9", 2),
],
2,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(5000, 6)],
rows,
"each memtable row is filtered by the cursor of the piece it belongs to: the rows at \
3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not"
);
}
/// The same rule at the memtable end of a scan: the per-piece rule of this region's own
/// memtable is built from the region's own cursor slices, so a slice set the read cannot
/// apply per row (a slice covering the whole value domain, or an identity this build cannot
/// read back) keeps the region-level floor only while every candidate carries it. With
/// several cursor values the floor delivers the rows a more advanced piece consumed, so the
/// read fails just like it does for a file of an adopted creator.
#[tokio::test]
async fn test_read_row_sequence_fails_closed_when_memtable_pieces_are_unresolved() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_memtable_pieces").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region = RegionId::new(1, 1);
// Five rows in the time-series memtable (numbers 1..5): no flush, so no file takes part
// in the read.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("sst_format", "primary_key")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region,
Rows {
schema,
rows: test_util::build_rows_for_key("1", 0, 5, 0),
},
)
.await;
// A whole-domain slice at 3 next to a piece slice at 1: no row of the memtable can be
// attributed to a piece, and the region-level floor (1) would deliver the rows 2 and 3
// the more advanced piece has already consumed.
let err = match engine
.scan_batch(
region,
creator_cursor_scan(
region,
vec![
CursorShard::whole_domain(3),
partition_str_slice_cursor("0", "5", 1),
],
1,
20,
),
true,
)
.await
{
Err(err) => err,
Ok(mut stream) => match stream.try_next().await {
Err(err) => err,
Ok(_) => panic!("an unresolvable memtable piece with disagreeing cursors must fail"),
},
};
let message = format!("{err}");
assert!(
message.contains("exact sequence range unavailable"),
"the shared exact-range contract prefix must reach the caller: {message}"
);
assert!(
message.contains("the memtable of region")
&& message.contains("covers the whole value domain"),
"the failure must name the memtable and say what could not be resolved: {message}"
);
// One cursor value for every candidate: the region-level floor is the per-row answer, so
// the rows above 1 are delivered exactly as before.
let mut rows = scan_flat_row_sequences(
&engine,
region,
creator_cursor_scan(
region,
vec![
CursorShard::whole_domain(1),
partition_str_slice_cursor("0", "5", 1),
],
1,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
rows,
"one cursor value for every piece is the region-level floor of the whole read"
);
}
/// The same per-row rule for a **bulk** memtable: a bulk part keeps the tag columns and the
/// physical sequence of every row as real columns, so the piece a row belongs to is resolved
/// per row there too, instead of by the single floor of the region.
///
/// As above, the rows of the piece consumed up to 5 (3, 4 and 5) are not delivered again
/// while the row at 6 of the piece consumed up to 2 still is.
#[tokio::test]
async fn test_read_row_sequence_splits_bulk_memtable_rows_by_the_expression_of_each_row() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_bulk_memtable_rows").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region = RegionId::new(1, 1);
// Five rows of the left expression (numbers 1..5) and one row of the right one
// (number 6), all of them in the bulk memtable: no flush, so no file takes part in the
// read, and `preserve_row_sequence` keeps the exact `(C, H]` delta admissible.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.insert_option("memtable.type", "bulk")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region, RegionRequest::Create(request))
.await
.unwrap();
let mut rows = test_util::build_rows_for_key("1", 0, 5, 0);
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
test_util::put_rows(&engine, region, Rows { schema, rows }).await;
// The rows really are in a bulk memtable, so the read below goes through a bulk part
// and the per-row rule there, not through the time-series memtable.
assert!(
matches!(
engine
.get_region(region)
.unwrap()
.version_control
.current()
.version
.options
.memtable,
Some(crate::region::options::MemtableOptions::Bulk(_))
),
"the region must hold the bulk memtable"
);
// One cursor value for every piece: the delivered rows are exactly the rows above the
// region-level floor 2, which is what the read delivered before the per-row rule.
let mut rows = scan_flat_row_sequences(
&engine,
region,
creator_cursor_scan(
region,
vec![
partition_str_slice_cursor("0", "5", 2),
partition_str_slice_cursor("5", "9", 2),
],
2,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)],
rows,
"one cursor value for every piece is the region-level floor of the whole read"
);
// The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed,
// the row at 6 belongs to the right one and stays live.
let mut rows = scan_flat_row_sequences(
&engine,
region,
creator_cursor_scan(
region,
vec![
partition_str_slice_cursor("0", "5", 5),
partition_str_slice_cursor("5", "9", 2),
],
2,
20,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(5000, 6)],
rows,
"each bulk memtable row is filtered by the cursor of the piece it belongs to: the \
rows at 3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not"
);
}
/// A row whose number a substitution produced is hidden **and reported** by the substitution
/// rule (`SubstitutedRowRanges`), so per-row slice selection must leave it to that rule
/// instead of dropping it silently: its number says nothing about progress.
#[tokio::test]
async fn test_read_row_sequence_leaves_substituted_rows_to_the_cut() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_leaves_substituted_rows").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// Numbers 1..6, all in the left expression's domain, and the cut 3 says a substitution
// produced the first three of them.
let (_, source_file) = build_foreign_source_file(&engine, source, 6, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 7, true, Some(3));
// The left slice is consumed up to 2, so only the rows 4, 5 and 6 are above it; the
// substituted rows 1..3 are dropped by the cut and their window is reported.
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("", "5", 2),
partition_str_slice_cursor("5", "z", 0),
],
1,
20,
),
)
.await;
assert_eq!(
vec![3000, 4000, 5000],
timestamps,
"the substituted rows are hidden by the cut, the rest is above the slice cursor"
);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 2_000,
}],
}],
substituted,
"the substituted rows are still reported for recomputation"
);
}
/// A physical-sequence read keeps an adopted file's own column: with the switch on, the rows
/// carry the numbers their writer allocated (1, 2, 3), not the holder's admission barrier
/// (4). With the switch off the reader virtualizes every row at the barrier, which is the
/// behavior compaction and ordinary queries depend on.
#[tokio::test]
async fn test_read_row_sequence_keeps_physical_column_of_foreign_file() {
let mut env =
TestEnv::with_prefix("test_read_row_sequence_keeps_physical_column_of_foreign_file").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
// The bytes carry no substitution, so nothing is substituted either way.
adopt_foreign_file(&engine, target, source_file, 4, true, None);
let rows =
scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await;
assert_eq!(
vec![(0, 1), (1000, 2), (2000, 3)],
rows,
"a physical-sequence read must keep the source's own numbering"
);
// The default reader substitutes the handle's barrier, which is why the design needs
// the switch: every row looks published by the import.
let rows = scan_flat_row_sequences(&engine, target, physical_sequence_scan(false)).await;
assert_eq!(vec![(0, 4), (1000, 4), (2000, 4)], rows);
}
/// Rows whose number a substitution produced are substituted, and the ranges they occupy
/// are reported, so Flow recomputes them instead of counting them again.
#[tokio::test]
async fn test_read_row_sequence_hides_rows_below_substituted_cut() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_rows_below_cut").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
// Rows at or below 2 carry a substituted number; only the row at 3 is this file's own.
adopt_foreign_file(&engine, target, source_file, 4, true, Some(2));
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
adopted_physical_sequence_scan(source),
)
.await;
assert_eq!(
vec![2000],
timestamps,
"the two substituted rows must not reach the caller"
);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 1000,
}],
}],
substituted,
"the ranges of the substituted rows must travel with the result"
);
// The surviving row carries its own number, not the barrier.
let rows =
scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await;
assert_eq!(vec![(2000, 3)], rows);
// With the switch off nothing is substituted and no range is reported: the query keeps
// today's substitution, which is what compaction and ordinary reads see.
let (timestamps, substituted) =
scan_partition_substituted_row_ranges(&engine, target, physical_sequence_scan(false)).await;
assert_eq!(vec![0, 1000, 2000], timestamps);
assert!(substituted.is_empty());
}
/// A legacy import states `Some(0)`: the column carries no per-row numbering at all, so every
/// row is substituted and the whole time range is reported.
#[tokio::test]
async fn test_read_row_sequence_hides_all_rows_of_legacy_cut() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_all_rows_legacy_cut").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// A legacy file: its `__sequence` column carries no per-row numbering at all, which is
// exactly what the substituted cut `Some(0)` states. The import still re-marks the handle
// as trusted, so the physical read is admissible and every row is substituted.
let (_, source_file) = build_foreign_source_file(&engine, source, 3, false).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 4, true, Some(0));
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
adopted_physical_sequence_scan(source),
)
.await;
assert!(timestamps.is_empty(), "a legacy cut hides every row");
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 2000,
}],
}],
substituted,
"every substituted row is inside the reported range"
);
}
/// Raises the region's committed watermark to `sequence`, which is what an admission does: the
/// manifest handler stamps the imported files with `last_sequence + 1` and sets
/// `committed_sequence` to it in the same action list (`worker/handle_manifest.rs`). Local writes
/// that follow are therefore numbered above the constant the holder substitutes for the imported
/// rows, which is the state the reader below is written for.
fn raise_committed_watermark(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
sequence: u64,
) {
let region = engine.get_region(region_id).unwrap();
let edit = RegionEdit {
files_to_add: vec![],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: Some(sequence),
..Default::default()
};
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
}
/// A compaction output is a **local** file, and a local file states a substituted cut too: the
/// merge substitutes the handle bound of every foreign input for its rows and the output states
/// the bound the merge produced (`sst/file.rs::substituted_up_to_after_merge`). Those rows carry
/// a number this region never allocated, so the cut has to hide them here as well — a reader
/// that trusts "local means nothing is substituted" delivers them again on every round, and Flow
/// counts the same rows twice.
#[tokio::test]
async fn test_read_row_sequence_hides_substituted_rows_of_local_compaction_output() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_hides_local_compaction_cut").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
// The holder of the repartition target, created the way `create_foreign_target` creates it.
// The request is kept because the test has to write a local row of the same schema.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(target, RegionRequest::Create(request))
.await
.unwrap();
// Admitted at barrier 4, with the cut 2 the bytes of the imported file carry.
adopt_foreign_file(&engine, target, source_file, 4, true, Some(2));
raise_committed_watermark(&engine, target, 4);
// One local row of the holder itself: the region numbers it 5, above the constant the
// reader substitutes for the imported rows.
test_util::put_rows(
&engine,
target,
Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key("0", 3, 4, 0),
},
)
.await;
test_util::flush_region(&engine, target, None).await;
// Merge the imported and the local file, as a background compaction of the target would.
engine
.handle_request(
target,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 60,
}),
parallelism: None,
time_range: None,
}),
)
.await
.unwrap();
let version = engine.get_region(target).unwrap().version();
let outputs = version
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.collect::<Vec<_>>();
assert_eq!(1, outputs.len(), "both input files are merged into one");
let output = outputs[0].meta_ref();
assert_eq!(target, output.region_id, "the output is a local file");
// The merge read the imported rows at this region's own barrier (4), so that number is what
// they now carry, and the local row kept the number the region gave it (5).
assert_eq!(Some(4), output.substituted_up_to);
// A cursor below the cut (0 < 4) must not be handed the rows the merge substituted: they are
// hidden and their time range is reported, so the caller recomputes exactly that window
// instead of receiving the rows a second time.
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
ScanRequest {
exact_sequence_range: true,
read_row_sequence: true,
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(5),
..Default::default()
},
)
.await;
assert_eq!(
vec![3000],
timestamps,
"the three substituted rows must not be delivered again: only the local row survives"
);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 2000,
}],
}],
substituted,
"the rows the cut of the local output hides are still reported for recomputation"
);
}
/// An exact `(C, H]` read of a region measured only by this request: both bounds are this
/// region's own numbers and the read keeps the physical sequence column.
fn local_exact_scan(min: u64, max: u64) -> ScanRequest {
ScanRequest {
exact_sequence_range: true,
read_row_sequence: true,
memtable_min_sequence: Some(min),
memtable_max_sequence: Some(max),
..Default::default()
}
}
/// A **local** file states a substitution as well: a merge substitutes a file-level constant
/// for the rows of its foreign inputs and records the bound it produced
/// (`sst/file.rs::substituted_up_to_after_merge`), so a local file may carry
/// `preserve_row_sequence = false` **and** a substituted cut.
///
/// Such a file is attributable. The physical-sequence read hides the rows at or below the cut
/// and reports their time windows, and every row above the cut carries a number this region
/// allocated, which the scan's own `(C, H]` bounds row by row — so the region keeps serving
/// its exact range instead of failing every later delta closed. A local file with no marker
/// **and** no cut has nothing to attribute its rows with, and still fails closed.
#[tokio::test]
async fn test_read_row_sequence_keeps_exact_sequence_range_of_local_file_with_cut() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_local_file_with_cut").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: test_util::build_rows_for_key("0", 0, 3, 0),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let file = engine
.get_region(region_id)
.unwrap()
.version()
.ssts
.levels()
.iter()
.flat_map(|level| level.files.values())
.next()
.expect("flushed file")
.meta_ref()
.clone();
assert_eq!(region_id, file.region_id);
assert!(file.preserve_row_sequence);
// The merge that produced this file substituted the constant 2 for the rows it took
// from a foreign input: those bytes carry 2, the row that stayed local carries 3.
let mut substituted = file.clone();
substituted.preserve_row_sequence = false;
substituted.substituted_up_to = Some(2);
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![substituted.clone()],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
// The rows at or below the cut are hidden and reported, so the caller recomputes them
// instead of counting them again; the row above it is delivered.
let (timestamps, substituted_ranges) =
scan_partition_substituted_row_ranges(&engine, region_id, local_exact_scan(0, 4)).await;
assert_eq!(vec![2000], timestamps);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: region_id.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 1000,
}],
}],
substituted_ranges,
"the rows the cut hides are reported for recomputation"
);
// What remains is filtered by this region's own `(C, H]`: a cursor that already consumed
// the row above the cut receives nothing, which is the exactness the range promises.
let (timestamps, _) =
scan_partition_substituted_row_ranges(&engine, region_id, local_exact_scan(3, 4)).await;
assert!(
timestamps.is_empty(),
"a local file's rows above its cut are filtered by (C, H]"
);
// Without the cut the same file has nothing that attributes its rows, so the region
// refuses the exact range instead of delivering rows outside `(C, H]`.
let mut unmarked = substituted;
unmarked.substituted_up_to = None;
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![unmarked],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
..Default::default()
},
)
.await
.unwrap();
// The same request that was served above now has no evidence left: both bounds are still
// enforceable against the flushed frontier, so the capability check is what rejects it.
let err = engine
.scanner(region_id, local_exact_scan(3, 4))
.await
.err()
.expect("a local file with no marker and no cut must deny the exact range");
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"unexpected error: {err:?}"
);
}
/// An import re-marks an adopted file with `preserve_row_sequence = false` and copies its bytes
/// verbatim, so the column still carries the creator's numbers and the file's cut still says
/// which of them a substitution produced. A physical-sequence read must therefore ignore the
/// marker: it keeps the physical column and hides the rows the cut covers, and its own
/// substituted cut stays the only thing that decides what a Flow cursor may compare.
#[tokio::test]
async fn test_read_row_sequence_splits_imported_file_without_marker() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_imported_file").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
// What an import of a file whose bytes already carry a substitution publishes: the handle
// is re-marked as marking nothing, holds barrier 4, and states the cut 2 the bytes carry.
adopt_foreign_file(&engine, target, source_file, 4, false, Some(2));
let (timestamps, substituted) = scan_partition_substituted_row_ranges(
&engine,
target,
adopted_physical_sequence_scan(source),
)
.await;
assert_eq!(
vec![2000],
timestamps,
"the two substituted rows must not reach the caller even though the marker is off"
);
assert_eq!(
vec![common_recordbatch::adapter::SubstitutedRowRanges {
region_id: target.as_u64(),
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 0,
end_millis: 1000,
}],
}],
substituted,
"the ranges of the substituted rows must travel with the result"
);
// The surviving row carries the creator's number the bytes hold, not the barrier.
let rows =
scan_flat_row_sequences(&engine, target, adopted_physical_sequence_scan(source)).await;
assert_eq!(vec![(2000, 3)], rows);
// With the switch off nothing changes: the reader substitutes the handle's barrier for
// every row and reports no window, which is what compaction and ordinary reads depend on.
let (timestamps, substituted) =
scan_partition_substituted_row_ranges(&engine, target, physical_sequence_scan(false)).await;
assert_eq!(vec![0, 1000, 2000], timestamps);
assert!(substituted.is_empty());
let rows = scan_flat_row_sequences(&engine, target, physical_sequence_scan(false)).await;
assert_eq!(vec![(0, 4), (1000, 4), (2000, 4)], rows);
}
/// A `cut = None` adopted file is filtered by the creator's cursor exactly like one that
/// states a cut. Its numbers were allocated in the creator's domain whether or not a
/// substitution touched them, so the holder's own `(C, H]` neither bounds them nor may
/// replace the creator's slice.
#[tokio::test]
async fn test_read_row_sequence_filters_adopted_file_without_cut_by_creator_cursor() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_adopted_without_cut").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// The creator consumed up to 3, so only its rows 4 and 5 are still owed. The holder's
// own cursor (0 in this scan) would deliver all five again.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(3)], 0, 10),
)
.await;
assert_eq!(
vec![(3000, 4), (4000, 5)],
rows,
"an adopted file without a cut is still bounded by the creator's cursor"
);
}
/// A creator slice that states the last sequence its delta covers bounds an adopted file from
/// above as well: a row above that bound was numbered after the delta this read stands for,
/// so delivering it here reports identity the caller has not consumed yet while its marker
/// stays below the row's number.
#[tokio::test]
async fn test_read_row_sequence_drops_adopted_rows_above_creator_upper_bound() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_creator_upper_bound").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// The creator's file states the numbers 1..5 and no cut, so the cursor decides alone.
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// The delta is `(1, 3]`: rows 4 and 5 carry numbers the creator's cursor did not consume
// and its bound does not cover, so this round must not read them.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![CursorShard::whole_domain(1).with_until(3)],
0,
10,
),
)
.await;
assert_eq!(
vec![(1000, 2), (2000, 3)],
rows,
"the rows above the creator's upper bound belong to a later delta, not to this read"
);
// The bound is a filter on the creator's domain, not a change of the cursor: stating a
// bound that covers every row delivers every row above the cursor, as before.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![CursorShard::whole_domain(1).with_until(5)],
0,
10,
),
)
.await;
assert_eq!(vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], rows);
}
/// A slice that states no upper bound keeps the unbounded `(cursor, +inf)` filter it always
/// had: the bound is optional evidence, and a read that lacks it must not lose a row that no
/// bound excludes.
#[tokio::test]
async fn test_read_row_sequence_reads_above_cursor_without_creator_upper_bound() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_without_upper_bound").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10),
)
.await;
assert_eq!(
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
rows,
"without a bound every row above the creator's cursor is still owed"
);
}
/// Several candidate slices: the file-level upper bound is the **least** bound any of them
/// states, because the file-level filter cannot tell which slice a row belongs to. The
/// counterexample this pins: the slice holding the file's rows proves the delta ends at 3
/// while another candidate's bound reaches 9, and reading up to 9 delivers rows 4 and 5,
/// which no slice yields this round.
#[tokio::test]
async fn test_read_row_sequence_takes_the_least_creator_upper_bound() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_least_upper_bound").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// One file stating no expression, so every slice of the creator is a candidate for it.
// Its five rows carry the tag `0`, i.e. they all fall in the `[0, 5)` slice.
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
assert_eq!(None, source_file.partition_expr);
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
// The slice the file's rows belong to: consumed up to 1, delta ends at 3.
partition_str_slice_cursor("0", "5", 1).with_until(3),
// A candidate that overlaps no row of this file, with a looser bound.
partition_str_slice_cursor("5", "9", 3).with_until(9),
],
0,
10,
),
)
.await;
assert_eq!(
vec![(1000, 2), (2000, 3)],
rows,
"the file-level bound is the least bound of the candidates, so row 4 is left out"
);
}
/// A creator this scan has no cursor slice for fails closed. Reading the file against this
/// region's own `(C, H]` compares two sequence domains, and reading it unfiltered delivers
/// every already consumed row again on every round; the scan reports the shared
/// "exact range unavailable" contract instead of choosing one of them.
#[tokio::test]
async fn test_read_row_sequence_fails_closed_without_creator_cursor() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 4, true, None);
// No creator slice, and no cut either: the file states nothing this scan can filter
// with.
let mut stream = engine
.scan_batch(target, physical_sequence_scan(true), true)
.await
.unwrap();
let err = match stream.try_next().await {
Err(err) => err,
Ok(_) => panic!("a foreign file without a creator cursor must fail closed"),
};
let message = format!("{err}");
assert!(
message.contains("exact sequence range unavailable"),
"the shared exact-range contract prefix must reach the caller: {message}"
);
assert!(
message.contains("no cursor slice of its creator region"),
"the failure must say what is missing: {message}"
);
}
/// The `Display` of `err` and of every cause below it, one per line.
///
/// A file-level decision is taken while the file is pruned, and the pruner reports a failed
/// file through a wrapper whose own `Display` does not repeat the cause, so the failure is
/// found in the chain.
fn error_chain(err: &Error) -> String {
let mut text = format!("{err}");
let mut source = std::error::Error::source(err);
while let Some(cause) = source {
text.push('\n');
text.push_str(&format!("{cause}"));
source = cause.source();
}
text
}
/// The counterexample to the file-level fallback of a physical-sequence read: when the
/// per-row rule of a file cannot be applied, the file is bounded by the **least** advanced
/// candidate. That floor is exact only while every candidate carries it — with several cursor
/// values it re-delivers the rows a more advanced piece has already consumed, so the read
/// fails instead of degrading an exact read into a duplicate.
///
/// Two shapes the per-row rule cannot apply, both on a file of an adopted creator: a slice
/// identity this build cannot read back, and a slice covering the whole value domain.
#[tokio::test]
async fn test_read_row_sequence_fails_closed_when_pieces_disagree_and_piece_is_unresolved() {
let mut env =
TestEnv::with_prefix("test_read_row_sequence_fails_closed_disagreeing_pieces").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// One file stating no expression, so every slice of the creator is a candidate for it.
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
assert_eq!(None, source_file.partition_expr);
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// The JSON `"MaxValue"` is a partition *bound*, not an expression: this build cannot read
// it back, so the file cannot be split per row. The two candidates carry different
// cursors, so the file-level floor (1) would deliver the rows 2 and 3 a piece consumed up
// to 3 again.
let unreadable = |cursor| CursorShard::new(Some("\"MaxValue\"".to_string()), cursor);
let mut stream = engine
.scan_batch(
target,
creator_cursor_scan(
source,
vec![partition_str_slice_cursor("0", "5", 1), unreadable(3)],
0,
10,
),
true,
)
.await
.unwrap();
let err = match stream.try_next().await {
Err(err) => err,
Ok(_) => {
panic!("an unreadable slice identity with disagreeing cursors must fail the read")
}
};
let message = error_chain(&err);
assert!(
message.contains("exact sequence range unavailable"),
"the shared exact-range contract prefix must reach the caller: {message}"
);
assert!(
message.contains("cannot resolve a per-piece cursor"),
"the failure must say what could not be resolved: {message}"
);
// One cursor value for every candidate: the file-level floor *is* the per-row answer, so
// the unreadable identity keeps today's fallback and the rows above it are delivered.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![partition_str_slice_cursor("0", "5", 1), unreadable(1)],
0,
10,
),
)
.await;
assert_eq!(
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
rows,
"with one cursor value the file-level floor is exact and nothing is dropped"
);
// A whole-domain slice cannot be evaluated per row either: it applies to every row, so no
// slice expression can tell which piece a row belongs to. With disagreeing cursors the
// same rule applies.
let mut stream = engine
.scan_batch(
target,
creator_cursor_scan(
source,
vec![
CursorShard::whole_domain(3),
partition_str_slice_cursor("0", "5", 1),
],
0,
10,
),
true,
)
.await
.unwrap();
let err = match stream.try_next().await {
Err(err) => err,
Ok(_) => panic!("a whole-domain slice with disagreeing cursors must fail the read"),
};
let message = error_chain(&err);
assert!(
message.contains("cannot resolve a per-piece cursor")
&& message.contains("covers the whole value domain"),
"the failure must say that the slice covers the whole domain: {message}"
);
// The same whole-domain read with one cursor value for every candidate keeps the
// file-level floor, exactly as before.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
CursorShard::whole_domain(1),
partition_str_slice_cursor("0", "5", 1),
],
0,
10,
),
)
.await;
assert_eq!(
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
rows,
"one cursor value for every piece is the file-level floor of the whole file"
);
}
/// The third shape the per-row rule cannot answer: a row of the file that **no** candidate
/// expression selects, i.e. a row outside the value domain of every piece of the creator.
///
/// Such a row has no piece to attribute it to, so only the least advanced candidate is left.
/// That floor is exact while every candidate carries the same cursor value — it then *is* what
/// the row's own piece states — and says nothing once they differ: it delivers the rows a more
/// advanced piece already consumed, so the read fails instead of replaying them.
#[tokio::test]
async fn test_read_row_sequence_fails_closed_when_no_piece_selects_a_row() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_unselected_row").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// One file of the creator: four rows of the series `k0 = "1"`, inside the domain of the
// left piece (`k0 < "5"`), and one row of `k0 = "9"`, outside the domain of both candidates.
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
let mut rows = test_util::build_rows_for_key("1", 0, 4, 0);
rows.extend(test_util::build_rows_for_key("9", 4, 5, 0));
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
test_util::flush_region(&engine, source, None).await;
let source_file = manifest_files(&engine, source)
.await
.into_values()
.next()
.expect("flushed file");
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// The candidates carry 5 and 2. The row at 5 (`k0 = "9"`) belongs to no piece, and the
// least advanced cursor (2) does not stand for the pieces: it would deliver the rows 3 and
// 4 the left piece already consumed up to 5.
let mut stream = engine
.scan_batch(
target,
creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("0", "5", 5),
partition_str_slice_cursor("5", "9", 2),
],
0,
10,
),
true,
)
.await
.unwrap();
let err = match stream.try_next().await {
Err(err) => err,
Ok(_) => panic!("a row no candidate selects with disagreeing cursors must fail the read"),
};
let message = error_chain(&err);
assert!(
message.contains("exact sequence range unavailable"),
"the shared exact-range contract prefix must reach the caller: {message}"
);
assert!(
message.contains("cannot resolve a per-piece cursor"),
"the failure must say what could not be resolved: {message}"
);
assert!(
message.contains("match no candidate creator cursor slice") && message.contains("(2..=5)"),
"the failure must name the unselected row and the cursors' own span: {message}"
);
// One cursor value for every candidate: the least advanced cursor is then every piece's
// cursor, so the row outside both domains keeps today's treatment and nothing is dropped.
let mut rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(
source,
vec![
partition_str_slice_cursor("0", "5", 2),
partition_str_slice_cursor("5", "9", 2),
],
0,
10,
),
)
.await;
rows.sort_unstable();
assert_eq!(
vec![(2000, 3), (3000, 4), (4000, 5)],
rows,
"with one cursor value the row no candidate selects is bounded by it exactly, so the \
rows above 2 are delivered and the rows at or below it are not"
);
}
/// The creator's cursor and the holder's snapshot are two different sequence domains, so a
/// foreign file is filtered by the creator's cursor alone — never by the holder's `(C, H]`,
/// which is what bounds the rows of every *local* file of the same scan.
///
/// The counterexample this pins: the creator published the rows `10..=12` while its cursor
/// sits at 9, and the holder admitted the file at barrier 6 with its own cursor at 6. The
/// holder's range is then empty (`(6, 6]`) and its cursor stands exactly at the file's
/// admission barrier, so a filter or a file-pruning rule that uses either of them drops all
/// three live rows — for good, because both repeat on every round.
#[tokio::test]
async fn test_read_row_sequence_ignores_holder_bounds_for_foreign_file() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_bounds").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 12, true).await;
create_foreign_target(&engine, target).await;
// Admitted at barrier 6: below the numbers its bytes carry, which is the whole point.
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// The creator consumed up to 9; the holder is caught up, so its cursor *and* its
// snapshot bound both stand at the file's admission barrier.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(9)], 6, 6),
)
.await;
assert_eq!(
vec![(9000, 10), (10_000, 11), (11_000, 12)],
rows,
"the rows above the creator's cursor must be delivered although the holder's own \
range is empty and the file sits at its admission barrier"
);
// The same file selected by a scan whose holder range is *not* empty: the creator's
// cursor still decides, so the holder's upper end must not truncate the file either.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(9)], 6, 7),
)
.await;
assert_eq!(
vec![(9000, 10), (10_000, 11), (11_000, 12)],
rows,
"a holder bound above the barrier must not cut the creator's rows"
);
// A creator cursor below every row still filters: what the creator consumed is not
// delivered again, whether or not it is above the holder's bound.
let rows = scan_flat_row_sequences(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(11)], 6, 6),
)
.await;
assert_eq!(
vec![(11_000, 12)],
rows,
"row 11 is at the cursor, row 12 above it"
);
}
/// A physical row-sequence read needs the creator's cursor slice and the adopted file's
/// substituted cut, and the `PerSeries` distribution applies neither: its per-series readers
/// bound a file by this region's own `(C, H]` only, and its legacy distributor reads the
/// same files through the plain flat reader. The combination is therefore refused with the
/// shared "exactness is not provable" contract instead of being silently approximated. A
/// plain `PerSeries` read is unaffected.
#[tokio::test]
async fn test_read_row_sequence_rejects_per_series_distribution() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_rejects_per_series").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 3, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 4, true, Some(2));
// Every other reader of the same rows is untouched: an ordinary `PerSeries` read reads
// the file (substituted rows and all) through the per-series path.
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
};
let mut stream = engine.scan_batch(target, request, true).await.unwrap();
let mut num_rows = 0;
while let Some(batch) = stream.try_next().await.unwrap() {
num_rows += match batch {
crate::read::stream::ScanBatch::RecordBatch(batch) => batch.num_rows(),
crate::read::stream::ScanBatch::Series(series) => series.num_rows(),
};
}
assert_eq!(3, num_rows, "a plain PerSeries read must keep working");
// The physical-sequence read asks for the same distribution: refused at construction,
// before any file is opened.
let rejected = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..creator_cursor_scan(source, vec![CursorShard::whole_domain(0)], 0, 10)
};
let err = match engine.scan_batch(target, rejected, true).await {
Ok(_) => panic!("read_row_sequence + PerSeries must be refused"),
Err(err) => err,
};
let message = format!("{err}");
assert!(
message.contains("exact sequence range unavailable"),
"the shared exact-range contract prefix must reach the caller: {message}"
);
assert!(
message.contains("the PerSeries distribution cannot carry a physical row-sequence read"),
"the refusal must name the combination: {message}"
);
}
/// The read reports which `(region, expression slice)` pairs it observed, so the owner of a
/// `(region, slice)` cursor can split a whole-domain entry and advance only the slices this
/// round actually read. A file whose expression cannot be read back states the region's
/// complete domain.
#[tokio::test]
async fn test_read_row_sequence_reports_observed_slices() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_observed_slices").await;
let engine = env.create_engine(MitoConfig::default()).await;
let narrow = RegionId::new(1, 2);
let coarse = RegionId::new(1, 3);
let target = RegionId::new(1, 1);
// One creator's file states `[50, 100)`.
let (_, mut narrow_file) = build_foreign_source_file(&engine, narrow, 3, true).await;
narrow_file.partition_expr = Some(partition_slice(50, 100).into());
// The other states no expression at all, so it can only be reported as the complete
// domain.
let (_, coarse_file) = build_foreign_source_file(&engine, coarse, 2, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, narrow_file, 4, true, None);
adopt_foreign_file(&engine, target, coarse_file, 5, true, None);
let request = ScanRequest {
exact_sequence_range: true,
read_row_sequence: true,
memtable_min_sequence: Some(0),
memtable_max_sequence: Some(10),
creator_cursor_shards: Some(Arc::new(BTreeMap::from([
(narrow.as_u64(), vec![CursorShard::whole_domain(0)]),
(coarse.as_u64(), vec![CursorShard::whole_domain(0)]),
]))),
..Default::default()
};
let observed = scan_partition_observed_slices(&engine, target, request).await;
let mut expected = vec![
common_recordbatch::adapter::ObservedPartitionExpr::new(
narrow.as_u64(),
Some(partition_slice_identity(50, 100)),
),
common_recordbatch::adapter::ObservedPartitionExpr::whole_domain(coarse.as_u64()),
];
expected.sort_unstable();
assert_eq!(
expected, observed,
"every file the scan read reports its creator and the value domain it states"
);
}
/// Scans one partition the way a datanode does and returns the timestamps it delivered together
/// with the adopted files' creators its terminal metrics report.
async fn scan_partition_rows_and_foreign_creators(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
request: ScanRequest,
) -> (Vec<i64>, Option<Vec<u64>>) {
use store_api::region_engine::QueryScanContext;
let scanner = engine.handle_query(region_id, request).await.unwrap();
let mut stream = scanner
.scan_partition(
&QueryScanContext::default(),
&ExecutionPlanMetricsSet::new(),
0,
)
.unwrap();
let mut timestamps = Vec::new();
while let Some(batch) = stream.try_next().await.unwrap() {
let column = batch
.column_by_name("ts")
.expect("time index column")
.clone();
timestamps.extend_from_slice(crate::read::timestamp_array_to_i64_slice(&column));
}
let creators = stream
.metrics()
.and_then(|metrics| metrics.foreign_file_row_creators);
(timestamps, creators)
}
/// A read of an adopted file names the region that created it, so a caller that must not count
/// a row above its creator's proved watermark learns that this read could have delivered one.
#[tokio::test]
async fn test_read_row_sequence_reports_foreign_file_row_creators() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_row_creators").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
let (timestamps, creators) = scan_partition_rows_and_foreign_creators(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10),
)
.await;
assert_eq!(vec![1000, 2000, 3000, 4000], timestamps);
assert_eq!(
Some(vec![source.as_u64()]),
creators,
"the rows of the adopted file reached the output, so its creator is named"
);
}
/// The base read of a repair is a **full** read: it carries no creator cursor and reads every
/// row of the adopted file. It still has to report that it did.
#[tokio::test]
async fn test_read_row_sequence_reports_foreign_file_row_creators_on_a_full_read() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_foreign_rows_full_read").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// No `read_row_sequence`, no creator cursors: nothing filters the adopted file.
let (timestamps, creators) =
scan_partition_rows_and_foreign_creators(&engine, target, ScanRequest::default()).await;
assert_eq!(vec![0, 1000, 2000, 3000, 4000], timestamps);
assert_eq!(
Some(vec![source.as_u64()]),
creators,
"a full read reads every row of the adopted file and says so"
);
}
/// A read that delivers no adopted row answers "none" instead of saying nothing: a caller can
/// tell the two apart only because the empty answer is stated, never defaulted.
#[tokio::test]
async fn test_read_row_sequence_reports_no_foreign_file_row_creators_for_a_local_read() {
let mut env = TestEnv::with_prefix("test_read_row_sequence_no_foreign_row_creators").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
create_foreign_target(&engine, target).await;
adopt_foreign_file(&engine, target, source_file, 6, true, None);
// A cursor of the creator's domain that has consumed every row the file states: the read
// opens the file and delivers nothing.
let (timestamps, creators) = scan_partition_rows_and_foreign_creators(
&engine,
target,
creator_cursor_scan(source, vec![CursorShard::whole_domain(5)], 0, 10),
)
.await;
assert!(timestamps.is_empty(), "{timestamps:?}");
assert_eq!(
Some(Vec::new()),
creators,
"an opened file that delivered no row is not evidence of a delivered row, and the \
answer is still stated"
);
}
/// A read that replays a cached range result does not open the files that produced its rows, so
/// it cannot say which other regions created them: it must answer "unknown" instead of the
/// "delivered none" an empty recorded set would say.
#[tokio::test]
async fn test_range_cache_replay_reports_unknown_foreign_file_row_creators() {
use std::time::Duration;
let mut env =
TestEnv::with_prefix("test_range_cache_replay_unknown_foreign_row_creators").await;
let engine = env
.create_engine(MitoConfig {
// The flat format is the one the range result cache covers.
default_flat_format: true,
range_result_cache_size: ReadableSize::mb(64),
..Default::default()
})
.await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
// A source region that is not in append mode: its reads go through the ordered scan, which
// is the one that reads and fills the range cache.
let request = CreateRequestBuilder::new().build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request.clone()))
.await
.unwrap();
test_util::put_rows(
&engine,
source,
Rows {
schema,
rows: test_util::build_rows_for_key("0", 0, 5, 0),
},
)
.await;
test_util::flush_region(&engine, source, None).await;
let source_file = engine
.get_region(source)
.unwrap()
.manifest_ctx
.manifest()
.await
.files
.values()
.next()
.expect("source file")
.as_ref()
.clone();
engine
.handle_request(target, RegionRequest::Create(request))
.await
.unwrap();
adopt_foreign_file(&engine, target, source_file, 6, false, None);
// A tag filter selects every row of the file and makes the range eligible for the cache.
let scan = || ScanRequest {
filters: vec![col("tag_0").eq(lit(ScalarValue::Utf8(Some("0".to_string()))))],
..Default::default()
};
// The first read opens the adopted file and names its creator.
let (cold_rows, cold_creators) =
scan_partition_rows_and_foreign_creators(&engine, target, scan()).await;
assert_eq!(vec![0, 1000, 2000, 3000, 4000], cold_rows);
assert_eq!(Some(vec![source.as_u64()]), cold_creators);
// A later read of the same range replays the completed result once the publisher ran. It
// delivers the same rows without reading the file, so it states no creator at all.
let warm_creators = tokio::time::timeout(Duration::from_secs(10), async {
loop {
let (rows, creators) =
scan_partition_rows_and_foreign_creators(&engine, target, scan()).await;
assert_eq!(cold_rows, rows, "a replay delivers the rows it replayed");
if creators.is_none() {
return creators;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the range result cache did not replay the range within the timeout");
assert_eq!(
None, warm_creators,
"a replayed range did not open the files its rows came from, so its creators are \
unknown rather than none"
);
}
/// Raw Mito output contains candidates after projection, filtering, and MVCC read processing.
#[tokio::test]
async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() {
use std::collections::HashSet;
use api::v1::{Row, Value};
use common_recordbatch::filter;
use datatypes::arrow::array::Array;
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::SampleRef;
use datatypes::value::Value as DatumValue;
use mito_codec::row_converter::build_primary_key_codec;
use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource};
use store_api::region_request::RegionDeleteRequest;
use table::predicate::Predicate;
let mut env =
TestEnv::with_prefix("test_mito_handle_query_raw_series_candidate_projection_and_mvcc")
.await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().field_num(3).build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let row = |tag: &str, f0: Option<f64>, f1: Option<f64>, gate: f64, ts: i64| Row {
values: vec![
Value {
value_data: Some(ValueData::StringValue(tag.to_string())),
},
Value {
value_data: f0.map(ValueData::F64Value),
},
Value {
value_data: f1.map(ValueData::F64Value),
},
Value {
value_data: Some(ValueData::F64Value(gate)),
},
Value {
value_data: Some(ValueData::TimestampMillisecondValue(ts)),
},
],
};
let put = |rows| {
RegionRequest::Put(RegionPutRequest {
rows: Rows {
schema: schema.clone(),
rows,
},
hint: None,
skip_wal: false,
partition_expr_version: None,
})
};
engine
.handle_request(
region_id,
put(vec![
row("A", Some(1.0), Some(10.0), 1.0, 1000),
row("A", Some(2.0), None, 1.0, 2000),
row("B", Some(5.0), Some(-0.0), 1.0, 1000),
row("B", Some(6.0), Some(60.0), 0.0, 2000),
row("B", None, Some(70.0), 1.0, 3000),
]),
)
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
// Newer write supersedes A@1000; A@2000 is deleted. B@2000 fails the static field_2 predicate.
engine
.handle_request(
region_id,
put(vec![row("A", Some(3.0), Some(30.0), 1.0, 1000)]),
)
.await
.unwrap();
engine
.handle_request(
region_id,
RegionRequest::Delete(RegionDeleteRequest {
rows: Rows {
schema: test_util::delete_rows_schema(
&CreateRequestBuilder::new().field_num(3).build(),
),
rows: vec![Row {
values: vec![
Value {
value_data: Some(ValueData::StringValue("A".to_string())),
},
Value {
value_data: Some(ValueData::TimestampMillisecondValue(2000)),
},
],
}],
},
hint: None,
partition_expr_version: None,
}),
)
.await
.unwrap();
let request = ScanRequest {
projection: Some(vec![2, 1, 4]),
filters: vec![col("field_2").gt(lit(0.0_f64))],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let mut scanner = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
let metadata = scanner.metadata();
let tags = metadata
.column_metadatas
.iter()
.filter(|c| c.semantic_type == SemanticType::Tag)
.map(|c| BoundTag {
column_id: c.column_id,
name: Arc::from(c.column_schema.name.as_str()),
})
.collect::<Vec<_>>();
let source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata.clone(),
logical_tags: tags.into(),
};
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let metrics = ExecutionPlanMetricsSet::default();
let mut raw = Vec::new();
for partition in 0..ranges.len() {
let mut previous_times = HashMap::<Vec<u8>, i64>::new();
let mut stream = scanner
.scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source)
.unwrap()
.expect("supported millisecond PerSeries scan");
assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering());
assert!(stream.schema().eval_grid.is_none());
assert_eq!(
vec!["field_1", "field_0"],
stream
.schema()
.fields
.iter()
.map(|f| f.name.as_ref())
.collect::<Vec<_>>()
);
let mut closed_keys = HashSet::<Vec<u8>>::new();
while let Some(chunk) = stream.try_next().await.unwrap() {
assert!(chunk.metric.is_none());
assert!(
!closed_keys.contains(chunk.primary_key.as_slice()),
"no chunk may follow a key's is_last chunk"
);
let times = chunk.time.as_buffer();
assert_eq!(2, chunk.fields.len());
assert_eq!(times.len(), chunk.fields.get(0).unwrap().len());
assert_eq!(times.len(), chunk.fields.get(1).unwrap().len());
for (index, time) in times.iter().enumerate() {
let SampleRef::Float(f1) = chunk.fields.get(0).unwrap().sample(index) else {
panic!("f1 float")
};
let f0 = match chunk.fields.get(1).unwrap().sample(index) {
SampleRef::Float(v) => Some(v),
SampleRef::Missing => None,
_ => panic!("f0 type"),
};
let key = chunk.primary_key.to_vec();
if let Some(previous) = previous_times.insert(key.clone(), *time) {
assert!(
previous < *time,
"raw time must increase strictly across chunks"
);
}
if chunk.is_last {
closed_keys.insert(chunk.primary_key.to_vec());
}
raw.push((
chunk.primary_key.clone(),
*time,
f1,
f0,
chunk.is_last && index + 1 == times.len(),
));
}
}
}
raw.sort_by(|a, b| a.2.total_cmp(&b.2));
assert_eq!(3, raw.len());
assert!(
raw.iter()
.any(|(_, _, value, _, _)| value.to_bits() == (-0.0_f64).to_bits())
);
let codec = build_primary_key_codec(&metadata);
let mut expected_keys = Vec::new();
for tag in ["A", "B"] {
let mut key = Vec::new();
codec
.encode_values(
&[(metadata.primary_key[0], DatumValue::String(tag.into()))],
&mut key,
)
.unwrap();
expected_keys.push(key);
}
expected_keys.sort();
let mut actual_keys = raw
.iter()
.map(|(key, _, _, _, _)| key.to_vec())
.collect::<Vec<_>>();
actual_keys.sort();
actual_keys.dedup();
assert_eq!(expected_keys, actual_keys);
for key in &actual_keys {
assert_eq!(
1,
raw.iter()
.filter(|(k, _, _, _, last)| k.as_ref() == key && *last)
.count()
);
}
// Compare keyed visible tuples through a separately opened legacy scanner.
// A partition cannot be consumed through both paths.
let mut legacy_request = request.clone();
legacy_request.projection = Some(vec![0, 3, 2, 1, 4]);
legacy_request.preserve_pk_dictionary_encoding = false;
let legacy = engine
.handle_query(region_id, legacy_request)
.await
.unwrap();
let mut batches = Vec::new();
for partition in 0..legacy.properties().num_partitions() {
batches.extend(
legacy
.scan_partition(&QueryScanContext::default(), &metrics, partition)
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap(),
);
}
let candidate_count: usize = batches.iter().map(|batch| batch.num_rows()).sum();
assert_eq!(4, candidate_count);
let predicate = Predicate::to_physical_expr(
&col("field_2").gt(lit(0.0_f64)),
legacy.schema().arrow_schema(),
)
.unwrap();
let batches = batches
.into_iter()
.map(|batch| {
let batch = batch.into_df_record_batch();
let filtered = filter::batch_filter(&batch, &predicate).unwrap();
filtered.project(&[0, 2, 3, 4]).unwrap()
})
.collect::<Vec<_>>();
let visible = batches
.iter()
.flat_map(|batch| {
(0..batch.num_rows()).map(move |r| {
let f1 = batch
.column(1)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
let f0 = batch
.column(2)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
(
batch
.column(0)
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(r)
.to_string(),
batch
.column(3)
.as_any()
.downcast_ref::<TimestampMillisecondArray>()
.unwrap()
.value(r),
f1.value(r),
if f0.is_null(r) {
None
} else {
Some(f0.value(r))
},
)
})
})
.collect::<Vec<_>>();
assert_eq!(
vec![
(1000, -0.0, Some(5.0)),
(1000, 30.0, Some(3.0)),
(3000, 70.0, None)
],
raw.iter()
.map(|(_, t, a, b, _)| (*t, *a, *b))
.collect::<Vec<_>>()
);
let mut visible = visible;
visible.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
let mut raw_visible = raw
.iter()
.map(|(key, time, f1, f0, _)| {
let tag = if key.as_ref() == expected_keys[0].as_slice() {
"A"
} else {
"B"
};
(tag.to_string(), *time, *f1, *f0)
})
.collect::<Vec<_>>();
raw_visible.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
assert_eq!(raw_visible, visible);
// Exercise the production table physical consumer over a fresh real Mito scanner.
use common_query::series_frame::{series_frame_ordering, unpack_raw_series};
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use table::table::scan::RegionScanExec;
let native_scanner = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
let native_metadata = native_scanner.metadata();
let native_tags = native_metadata
.column_metadatas
.iter()
.filter(|c| c.semantic_type == SemanticType::Tag)
.map(|c| BoundTag {
column_id: c.column_id,
name: Arc::from(c.column_schema.name.as_str()),
})
.collect::<Vec<_>>();
let native_source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: native_metadata,
logical_tags: native_tags.into(),
};
let native_plan = Arc::new(RegionScanExec::new(native_scanner, request.clone(), None).unwrap());
let native_plan = native_plan
.try_to_series_scan(native_source)
.unwrap()
.expect("Mito raw-series capability");
let native_schema = native_plan.series_schema().clone();
let native_frames = native_plan
.execute(0, Arc::new(TaskContext::default()))
.unwrap();
// Unpack under the frame's own declaration. A legacy producer declares `KeyThenTime`, and
// only that declaration makes the decoder check that keys increase.
let frame_ordering = series_frame_ordering(native_frames.schema().as_ref()).unwrap();
assert_eq!(
SeriesOrdering::KeyThenTime,
frame_ordering,
"the legacy producer must declare key-then-time frames"
);
let unpacked = unpack_raw_series(native_frames, Some(native_schema)).unwrap();
let native_schema = unpacked.schema().clone();
let mut native = unpacked.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(
vec!["field_1", "field_0"],
native_schema
.fields
.iter()
.map(|field| field.name.as_ref())
.collect::<Vec<_>>()
);
let mut native_visible = native
.drain(..)
.flat_map(|chunk| {
let key = chunk.primary_key.to_vec();
// The frame binding is the raw primary key, so decode it back to the fixture tag to
// keep the raw rows comparable with the legacy path.
let tag = if key == expected_keys[0] {
"A"
} else if key == expected_keys[1] {
"B"
} else {
panic!("unexpected raw primary key {key:?}")
};
let times = chunk.time.as_buffer();
let is_last = chunk.is_last;
let mut rows = Vec::with_capacity(times.len());
for (i, time) in times.iter().enumerate() {
let SampleRef::Float(f1) = chunk.fields.get(0).unwrap().sample(i) else {
panic!("expected f1 float")
};
let f0 = match chunk.fields.get(1).unwrap().sample(i) {
SampleRef::Float(value) => Some(value),
SampleRef::Missing => None,
_ => panic!("expected f0 float or null"),
};
rows.push((
key.clone(),
tag.to_string(),
*time,
f1,
f0,
is_last && i + 1 == times.len(),
));
}
rows
})
.collect::<Vec<_>>();
let mut expected_native = raw
.iter()
.map(|(key, time, f1, f0, _)| (key.to_vec(), *time, *f1, *f0))
.collect::<Vec<_>>();
type NativeRow = (Vec<u8>, String, i64, f64, Option<f64>, bool);
let sort_native = |rows: &mut Vec<NativeRow>| {
rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
};
sort_native(&mut native_visible);
expected_native.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
assert_eq!(
expected_native,
native_visible
.iter()
.map(|(key, _, time, f1, f0, _)| (key.clone(), *time, *f1, *f0))
.collect::<Vec<_>>()
);
for key in &expected_keys {
assert_eq!(
1,
native_visible
.iter()
.filter(|(row_key, _, _, _, _, is_last)| row_key == key && *is_last)
.count()
);
}
let mut decoded_visible = native_visible
.iter()
.map(|(_, tag, time, f1, f0, _)| (tag.clone(), *time, *f1, *f0))
.collect::<Vec<_>>();
decoded_visible.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
assert_eq!(visible, decoded_visible);
// Apply the typed predicate and final projection through the ordinary legacy filter path.
assert_eq!(3, visible.len());
assert_eq!(
vec![
("A".to_string(), 1000, 30.0, Some(3.0)),
("B".to_string(), 1000, -0.0, Some(5.0)),
("B".to_string(), 3000, 70.0, None)
],
visible
);
}
/// A `TwoPhase` scan declares [`SeriesOrdering::KeyThenTime`] on the scanner, every partition
/// stream, and every frame it packs. This is stronger than `Contiguous`: keys must be increasing,
/// in addition to each series' chunks remaining together; the frame adapter validates that claim.
///
/// An ordering the frame cannot carry is rejected by the frame constructor before any poll; that
/// refusal is covered by `common_query::series_frame::tests::interleaved_ordering_is_rejected_before_any_poll`.
#[tokio::test]
async fn test_two_phase_native_raw_stream_declares_key_then_time_frames() {
use common_query::series_frame::{pack_raw_series, series_frame_ordering, unpack_raw_series};
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::SeriesSchema;
use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource};
use store_api::region_request::RegionPutRequest;
let mut env = TestEnv::with_prefix("test_two_phase_native_raw_key_then_time_frames").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let metadata = Arc::new(sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
));
let mut create = CreateRequestBuilder::new().build();
create.column_metadatas = metadata.column_metadatas.clone();
create.primary_key = metadata.primary_key.clone();
create
.options
.insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string());
create
.options
.insert("memtable.type".to_string(), "bulk".to_string());
create
.options
.insert("sst_format".to_string(), "flat".to_string());
let full_schema = test_util::rows_schema(&create);
let mut key_schema = full_schema[0].clone();
key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string();
key_schema.datatype = ColumnDataType::Binary.into();
key_schema.semantic_type = SemanticType::Tag.into();
let row_schema = vec![key_schema, full_schema[5].clone(), full_schema[4].clone()];
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
let sparse_rows = Rows {
schema: row_schema,
rows: vec![
row(vec![
ValueData::BinaryValue(new_sparse_primary_key(&["a", "x"], &metadata, 10, 0)),
ValueData::TimestampMillisecondValue(10),
ValueData::U64Value(1),
]),
row(vec![
ValueData::BinaryValue(new_sparse_primary_key(&["b", "y"], &metadata, 20, 0)),
ValueData::TimestampMillisecondValue(20),
ValueData::U64Value(2),
]),
],
};
engine
.handle_request(
region_id,
RegionRequest::Put(RegionPutRequest {
rows: sparse_rows,
hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
}),
skip_wal: false,
partition_expr_version: None,
}),
)
.await
.unwrap();
test_util::flush_region(&engine, region_id, None).await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let selected = engine.scanner(region_id, request.clone()).await.unwrap();
let Scanner::Series(series) = selected else {
panic!("sparse PerSeries request must use SeriesScan");
};
assert_eq!("two_phase", series.mode());
let mut scanner = engine.handle_query(region_id, request).await.unwrap();
assert_eq!(
SeriesOrdering::KeyThenTime,
scanner.raw_series_ordering().unwrap()
);
let metadata = scanner.metadata();
let source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata.clone(),
logical_tags: metadata
.column_metadatas
.iter()
.filter(|column| {
column.semantic_type == SemanticType::Tag
&& !store_api::storage::consts::is_internal_column(&column.column_schema.name)
&& !store_api::metric_engine_consts::is_metric_engine_internal_column(
&column.column_schema.name,
)
})
.map(|column| BoundTag {
column_id: column.column_id,
name: Arc::from(column.column_schema.name.as_str()),
})
.collect::<Vec<_>>()
.into(),
};
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let metrics = ExecutionPlanMetricsSet::default();
let mut schema: Option<Arc<SeriesSchema>> = None;
let mut chunks = Vec::new();
for partition in 0..ranges.len() {
let stream = scanner
.scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source)
.unwrap()
.unwrap();
// The storage-side contract: every partition stream reports the scanner's declaration.
assert_eq!(scanner.raw_series_ordering().unwrap(), stream.ordering());
assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering());
schema.get_or_insert_with(|| Arc::clone(stream.schema()));
chunks.extend(stream.try_collect::<Vec<_>>().await.unwrap());
}
assert_eq!(
2,
chunks.iter().map(|chunk| chunk.time.len()).sum::<usize>()
);
// The frames the adapter receives carry the key-then-time declaration, which the adapter
// validates through `pack`/`unpack_raw_series`.
let schema = schema.expect("the scan must emit at least one partition stream");
let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new(
Arc::clone(&schema),
source,
SeriesOrdering::KeyThenTime,
chunks,
)))
.unwrap();
let ordering = series_frame_ordering(packed.schema().as_ref()).unwrap();
assert_eq!(SeriesOrdering::KeyThenTime, ordering);
let validated = unpack_raw_series(packed, Some(schema))
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert_eq!(
2,
validated
.iter()
.map(|chunk| chunk.time.len())
.sum::<usize>()
);
}
#[tokio::test]
async fn test_two_phase_raw_partition_out_of_range_keeps_scanner_usable() {
use datatypes::series::samples::SampleRef;
use store_api::region_engine::QueryScanContext;
let mut env = TestEnv::with_prefix("test_two_phase_raw_partition_out_of_range").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await;
let expected = [
(new_sparse_primary_key(&["a", "x"], &metadata, 10, 0), 10, 1),
(new_sparse_primary_key(&["b", "x"], &metadata, 10, 0), 20, 2),
];
put_sparse_rows(
&engine,
region_id,
&row_schema,
expected
.iter()
.map(|(key, time, value)| (key.clone(), *time, *value))
.collect(),
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let Scanner::Series(selected) = engine.scanner(region_id, request.clone()).await.unwrap()
else {
panic!("sparse PerSeries request must use SeriesScan");
};
assert_eq!("two_phase", selected.mode());
let mut scanner = engine.handle_query(region_id, request).await.unwrap();
let source = primary_key_label_source(&scanner.metadata());
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let partitions = scanner.properties().num_partitions();
assert!(partitions > 0, "prepared scan needs an output partition");
let metrics = ExecutionPlanMetricsSet::default();
let ctx = QueryScanContext::default();
// `scan_batch_in_partition` validates the index before it takes that partition's receiver, so
// the first index past the last partition must fail without disturbing scanner state.
let error = match scanner.scan_series_partition(&ctx, &metrics, partitions, &source) {
Ok(_) => {
panic!("partition {partitions} must be rejected by a {partitions}-partitions scan")
}
Err(error) => error,
};
let message = error.to_string();
assert!(
message.contains("out of range") && message.contains(&partitions.to_string()),
"expected a partition range error, got: {message}"
);
// The in-range partition must still read the complete data set.
let stream = scanner
.scan_series_partition(&ctx, &metrics, 0, &source)
.unwrap()
.expect("the raw series scan stays available after a rejected partition");
let mut actual = HashMap::new();
for chunk in stream.try_collect::<Vec<_>>().await.unwrap() {
let times = chunk.time.as_buffer();
for (index, time) in times.iter().enumerate() {
let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(index) else {
panic!("raw fields are converted to float samples");
};
actual.insert((chunk.primary_key.to_vec(), *time), value);
}
}
assert_eq!(
expected.len(),
actual.len(),
"the rejected call must not consume rows"
);
for (key, time, value) in expected {
assert_eq!(Some(&(value as f64)), actual.get(&(key, time)));
}
// A partition can only be scanned once, so this proves the rejected index never took the
// in-range partition's receiver: the error above is raised by the range check alone.
let repeated = match scanner.scan_series_partition(&ctx, &metrics, 0, &source) {
Ok(_) => panic!("partition 0 was already scanned"),
Err(error) => error.to_string(),
};
assert!(
repeated.contains("scan multiple times"),
"expected a repeated-scan error, got: {repeated}"
);
}
/// A `TwoPhase` scan declares [`SeriesOrdering::KeyThenTime`], a stronger claim than
/// `Contiguous` because it also guarantees increasing keys. Each disjoint partition assignment
/// must own exactly its assigned key set, and the concatenated stream must keep each series in one
/// run; packing and unpacking validates the codec sequence.
#[tokio::test]
async fn test_two_phase_raw_stream_stays_key_ordered_across_disjoint_partition_assignments() {
use common_query::series_frame::{pack_raw_series, unpack_raw_series};
use datatypes::series::SeriesOrdering;
use datatypes::series::raw::RawSeriesChunk;
use datatypes::series::samples::{SampleRef, SeriesSchema};
use store_api::region_engine::QueryScanContext;
let mut env = TestEnv::with_prefix("test_two_phase_raw_key_ordered_assignments").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
// Automatic compaction could merge the two flushed SSTs before the scan pins its
// input and make the source-composition assertions below racy.
schedule_compaction_after_edit: false,
min_compaction_interval: Duration::from_secs(60 * 60),
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await;
// A sparse primary key carries the TSID, and `SeriesRange::partition_for` splits the u64 TSID
// domain over the output partitions, so the fixture splits into two disjoint groups of series:
// tsids below 2^63 own partition 0 and tsids at or above 2^63 own partition 1.
let series = [
("a0", 0_u64),
("a1", 1),
("b0", 1_u64 << 63),
("b1", (1_u64 << 63) + 1),
];
let keys = series
.iter()
.map(|(tag, tsid)| new_sparse_primary_key(&[tag, "x"], &metadata, 10, *tsid))
.collect::<Vec<_>>();
// Three write rounds put every series into two SST sources (the first two rounds are flushed)
// plus one memtable source (the last round stays in memory), and the large rounds make a
// series span more than one read batch, so one series is emitted as multiple chunks instead
// of exactly one. The scan input assertions below check that composition instead of only
// checking that something was read.
const LARGE: i64 = 20_000;
const SMALL: i64 = 3;
let rounds: [&[(usize, i64, i64)]; 3] = [
&[(0, 0, LARGE), (1, 0, SMALL), (2, 0, SMALL), (3, 0, LARGE)],
&[
(0, LARGE, 5),
(1, SMALL, SMALL),
(2, SMALL, SMALL),
(3, LARGE, 5),
],
&[
(0, LARGE + 5, 2),
(1, 2 * SMALL, 2),
(2, 2 * SMALL, 2),
(3, LARGE + 5, 2),
],
];
let mut expected_times = HashMap::<Vec<u8>, Vec<i64>>::new();
for spec in rounds {
for &(index, first, count) in spec {
expected_times
.entry(keys[index].clone())
.or_default()
.extend(first..first + count);
}
}
let mut round_rows = Vec::with_capacity(rounds.len());
for (round, spec) in rounds.iter().enumerate() {
let rows = spec
.iter()
.flat_map(|&(index, first, count)| {
let key = keys[index].clone();
(0..count).map(move |offset| {
let time = first + offset;
(key.clone(), time, (time + 1) as u64)
})
})
.collect::<Vec<_>>();
round_rows.push(rows.len());
put_sparse_rows(&engine, region_id, &row_schema, rows).await;
if round + 1 < rounds.len() {
test_util::flush_region(&engine, region_id, None).await;
}
}
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let selected = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(mut scanner) = selected else {
panic!("sparse PerSeries request must use SeriesScan");
};
assert_eq!("two_phase", scanner.mode());
assert_eq!(
SeriesOrdering::KeyThenTime,
scanner.raw_series_ordering().unwrap()
);
// Composition of the pinned scan input: the two flushes pin two SST sources and the third
// write round stays in one memtable source. Each source reports the rows its write round
// wrote, so this asserts the layout instead of only asserting that something was read.
{
let input = scanner.input();
let mut file_rows = input
.files
.iter()
.map(|file| file.num_rows())
.collect::<Vec<_>>();
file_rows.sort_unstable();
let mut expected_file_rows = round_rows[..2].to_vec();
expected_file_rows.sort_unstable();
assert_eq!(
expected_file_rows, file_rows,
"each flushed write round must be one SST source"
);
assert_eq!(2, input.num_files());
assert_eq!(
1,
input.num_memtables(),
"the last round is one memtable range"
);
assert_eq!(
round_rows[2],
input
.memtables
.iter()
.map(|memtable| memtable.stats().num_rows)
.sum::<usize>(),
"the unflushed round must be the memtable's contribution"
);
assert_eq!(
round_rows.iter().sum::<usize>(),
input.total_rows(),
"the sources must add up to every written row"
);
}
let source = primary_key_label_source(&scanner.metadata());
let ranges = scanner
.properties()
.partitions
.clone()
.into_iter()
.flatten()
.collect::<Vec<_>>();
assert!(!ranges.is_empty(), "region scan needs an input range");
// Two output partitions make the candidate distributor create one reader assignment per
// partition, so the scan runs more than one assignment.
let partition_count = 2;
let mut partitions = vec![Vec::new(); partition_count];
for (index, range) in ranges.into_iter().enumerate() {
partitions[index % partition_count].push(range);
}
scanner
.prepare(PrepareRequest {
ranges: Some(partitions),
target_partitions: Some(partition_count),
..Default::default()
})
.unwrap();
assert_eq!(partition_count, scanner.properties().num_partitions());
let metrics = ExecutionPlanMetricsSet::default();
let ctx = QueryScanContext::default();
let mut per_partition = Vec::with_capacity(partition_count);
let mut schema: Option<Arc<SeriesSchema>> = None;
for partition in 0..partition_count {
let stream = scanner
.scan_series_partition(&ctx, &metrics, partition, &source)
.unwrap()
.expect("two-phase raw scan is supported");
assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering());
assert_eq!(
vec!["field_0"],
stream
.schema()
.fields
.iter()
.map(|field| field.name.as_ref())
.collect::<Vec<_>>()
);
schema.get_or_insert_with(|| Arc::clone(stream.schema()));
let chunks = stream.try_collect::<Vec<_>>().await.unwrap();
assert!(
!chunks.is_empty(),
"partition {partition} must own a reader assignment"
);
// Each partition owns exactly the series the TSID split assigned to it, so the two
// assignment streams are non-empty and disjoint.
let mut observed = chunks
.iter()
.map(|chunk| chunk.primary_key.to_vec())
.collect::<Vec<_>>();
observed.sort();
observed.dedup();
let mut assigned = vec![keys[2 * partition].clone(), keys[2 * partition + 1].clone()];
assigned.sort();
assert_eq!(
assigned, observed,
"partition {partition} must own exactly its assigned series"
);
per_partition.push(chunks);
}
// The complete raw series stream of the two-partition scan: each partition's one assignment,
// concatenated in partition order. `test_two_phase_raw_same_partition_multi_round_assignment_
// stays_key_ordered` covers two assignments handed to the same partition.
let complete = per_partition
.into_iter()
.flatten()
.collect::<Vec<RawSeriesChunk>>();
let schema = schema.unwrap();
let complete_rows = complete.iter().map(|chunk| chunk.time.len()).sum::<usize>();
assert_eq!(
expected_times.values().map(Vec::len).sum::<usize>(),
complete_rows,
"the complete stream must carry every written row"
);
// Reuse the frame adapter's cross-chunk validator (private to
// `common_query::series_frame`) by packing and unpacking the complete stream. It rejects a key
// change that was not preceded by that key's final chunk, a key that recurs right after its
// final chunk, timestamps that do not increase across chunks, and a stream whose last chunk is
// not final.
let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new(
Arc::clone(&schema),
source,
SeriesOrdering::KeyThenTime,
complete.clone(),
)))
.unwrap();
let unpacked = unpack_raw_series(packed, Some(schema)).unwrap();
let validated = unpacked.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(
complete_rows,
validated
.iter()
.map(|chunk| chunk.time.len())
.sum::<usize>(),
"packing and unpacking must preserve the complete stream"
);
// `SequenceValidator` checks adjacent chunks only, so also reject non-adjacent recurrence: a
// series interrupted by another series and resumed later would violate key-then-time order.
let mut runs = Vec::<Vec<u8>>::new();
let mut chunks_per_series = HashMap::<Vec<u8>, usize>::new();
for chunk in &complete {
let key = chunk.primary_key.to_vec();
*chunks_per_series.entry(key.clone()).or_default() += 1;
if runs.last() != Some(&key) {
assert!(
!runs.contains(&key),
"a series' chunks must stay contiguous across the concatenated assignments"
);
runs.push(key);
}
}
assert_eq!(keys.len(), runs.len(), "every series appears exactly once");
assert!(
chunks_per_series.values().copied().max().unwrap() > 1,
"the fixture must emit multiple chunks for one series, got {chunks_per_series:?}"
);
assert_eq!(keys.len(), chunks_per_series.len());
for (key, times) in &expected_times {
let observed = complete
.iter()
.filter(|chunk| chunk.primary_key.as_slice() == key.as_slice())
.flat_map(|chunk| chunk.time.as_buffer().iter().copied())
.collect::<Vec<_>>();
assert_eq!(
times, &observed,
"sample positions must increase per series"
);
}
for (index, chunk) in complete.iter().enumerate() {
let next_is_same_series = complete
.get(index + 1)
.is_some_and(|next| next.primary_key.as_slice() == chunk.primary_key.as_slice());
assert_eq!(
!next_is_same_series, chunk.is_last,
"is_last must mark the final chunk of a series"
);
let times = chunk.time.as_buffer();
for (sample, time) in times.iter().enumerate() {
let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(sample) else {
panic!("raw fields are converted to float samples");
};
assert_eq!((*time + 1) as f64, value);
}
}
}
/// Lowers the candidate-series assignment threshold and restores it when dropped.
///
/// The override is process-global, so it is restored from `Drop` to keep a failing assertion or a
/// panic from leaking a weakened threshold into later tests of the same binary. `cargo nextest`
/// (the documented runner for this crate) additionally runs every test in its own process.
struct AssignmentThresholdScope;
impl AssignmentThresholdScope {
fn lower_to(threshold: usize) -> Self {
crate::read::series_scan::set_candidate_series_assignment_threshold(threshold);
Self
}
}
impl Drop for AssignmentThresholdScope {
fn drop(&mut self) {
crate::read::series_scan::set_candidate_series_assignment_threshold(0);
}
}
/// One partition receiving two candidate assignments must still emit one key-then-time stream,
/// a stronger claim than `Contiguous` because keys must also be increasing. The test checks single-run
/// ownership for each series and round-trip validation through the frame codec.
///
/// Without the threshold override a second assignment reaches the same partition only when a
/// single collection round holds `CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD` (1,000,000) candidate
/// series, so this test lowers the threshold instead of writing a million series.
#[tokio::test]
async fn test_two_phase_raw_same_partition_multi_round_assignment_stays_key_ordered() {
use common_query::series_frame::{pack_raw_series, unpack_raw_series};
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::SampleRef;
use store_api::region_engine::QueryScanContext;
// The candidate distributor starts a new assignment as soon as the collected series reach the
// threshold, and the candidate stream hands series over in globally sorted batches of at most
// `METRIC_SERIES_ID_BATCH_SIZE` (500) entries, yielding a trailing batch for the remainder.
// With the threshold lowered to 1 every one of those batches becomes one assignment round, so
// 501 series produce exactly two non-empty rounds: the first 500 sorted series, then the last
// one. Both rounds are addressed to the single output partition, i.e. to one receiver.
const CANDIDATE_BATCH: usize = 500;
const SERIES: usize = CANDIDATE_BATCH + 1;
let _scope = AssignmentThresholdScope::lower_to(1);
let mut env = TestEnv::with_prefix("test_two_phase_raw_same_partition_multi_round").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
// The source-composition assertions below pin the flushed SST until the scan opens.
schedule_compaction_after_edit: false,
min_compaction_interval: Duration::from_secs(60 * 60),
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await;
let tags = (0..SERIES)
.map(|index| format!("s{index}"))
.collect::<Vec<_>>();
let keys = tags
.iter()
.enumerate()
.map(|(index, tag)| {
new_sparse_primary_key(&[tag.as_str(), "x"], &metadata, 10, index as u64)
})
.collect::<Vec<_>>();
// The round split below relies on the candidate stream ordering series by primary key, which
// is the ascending TSID order for this fixture.
let mut sorted_keys = keys.clone();
sorted_keys.sort();
assert_eq!(keys, sorted_keys, "primary keys must sort in TSID order");
// One flushed SST source plus one memtable source. The wide series spans more than one read
// batch, so a series is emitted as several chunks and the round boundary sits next to chunks
// that must stay grouped.
const WIDE: i64 = 20_000;
const SMALL: i64 = 3;
const SECOND_ROUND_FIRST: i64 = 100_000;
let mut expected_times = HashMap::<Vec<u8>, Vec<i64>>::new();
expected_times.insert(
keys[0].clone(),
(0..WIDE)
.chain(SECOND_ROUND_FIRST..SECOND_ROUND_FIRST + 3)
.collect(),
);
for key in &keys[1..] {
expected_times.insert(
key.clone(),
(0..SMALL)
.chain(SECOND_ROUND_FIRST..SECOND_ROUND_FIRST + 3)
.collect(),
);
}
let first_round = std::iter::once((keys[0].clone(), 0_i64, WIDE))
.chain(keys[1..].iter().map(|key| (key.clone(), 0_i64, SMALL)))
.flat_map(|(key, first, count)| {
(0..count).map(move |offset| {
let time = first + offset;
(key.clone(), time, (time + 1) as u64)
})
})
.collect::<Vec<_>>();
let second_round = keys
.iter()
.flat_map(|key| {
(0..SMALL).map(move |offset| {
let time = SECOND_ROUND_FIRST + offset;
(key.clone(), time, (time + 1) as u64)
})
})
.collect::<Vec<_>>();
let (sst_rows, memtable_rows) = (first_round.len(), second_round.len());
put_sparse_rows(&engine, region_id, &row_schema, first_round).await;
test_util::flush_region(&engine, region_id, None).await;
put_sparse_rows(&engine, region_id, &row_schema, second_round).await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let selected = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(mut scanner) = selected else {
panic!("sparse PerSeries request must use SeriesScan");
};
assert_eq!("two_phase", scanner.mode());
assert_eq!(
SeriesOrdering::KeyThenTime,
scanner.raw_series_ordering().unwrap()
);
// The fixture must really be one SST source plus one memtable source, or the two rounds below
// would be explained by something else.
{
let input = scanner.input();
assert_eq!(1, input.num_files());
assert_eq!(
vec![sst_rows],
input
.files
.iter()
.map(|file| file.num_rows())
.collect::<Vec<_>>()
);
assert_eq!(1, input.num_memtables());
assert_eq!(
memtable_rows,
input
.memtables
.iter()
.map(|memtable| memtable.stats().num_rows)
.sum::<usize>()
);
}
let source = primary_key_label_source(&scanner.metadata());
let ranges = scanner
.properties()
.partitions
.clone()
.into_iter()
.flatten()
.collect::<Vec<_>>();
assert!(!ranges.is_empty(), "region scan needs an input range");
// One output partition means every series the distributor assigns belongs to this receiver,
// so both rounds are delivered to partition 0.
scanner
.prepare(PrepareRequest {
ranges: Some(vec![ranges]),
target_partitions: Some(1),
..Default::default()
})
.unwrap();
assert_eq!(1, scanner.properties().num_partitions());
let metrics = ExecutionPlanMetricsSet::default();
let ctx = QueryScanContext::default();
let stream = scanner
.scan_series_partition(&ctx, &metrics, 0, &source)
.unwrap()
.expect("two-phase raw scan is supported");
assert_eq!(SeriesOrdering::KeyThenTime, stream.ordering());
let schema = Arc::clone(stream.schema());
let chunks = stream.try_collect::<Vec<_>>().await.unwrap();
// Two collection rounds really happened; the fixture never reaches the production threshold.
let rounds = crate::read::series_scan::candidate_assignment_rounds();
assert!(
rounds >= 2,
"the partition must consume more than one assignment round, got {rounds}"
);
assert!(
!chunks.is_empty(),
"partition 0 must own reader assignments"
);
// Partition 0's single stream carries every series in one run each, with keys in increasing
// order as declared by `KeyThenTime`; the assignment
// composition is: the first assignment holds the first 500 candidate series (which includes
// `keys[0]`) and the trailing assignment holds the last candidate series.
let mut runs = Vec::<Vec<u8>>::new();
let mut chunks_per_series = HashMap::<Vec<u8>, usize>::new();
for chunk in &chunks {
let key = chunk.primary_key.to_vec();
*chunks_per_series.entry(key.clone()).or_default() += 1;
if runs.last() != Some(&key) {
assert!(
!runs.contains(&key),
"a series must not resume after another series across a round boundary"
);
runs.push(key);
}
}
assert_eq!(keys.len(), runs.len(), "every series appears in one run");
assert!(
chunks_per_series.values().copied().max().unwrap() > 1,
"the fixture must emit multiple chunks for one series, got {chunks_per_series:?}"
);
// The round boundary: the first run belongs to the first assignment, the last run to the
// second assignment, and both are chunks of the same partition stream.
let (first_assignment, second_assignment) = runs.split_at(SERIES - 1);
assert!(
first_assignment.contains(&keys[0]),
"the first assignment must stream the first key"
);
assert!(
second_assignment.contains(&keys[SERIES - 1]),
"the second assignment must stream the last key"
);
let last_round_chunks = chunks
.iter()
.filter(|chunk| chunk.primary_key.as_slice() == keys[SERIES - 1].as_slice())
.count();
assert!(
last_round_chunks > 0,
"the series of the second assignment must be streamed"
);
let stream_rows = chunks.iter().map(|chunk| chunk.time.len()).sum::<usize>();
assert_eq!(
expected_times.values().map(Vec::len).sum::<usize>(),
stream_rows,
"the stream must carry every written row of both rounds"
);
for (key, times) in &expected_times {
let observed = chunks
.iter()
.filter(|chunk| chunk.primary_key.as_slice() == key.as_slice())
.flat_map(|chunk| chunk.time.as_buffer().iter().copied())
.collect::<Vec<_>>();
assert_eq!(times, &observed, "timestamps must increase per series");
assert!(
observed.windows(2).all(|window| window[0] < window[1]),
"timestamps must strictly increase within a key"
);
}
for (index, chunk) in chunks.iter().enumerate() {
let next_is_same_series = chunks
.get(index + 1)
.is_some_and(|next| next.primary_key.as_slice() == chunk.primary_key.as_slice());
assert_eq!(
!next_is_same_series, chunk.is_last,
"is_last must mark the final chunk of a series, including at the round boundary"
);
let times = chunk.time.as_buffer();
for (sample, time) in times.iter().enumerate() {
let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(sample) else {
panic!("raw fields are converted to float samples");
};
assert_eq!((*time + 1) as f64, value);
}
}
// Route the same partition stream through the frame codec so its `SequenceValidator` checks
// the chunks this reader produced, including the chunks the second assignment added.
let packed = pack_raw_series(Box::pin(ChainedRawSeriesStream::new(
Arc::clone(&schema),
source,
SeriesOrdering::KeyThenTime,
chunks.clone(),
)))
.unwrap();
let unpacked = unpack_raw_series(packed, Some(Arc::clone(&schema))).unwrap();
let validated = unpacked.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(
stream_rows,
validated
.iter()
.map(|chunk| chunk.time.len())
.sum::<usize>(),
"packing and unpacking must preserve the multi-round stream"
);
let mut schema_fields = schema
.fields
.iter()
.map(|field| field.name.as_ref())
.collect::<Vec<_>>();
schema_fields.dedup();
assert_eq!(vec!["field_0"], schema_fields);
}
/// Creates the sparse-encoded flat region shared by the two-phase raw scan tests.
///
/// Returns the region metadata and the row schema accepted by the sparse write path.
async fn create_two_phase_sparse_region(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
) -> (
Arc<store_api::metadata::RegionMetadata>,
Vec<api::v1::ColumnSchema>,
) {
let metadata = Arc::new(sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
));
let mut create = CreateRequestBuilder::new().build();
create.column_metadatas = metadata.column_metadatas.clone();
create.primary_key = metadata.primary_key.clone();
create
.options
.insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string());
create
.options
.insert("memtable.type".to_string(), "bulk".to_string());
create
.options
.insert("sst_format".to_string(), "flat".to_string());
let full_schema = test_util::rows_schema(&create);
let mut key_schema = full_schema[0].clone();
key_schema.column_name = PRIMARY_KEY_COLUMN_NAME.to_string();
key_schema.datatype = ColumnDataType::Binary.into();
key_schema.semantic_type = SemanticType::Tag.into();
let row_schema = vec![key_schema, full_schema[5].clone(), full_schema[4].clone()];
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
(metadata, row_schema)
}
/// Writes `(primary key, timestamp, field_0)` rows through the sparse write path.
async fn put_sparse_rows(
engine: &crate::engine::MitoEngine,
region_id: RegionId,
schema: &[api::v1::ColumnSchema],
rows: Vec<(Vec<u8>, i64, u64)>,
) {
let rows = rows
.into_iter()
.map(|(key, time, value)| {
row(vec![
ValueData::BinaryValue(key),
ValueData::TimestampMillisecondValue(time),
ValueData::U64Value(value),
])
})
.collect();
engine
.handle_request(
region_id,
RegionRequest::Put(RegionPutRequest {
rows: Rows {
schema: schema.to_vec(),
rows,
},
hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
}),
skip_wal: false,
partition_expr_version: None,
}),
)
.await
.unwrap();
}
/// Binds every non-internal tag column of `metadata` as the raw label source.
fn primary_key_label_source(
metadata: &store_api::metadata::RegionMetadataRef,
) -> store_api::region_engine::RawLabelSource {
use store_api::region_engine::{BoundTag, RawLabelSource};
RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: Arc::clone(metadata),
logical_tags: metadata
.column_metadatas
.iter()
.filter(|column| {
column.semantic_type == SemanticType::Tag
&& !store_api::storage::consts::is_internal_column(&column.column_schema.name)
&& !store_api::metric_engine_consts::is_metric_engine_internal_column(
&column.column_schema.name,
)
})
.map(|column| BoundTag {
column_id: column.column_id,
name: Arc::from(column.column_schema.name.as_str()),
})
.collect::<Vec<_>>()
.into(),
}
}
/// Concatenates the raw chunks of every reader assignment of one scan, in partition order.
struct ChainedRawSeriesStream {
schema: Arc<datatypes::series::samples::SeriesSchema>,
label_source: store_api::region_engine::RawLabelSource,
/// The description this stream declares, derived from `label_source` once, like a producer.
label_decode_spec: Option<datatypes::series::frame::LabelDecodeSpec>,
ordering: datatypes::series::SeriesOrdering,
chunks: std::vec::IntoIter<datatypes::series::raw::RawSeriesChunk>,
}
impl ChainedRawSeriesStream {
fn new(
schema: Arc<datatypes::series::samples::SeriesSchema>,
label_source: store_api::region_engine::RawLabelSource,
ordering: datatypes::series::SeriesOrdering,
chunks: Vec<datatypes::series::raw::RawSeriesChunk>,
) -> Self {
let label_decode_spec = common_query::series_frame::label_decode_spec(&label_source);
Self {
schema,
label_source,
label_decode_spec,
ordering,
chunks: chunks.into_iter(),
}
}
}
impl futures::Stream for ChainedRawSeriesStream {
type Item = Result<datatypes::series::raw::RawSeriesChunk, common_error::ext::BoxedError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::task::Poll::Ready(self.chunks.next().map(Ok))
}
}
impl store_api::region_engine::RawSeriesStream for ChainedRawSeriesStream {
fn schema(&self) -> &Arc<datatypes::series::samples::SeriesSchema> {
&self.schema
}
fn label_source(&self) -> &store_api::region_engine::RawLabelSource {
&self.label_source
}
fn label_decode_spec(&self) -> Option<&datatypes::series::frame::LabelDecodeSpec> {
self.label_decode_spec.as_ref()
}
fn ordering(&self) -> datatypes::series::SeriesOrdering {
self.ordering
}
}
/// Decodes each chunk's primary key through `description`, as a consumer holding only the stream
/// would, and asserts none of the chunks carries inline labels.
fn decode_declared_labels(
description: &datatypes::series::frame::LabelDecodeSpec,
chunks: &[datatypes::series::raw::RawSeriesChunk],
) -> Vec<datatypes::series::SeriesLabels> {
use mito_codec::labels::PrimaryKeyLabelDecoder;
let mut decoder = PrimaryKeyLabelDecoder::from_decode_spec(description).unwrap();
chunks
.iter()
.map(|chunk| {
assert!(
chunk.metric.is_none(),
"a key-encoded chunk leaves its labels undecoded"
);
decoder.decode(chunk.primary_key.as_slice()).unwrap()
})
.collect()
}
/// Every key-encoded raw series stream declares its own label decode description before the first
/// poll, and that declaration is the one derived from the binding the scan read under. Dense and
/// sparse producers are both covered, plus a stream that ends without producing a chunk, so the
/// producer and the consumer are exercised against the same declaration.
#[tokio::test]
async fn test_mito_raw_series_stream_declares_its_label_decode_description() {
use store_api::region_engine::QueryScanContext;
// Dense encoding: one flushed series under the default region layout.
let mut env = TestEnv::with_prefix("test_mito_raw_series_self_describing_dense").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: test_util::build_rows_for_key("host-a", 0, 2, 0),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let mut scanner = engine.handle_query(region_id, request).await.unwrap();
let source = primary_key_label_source(&scanner.metadata());
let expected = common_query::series_frame::label_decode_spec(&source)
.expect("a primary-key binding describes its key");
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let metrics = ExecutionPlanMetricsSet::default();
let mut chunks = Vec::new();
for partition in 0..ranges.len() {
let stream = scanner
.scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source)
.unwrap()
.expect("a dense PerSeries scan produces raw series");
// The producer states its layout up front, before anything is polled.
assert_eq!(
Some(&expected),
stream.label_decode_spec(),
"dense partition {partition} must declare its label decode description before polling"
);
chunks.extend(stream.try_collect::<Vec<_>>().await.unwrap());
}
assert_eq!(
2,
chunks.iter().map(|chunk| chunk.time.len()).sum::<usize>()
);
let dense_metrics = decode_declared_labels(&expected, &chunks);
assert_eq!(dense_metrics.len(), chunks.len());
for metric in &dense_metrics {
assert_eq!(metric.name(), Some("fixture_metric"));
assert_eq!(metric.get("tag_0"), Some("host-a"));
}
// A statically empty stream declares the same layout while producing no chunk at all.
let empty_request = ScanRequest {
filters: vec![col("field_0").gt(lit(1.0e9_f64))],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let mut empty_scanner = engine.handle_query(region_id, empty_request).await.unwrap();
let empty_source = primary_key_label_source(&empty_scanner.metadata());
let empty_expected = common_query::series_frame::label_decode_spec(&empty_source)
.expect("a primary-key binding describes its key");
let empty_ranges = empty_scanner.properties().partitions.clone();
assert!(
!empty_ranges.is_empty(),
"a filtered PerSeries scan still assigns its pinned input to a partition"
);
empty_scanner
.prepare(PrepareRequest {
ranges: Some(empty_ranges.clone()),
target_partitions: Some(empty_ranges.len()),
..Default::default()
})
.unwrap();
let mut empty_chunks = Vec::new();
for partition in 0..empty_ranges.len() {
let stream = empty_scanner
.scan_series_partition(
&QueryScanContext::default(),
&metrics,
partition,
&empty_source,
)
.unwrap()
.expect("a statically empty PerSeries scan still produces a raw series stream");
assert_eq!(
Some(&empty_expected),
stream.label_decode_spec(),
"an empty partition {partition} must still declare its layout before polling"
);
empty_chunks.extend(stream.try_collect::<Vec<_>>().await.unwrap());
}
assert!(
empty_chunks.is_empty(),
"the filtered-out stream produced no chunk"
);
// Sparse encoding: the two-phase producer encodes table id and TSID into the key too.
let mut env = TestEnv::with_prefix("test_mito_raw_series_self_describing_sparse").await;
let engine = env
.create_engine(MitoConfig {
experimental_series_scan_v2: true,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let (metadata, row_schema) = create_two_phase_sparse_region(&engine, region_id).await;
let key = new_sparse_primary_key(&["host-a", "zone-1"], &metadata, 10, 0);
put_sparse_rows(
&engine,
region_id,
&row_schema,
vec![(key.clone(), 10, 1), (key, 20, 2)],
)
.await;
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let mut scanner = engine.handle_query(region_id, request).await.unwrap();
let source = primary_key_label_source(&scanner.metadata());
let expected = common_query::series_frame::label_decode_spec(&source)
.expect("a primary-key binding describes its key");
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let mut chunks = Vec::new();
for partition in 0..ranges.len() {
let stream = scanner
.scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source)
.unwrap()
.expect("a sparse PerSeries scan produces raw series");
assert_eq!(
Some(&expected),
stream.label_decode_spec(),
"sparse partition {partition} must declare its label decode description before polling"
);
chunks.extend(stream.try_collect::<Vec<_>>().await.unwrap());
}
assert_eq!(
2,
chunks.iter().map(|chunk| chunk.time.len()).sum::<usize>()
);
let metrics_seen = decode_declared_labels(&expected, &chunks);
assert_eq!(metrics_seen.len(), chunks.len());
for metric in &metrics_seen {
assert_eq!(metric.name(), Some("fixture_metric"));
assert_eq!(metric.get("tag_0"), Some("host-a"));
assert_eq!(metric.get("tag_1"), Some("zone-1"));
}
}
#[tokio::test]
async fn test_mito_raw_series_int64_predicate_uses_original_precision() {
use datatypes::series::samples::SampleRef;
use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource};
let mut env =
TestEnv::with_prefix("test_mito_raw_series_int64_predicate_uses_original_precision").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.field_num(2)
.field_datatype(ConcreteDataType::int64_datatype())
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let boundary = 1_i64 << 53;
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: [boundary, boundary + 1]
.into_iter()
.enumerate()
.map(|(i, gate)| {
row(vec![
ValueData::StringValue("series".into()),
ValueData::I64Value(gate),
ValueData::I64Value((i as i64 + 1) * 10),
ValueData::TimestampMillisecondValue(i as i64 + 1),
])
})
.collect(),
},
)
.await;
let mut scanner = engine
.handle_query(
region_id,
ScanRequest {
projection: Some(vec![2, 3]),
filters: vec![
col("tag_0").eq(lit("series")),
col("field_0").gt(lit(boundary)),
],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
},
)
.await
.unwrap();
let metadata = scanner.metadata();
let tags = metadata
.column_metadatas
.iter()
.filter(|c| c.semantic_type == SemanticType::Tag)
.map(|c| BoundTag {
column_id: c.column_id,
name: Arc::from(c.column_schema.name.as_str()),
})
.collect::<Vec<_>>();
let source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata,
logical_tags: tags.into(),
};
let ranges = scanner.properties().partitions.clone();
scanner
.prepare(PrepareRequest {
ranges: Some(ranges.clone()),
target_partitions: Some(ranges.len()),
..Default::default()
})
.unwrap();
let metrics = ExecutionPlanMetricsSet::default();
let mut times = Vec::new();
let mut output_values = Vec::new();
for partition in 0..ranges.len() {
let stream = scanner
.scan_series_partition(&QueryScanContext::default(), &metrics, partition, &source)
.unwrap()
.expect("typed predicate is supported");
assert_eq!(
vec!["field_1"],
stream
.schema()
.fields
.iter()
.map(|f| f.name.as_ref())
.collect::<Vec<_>>()
);
let chunks = stream.try_collect::<Vec<_>>().await.unwrap();
for chunk in chunks {
let axis = chunk.time.as_buffer();
times.extend(axis.iter().copied());
for (index, &time) in axis.iter().enumerate() {
output_values.push((
time,
match chunk.fields.get(0).unwrap().sample(index) {
SampleRef::Float(value) => value,
_ => panic!("expected float sample"),
},
));
}
}
}
assert_eq!(vec![2], times);
assert_eq!(vec![(2, 20.0)], output_values);
// Validate the typed integer gate through RegionScanExec's actual physical consumer.
use common_query::series_frame::{series_frame_ordering, unpack_raw_series};
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use datatypes::series::SeriesOrdering;
use table::table::scan::RegionScanExec;
let native_request = ScanRequest {
projection: Some(vec![2, 3]),
filters: vec![
col("tag_0").eq(lit("series")),
col("field_0").gt(lit(boundary)),
],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let native_scanner = engine
.handle_query(region_id, native_request.clone())
.await
.unwrap();
let native_metadata = native_scanner.metadata();
let native_source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: native_metadata.clone(),
logical_tags: Arc::from([BoundTag {
column_id: native_metadata.primary_key[0],
name: Arc::from("tag_0"),
}]),
};
let native_plan = Arc::new(RegionScanExec::new(native_scanner, native_request, None).unwrap())
.try_to_series_scan(native_source)
.unwrap()
.expect("typed int64 gate is supported");
let native_schema = native_plan.series_schema().clone();
let frames = native_plan
.execute(0, Arc::new(TaskContext::default()))
.unwrap();
// Unpack under the frame's own declaration so the decoder checks the legacy key order.
let ordering = series_frame_ordering(frames.schema().as_ref()).unwrap();
assert_eq!(
SeriesOrdering::KeyThenTime,
ordering,
"the legacy producer must declare key-then-time frames"
);
let chunks = unpack_raw_series(frames, Some(native_schema))
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let native_rows = chunks
.iter()
.flat_map(|chunk| {
let times = chunk.time.as_buffer();
(0..times.len())
.map(|i| {
let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(i) else {
panic!("expected float output field")
};
(times[i], value)
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
assert_eq!(vec![(2, 20.0)], native_rows);
let empty_request = ScanRequest {
projection: Some(vec![2, 3]),
filters: vec![
col("tag_0").eq(lit("series")),
col("field_0").gt(lit(boundary + 1)),
],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let empty_scanner = engine
.handle_query(region_id, empty_request.clone())
.await
.unwrap();
let empty_metadata = empty_scanner.metadata();
let empty_source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: empty_metadata.clone(),
logical_tags: Arc::from([BoundTag {
column_id: empty_metadata.primary_key[0],
name: Arc::from("tag_0"),
}]),
};
let empty_plan = Arc::new(RegionScanExec::new(empty_scanner, empty_request, None).unwrap())
.try_to_series_scan(empty_source)
.unwrap()
.expect("statically empty scan still has native capability");
let empty_schema = empty_plan.series_schema().clone();
let empty_frames = empty_plan
.execute(0, Arc::new(TaskContext::default()))
.unwrap();
let empty_ordering = series_frame_ordering(empty_frames.schema().as_ref()).unwrap();
assert_eq!(
SeriesOrdering::KeyThenTime,
empty_ordering,
"a statically empty legacy scan still declares key-then-time frames"
);
let empty_chunks = unpack_raw_series(empty_frames, Some(empty_schema))
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert!(empty_chunks.is_empty());
}
/// Invalid predicate bindings decline before consumption; explicit labels decline and legacy still reads.
#[tokio::test]
async fn test_mito_raw_series_invalid_binding_before_legacy_read() {
use datatypes::series::samples::SampleRef;
use store_api::region_engine::{BoundTag, QueryScanContext, RawLabelSource};
let mut env =
TestEnv::with_prefix("test_mito_raw_series_invalid_binding_before_legacy_read").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: test_util::build_rows(0, 2),
},
)
.await;
use datafusion_expr::{ColumnarValue, Expr, Volatility, create_udf};
let udf = |name, volatility| {
create_udf(
name,
vec![],
DataType::Boolean,
volatility,
Arc::new(|_| Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))))),
)
.call(vec![])
};
let scalar_variable = Expr::ScalarVariable(
Arc::new(Field::new("@@version", DataType::Boolean, false)),
vec!["@@version".to_string()],
);
let cases = vec![
(
"missing column",
col("missing_column").gt(lit(1_i64)),
false,
),
(
"stable function",
udf("stable_guard", Volatility::Stable),
false,
),
(
"volatile function",
udf("volatile_guard", Volatility::Volatile),
false,
),
("scalar variable", scalar_variable, false),
("non-boolean predicate", col("field_0"), false),
(
"immutable function",
udf("immutable_guard", Volatility::Immutable),
true,
),
];
let metrics = ExecutionPlanMetricsSet::default();
let ctx = QueryScanContext::default();
for (name, filter, supported) in cases {
let scanner = engine
.handle_query(
region_id,
ScanRequest {
filters: vec![filter],
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: false,
..Default::default()
},
)
.await
.unwrap();
let metadata = scanner.metadata();
let valid_source = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata.clone(),
logical_tags: Arc::from([BoundTag {
column_id: metadata.primary_key[0],
name: Arc::from("tag_0"),
}]),
};
assert_eq!(
supported,
scanner.raw_series_schema(&valid_source).unwrap().is_some(),
"schema preflight case: {name}"
);
let raw = scanner
.scan_series_partition(&ctx, &metrics, 0, &valid_source)
.unwrap();
assert_eq!(supported, raw.is_some(), "case: {name}");
if let Some(raw) = raw {
let chunks = raw.try_collect::<Vec<_>>().await.unwrap();
let tuples = chunks
.iter()
.map(|chunk| {
let times = chunk.time.as_buffer();
let SampleRef::Float(value) = chunk.fields.get(0).unwrap().sample(0) else {
panic!("expected raw float sample");
};
(times[0], value)
})
.collect::<Vec<_>>();
assert_eq!(vec![(0, 0.0), (1000, 1.0)], tuples, "case: {name}");
} else {
let batches = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
let batches = RecordBatches::try_collect(batches).await.unwrap();
let rows = batches
.iter()
.flat_map(|batch| {
(0..batch.num_rows()).map(move |row| {
let tag = batch
.column_by_name("tag_0")
.unwrap()
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(row)
.to_string();
let field = batch
.column_by_name("field_0")
.unwrap()
.as_any()
.downcast_ref::<Float64Array>()
.unwrap()
.value(row);
let time = batch
.column_by_name("ts")
.unwrap()
.as_any()
.downcast_ref::<TimestampMillisecondArray>()
.unwrap()
.value(row);
(tag, field, time)
})
})
.collect::<Vec<_>>();
assert_eq!(
vec![("0".to_string(), 0.0, 0), ("1".to_string(), 1.0, 1000)],
rows,
"case: {name}"
);
}
}
let scanner = engine
.handle_query(
region_id,
ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: false,
..Default::default()
},
)
.await
.unwrap();
let metadata = scanner.metadata();
let valid_shape_bad_tag = RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata.clone(),
logical_tags: Arc::from([BoundTag {
column_id: metadata.primary_key[0],
name: Arc::from("wrong_name"),
}]),
};
assert!(
scanner
.scan_series_partition(&ctx, &metrics, 0, &RawLabelSource::Explicit)
.unwrap()
.is_none()
);
assert!(
scanner
.raw_series_schema(&RawLabelSource::Explicit)
.unwrap()
.is_none()
);
assert!(scanner.raw_series_schema(&valid_shape_bad_tag).is_err());
assert!(
scanner
.scan_series_partition(&ctx, &metrics, 0, &valid_shape_bad_tag)
.is_err()
);
let batches = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
let batches = RecordBatches::try_collect(batches).await.unwrap();
let rows = batches
.iter()
.flat_map(|batch| {
(0..batch.num_rows()).map(move |row| {
let tag = batch
.column_by_name("tag_0")
.unwrap()
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(row);
let field = batch
.column_by_name("field_0")
.unwrap()
.as_any()
.downcast_ref::<Float64Array>()
.unwrap()
.value(row);
let time = batch
.column_by_name("ts")
.unwrap()
.as_any()
.downcast_ref::<TimestampMillisecondArray>()
.unwrap()
.value(row);
(tag.to_string(), field, time)
})
})
.collect::<Vec<_>>();
assert_eq!(
vec![("0".to_string(), 0.0, 0), ("1".to_string(), 1.0, 1000)],
rows
);
// Runtime pruning wrappers are deliberately ineligible for native planning, and
// wrappers installed after planning must be caught at execute time.
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use table::table::scan::RegionScanExec;
let dynamic_request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
..Default::default()
};
let dynamic_source_for = |scanner: &dyn RegionScanner| {
let metadata = scanner.metadata();
RawLabelSource::PrimaryKey {
metric_name: Arc::from("fixture_metric"),
physical_metadata: metadata.clone(),
logical_tags: Arc::from([BoundTag {
column_id: metadata.primary_key[0],
name: Arc::from("tag_0"),
}]),
}
};
let make_dynamic = || {
Arc::new(DynamicFilterPhysicalExpr::new(
vec![Arc::new(Column::new("field_0", 1))],
physical_lit(true),
))
};
let before = engine
.handle_query(region_id, dynamic_request.clone())
.await
.unwrap();
let before_source = dynamic_source_for(before.as_ref());
let before_scan = Arc::new(RegionScanExec::new(before, dynamic_request.clone(), None).unwrap());
assert_eq!(
vec![true],
before_scan.add_dyn_filters_to_predicate(vec![make_dynamic()])
);
assert!(
before_scan
.clone()
.try_to_series_scan(before_source)
.unwrap()
.is_none()
);
let after = engine
.handle_query(region_id, dynamic_request.clone())
.await
.unwrap();
let after_source = dynamic_source_for(after.as_ref());
let after_scan = Arc::new(RegionScanExec::new(after, dynamic_request, None).unwrap());
let after_plan = after_scan
.clone()
.try_to_series_scan(after_source)
.unwrap()
.expect("native plan before dynamic wrapper installation");
assert_eq!(
vec![true],
after_scan.add_dyn_filters_to_predicate(vec![make_dynamic()])
);
assert!(
after_plan
.execute(0, Arc::new(TaskContext::default()))
.is_err()
);
}
#[tokio::test]
async fn test_seq_scan_reads_files_with_disjoint_keys_in_parallel() {
let mut env = TestEnv::with_prefix("test_seq_scan_disjoint_keys").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let put_flush = async |key: &str, start, end, value_start| {
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows_for_key(key, start, end, value_start),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
};
// Three files over the same time range. The last one overwrites a row of the first.
put_flush("a", 0, 3, 0).await;
put_flush("b", 0, 3, 10).await;
put_flush("a", 1, 2, 100).await;
// A memtable outside the files' time range gets its own range.
let rows = Rows {
schema: column_schemas.clone(),
rows: test_util::build_rows_for_key("c", 10, 11, 20),
};
test_util::put_rows(&engine, region_id, rows).await;
let scanner = engine
.scanner(region_id, ScanRequest::default())
.await
.unwrap();
let Scanner::Seq(scanner) = scanner else {
panic!("Scanner should be seq scan");
};
// Files of key "a" share a range; the file of key "b" gets its own.
assert_eq!(
3,
scanner.properties().partitions[0].len(),
"unexpected ranges: {:?}",
scanner.properties().partitions
);
let batches = RecordBatches::try_collect(scanner.build_stream().unwrap())
.await
.unwrap();
let expected = "\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| a | 0.0 | 1970-01-01T00:00:00 |
| a | 100.0 | 1970-01-01T00:00:01 |
| a | 2.0 | 1970-01-01T00:00:02 |
| b | 10.0 | 1970-01-01T00:00:00 |
| b | 11.0 | 1970-01-01T00:00:01 |
| b | 12.0 | 1970-01-01T00:00:02 |
| c | 20.0 | 1970-01-01T00:00:10 |
+-------+---------+---------------------+";
assert_eq!(expected, sort_batches_and_print(&batches, &["tag_0", "ts"]));
// Per-series scans still group the files by time only.
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
};
let scanner = engine.scanner(region_id, request).await.unwrap();
let Scanner::Series(scanner) = scanner else {
panic!("Scanner should be series scan");
};
let ranges: Vec<_> = scanner.properties().partitions.iter().flatten().collect();
assert_eq!(2, ranges.len(), "unexpected ranges: {ranges:?}");
}
#[tokio::test]
async fn test_time_windowed_seq_scan_keeps_files_with_disjoint_keys_together() {
let mut env = TestEnv::with_prefix("test_time_windowed_disjoint_keys").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let column_schemas = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// All rows share one timestamp. The second file holds more rows than the first.
for keys in [&["a"][..], &["b", "c"][..]] {
let rows = Rows {
schema: column_schemas.clone(),
rows: keys
.iter()
.flat_map(|key| test_util::build_rows_for_key(key, 0, 1, 0))
.collect(),
};
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
}
let request = ScanRequest {
distribution: Some(TimeSeriesDistribution::TimeWindowed),
..Default::default()
};
let Scanner::Seq(mut scanner) = engine.scanner(region_id, request).await.unwrap() else {
panic!("Scanner should be seq scan");
};
// Assign the ranges to one partition with the largest first, as partition assignment
// orders them by rows.
let mut ranges: Vec<_> = scanner
.properties()
.partitions
.iter()
.flatten()
.copied()
.collect();
ranges.sort_by_key(|range| std::cmp::Reverse(range.num_rows));
scanner
.prepare(
PrepareRequest::default()
.with_ranges(vec![ranges])
.with_target_partitions(1),
)
.unwrap();
let batches = scanner
.scan_partition(
&store_api::region_engine::QueryScanContext::default(),
&ExecutionPlanMetricsSet::default(),
0,
)
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let mut keys = Vec::new();
for batch in batches {
let tags = batch.column_by_name("tag_0").unwrap();
for row in 0..batch.num_rows() {
keys.push(
datatypes::arrow_array::string_array_value_at_index(tags, row)
.unwrap()
.to_string(),
);
}
}
// Rows come out in `(ts, primary key)` order without sorting them.
assert_eq!(vec!["a", "b", "c"], keys);
}