use super::*;
use crate::substrait::schema::to_substrait_named_struct;
fn contract_plan(
template: &Plan,
payload: payload::MatchRecognizeRel,
input_schema: NamedStruct,
) -> Plan {
let mut plan = template.clone();
plan.relations = plan_for_payload(payload).relations;
let Some(plan_rel::RelType::Rel(root)) = &mut plan.relations[0].rel_type else {
panic!("test_case root relation");
};
let Some(RelType::ExtensionSingle(extension)) = &mut root.rel_type else {
panic!("test_case extension relation");
};
let Some(RelType::Read(read)) = &mut extension.input.as_mut().unwrap().rel_type
else {
panic!("test_case input relation");
};
read.base_schema = Some(input_schema);
plan
}
#[tokio::test]
async fn prepared_window_output_uses_declared_ordinals() -> Result<()> {
let ctx = context_with_input().await?;
let direct = sql_plan(
&ctx,
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(ts) < ts AND PREV(price) < price)",
)
.await?;
let state = ctx.state();
let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
let mut semantic = root_payload(&exported)?;
let [first, second] = semantic.prepared_output_fields.as_slice() else {
panic!("expected two prepared window outputs");
};
assert_ne!(first.output_field, second.output_field);
assert_ne!(first.expression, second.expression);
let input_schema = named_struct(vec![
("company", string_type()),
("ts", i64_type()),
("price", i64_type()),
]);
semantic.prepared_output_fields.reverse();
let reordered = contract_plan(&exported, semantic.clone(), input_schema.clone());
from_substrait_plan_with_match_recognize(&state, &reordered).await?;
semantic.prepared_output_fields[1].expression =
semantic.prepared_output_fields[0].expression.clone();
let reused = contract_plan(&exported, semantic, input_schema);
let error = from_substrait_plan_with_match_recognize(&state, &reused)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("does not identify one unambiguous retained field"),
"{error}"
);
Ok(())
}
#[tokio::test]
async fn equal_volatile_prepared_windows_roundtrip_as_distinct_fields() -> Result<()> {
let ctx = context_with_input().await?;
let direct = sql_plan(
&ctx,
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(RANDOM() + price) <> PREV(RANDOM() + price))",
)
.await?;
let state = ctx.state();
let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
let semantic = root_payload(&exported)?;
let [first, second] = semantic.prepared_output_fields.as_slice() else {
panic!("expected separate prepared outputs for both volatile windows");
};
assert_ne!(first.output_field, second.output_field);
assert_eq!(first.expression, second.expression);
let input_schema = named_struct(vec![
("company", string_type()),
("ts", i64_type()),
("price", i64_type()),
]);
let retained = contract_plan(&exported, semantic, input_schema);
from_substrait_plan_with_match_recognize(&state, &retained).await?;
from_substrait_plan_with_match_recognize(&state, &exported).await?;
Ok(())
}
#[tokio::test]
async fn summary_output_fields_reject_omission_and_duplicate_identity() -> Result<()> {
let ctx = context_with_input().await?;
let direct = sql_plan(
&ctx,
"SELECT c1, c2 FROM t MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(A.*) AS c1, COUNT(B.*) AS c2
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS price < 14, B AS price >= 14)",
)
.await?;
let state = ctx.state();
let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
let mut semantic = root_payload(&exported)?;
let [first, second] = semantic.summary_output_fields.as_slice() else {
panic!("expected two summary output identities");
};
assert_ne!(first.output_field, second.output_field);
assert_ne!(first.filter, second.filter);
let input_schema = named_struct(vec![
("company", string_type()),
("ts", i64_type()),
("price", i64_type()),
]);
semantic.summary_output_fields.reverse();
let reordered = contract_plan(&exported, semantic.clone(), input_schema.clone());
from_substrait_plan_with_match_recognize(&state, &reordered).await?;
let mut duplicated = semantic.clone();
let first_summary = duplicated.summary_output_fields[0].clone();
let second_output_field = duplicated.summary_output_fields[1].output_field;
duplicated.summary_output_fields[1] = payload::SummaryOutputField {
output_field: second_output_field,
..first_summary
};
let duplicated = contract_plan(&exported, duplicated, input_schema.clone());
let error = from_substrait_plan_with_match_recognize(&state, &duplicated)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("does not identify one unambiguous retained field"),
"{error}"
);
semantic.summary_output_fields.clear();
let omitted = contract_plan(&exported, semantic, input_schema);
let error = from_substrait_plan_with_match_recognize(&state, &omitted)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("does not identify one unambiguous retained field"),
"{error}"
);
Ok(())
}
#[tokio::test]
async fn dictionary_struct_names_roundtrip_matcher_passthrough() -> Result<()> {
let ctx = context_with_input().await?;
let plan = sql_plan(
&ctx,
r#"WITH dictionary_input AS (
SELECT 1 AS id,
arrow_cast(named_struct('label', CAST(2 AS BIGINT)),
'Dictionary(Int8, Struct("label": non-null Int64))') AS payload
)
SELECT COUNT(*) AS n
FROM dictionary_input MATCH_RECOGNIZE (
ORDER BY id ALL ROWS PER MATCH PATTERN (A) DEFINE A AS TRUE
)
WHERE payload IS NOT NULL"#,
)
.await?;
assert_roundtrip_output(
&ctx,
plan,
&[("n", DataType::Int64, false)],
&[vec![1_i64.into()]],
)
.await
}
#[test]
fn dictionary_output_validates_both_child_nullabilities() -> Result<()> {
use crate::substrait::schema::output_type_matches;
use r#type::Nullability::{Nullable, Required, Unspecified};
let dictionary =
DataType::Dictionary(Box::new(DataType::Int64), Box::new(DataType::Int64));
let child = |nullability| {
Box::new(Type {
kind: Some(r#type::Kind::I64(r#type::I64 {
nullability,
..Default::default()
})),
})
};
let matches = |key, value| {
let wire = Type {
kind: Some(r#type::Kind::Map(Box::new(r#type::Map {
key: Some(child(key)),
value: Some(child(value)),
nullability: Nullable as i32,
type_variation_reference: DICTIONARY_MAP_TYPE_VARIATION_REF,
}))),
};
output_type_matches(&dictionary, &dictionary, &wire)
};
for valid in [Nullable as i32, Required as i32] {
assert!(matches(valid, valid)?);
for invalid in [999, Unspecified as i32] {
assert!(matches(invalid, valid).is_err());
assert!(matches(valid, invalid).is_err());
}
}
Ok(())
}
#[tokio::test]
async fn output_contract_checks_recursive_wire_properties() -> Result<()> {
let structure = |name, nullable| {
DataType::Struct(vec![Field::new(name, DataType::Int64, nullable)].into())
};
let list = |nullable| {
DataType::List(Arc::new(Field::new(
"custom_item",
structure("leaf", true),
nullable,
)))
};
let map = |nullable| {
DataType::Map(
Arc::new(Field::new(
"custom_entries",
DataType::Struct(
vec![
Field::new("custom_key", DataType::Int64, false),
Field::new("custom_value", structure("leaf", false), nullable),
]
.into(),
),
false,
)),
true,
)
};
for (case, actual_type, declared_type, admitted) in [
(
"struct nullability",
structure("leaf", true),
structure("leaf", false),
false,
),
(
"struct name",
structure("leaf", true),
structure("other", true),
false,
),
("list element nullability", list(false), list(true), false),
("map value nullability", map(false), map(true), false),
(
"decimal precision",
DataType::Decimal128(12, 2),
DataType::Decimal128(13, 2),
false,
),
(
"decimal scale",
DataType::Decimal128(12, 2),
DataType::Decimal128(12, 3),
false,
),
(
"timestamp precision",
DataType::Timestamp(TimeUnit::Microsecond, None),
DataType::Timestamp(TimeUnit::Nanosecond, None),
false,
),
(
"timestamp timezone",
DataType::Timestamp(TimeUnit::Nanosecond, Some("Europe/Paris".into())),
DataType::Timestamp(TimeUnit::Nanosecond, None),
false,
),
("string view", DataType::Utf8, DataType::Utf8View, true),
] {
let builder =
datafusion::execution::SessionStateBuilder::new().with_default_features();
let ctx = new_match_recognize_context(builder)?;
let input = Arc::new(Schema::new(vec![
Field::new("ts", DataType::Int64, false),
Field::new("value", actual_type.clone(), true),
]));
ctx.register_batch("t", RecordBatch::new_empty(Arc::clone(&input)))?;
for rows in ["ONE ROW PER MATCH", "ALL ROWS PER MATCH"] {
let direct = sql_plan(
&ctx,
&format!(
"SELECT * FROM t MATCH_RECOGNIZE (
ORDER BY ts MEASURES LAST(A.value) AS observed {rows}
PATTERN (A+) DEFINE A AS true)"
),
)
.await?;
let node = match_recognize_node(&direct).expect("test_case matcher");
let state = ctx.state();
let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
let semantic = root_payload(&exported)?;
for complete in [false, true] {
let mut payload = semantic.clone();
let actual_schema = if complete {
payload.semantic_node = false;
payload.semantic_node_finalizes_one_row = false;
payload.retained_passthrough_input_fields.clear();
payload.prepared_output_fields.clear();
payload.summary_output_fields.clear();
payload
.required_features
.retain(|feature| feature != DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
direct.schema()
} else {
node.schema()
};
let mut producer = MatchRecognizeSubstraitProducer::new(&state);
let input_schema = to_substrait_named_struct(
&mut producer,
&Arc::new(DFSchema::try_from(input.as_ref().clone())?),
)?;
payload.output_schema =
Some(to_substrait_named_struct(&mut producer, actual_schema)?);
let valid =
contract_plan(&exported, payload.clone(), input_schema.clone());
let imported =
from_substrait_plan_with_match_recognize(&state, &valid).await?;
let batches = ctx.execute_logical_plan(imported).await?.collect().await?;
assert!(batches.iter().all(|batch| batch.num_rows() == 0));
let mut fields = actual_schema.fields().to_vec();
let index = fields
.iter()
.position(|field| field.data_type() == &actual_type)
.expect("test_case value output");
fields[index] = Arc::new(
fields[index]
.as_ref()
.clone()
.with_data_type(declared_type.clone()),
);
let declared = Arc::new(DFSchema::try_from(Schema::new(fields))?);
payload.output_schema =
Some(to_substrait_named_struct(&mut producer, &declared)?);
let changed = contract_plan(&exported, payload, input_schema);
let result =
from_substrait_plan_with_match_recognize(&state, &changed).await;
if admitted {
result?;
} else {
let error = result.expect_err(case);
let diagnostic = error.to_string();
assert!(
diagnostic.contains("output schema mismatch")
|| diagnostic.contains(
"does not identify one unambiguous retained field"
),
"{case}, {rows}, complete={complete}: {error}"
);
}
}
}
}
Ok(())
}