use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion::common::{Column, DFSchema, ExprSchema, Result, ScalarValue};
use datafusion::logical_expr::expr::{
Case, WindowFunction, WindowFunctionDefinition, WindowFunctionParams,
};
use datafusion::logical_expr::utils::{find_aggregate_exprs, find_window_exprs};
use datafusion::logical_expr::{
Expr, ExprSchemable, LogicalPlan, SortExpr, WindowFrame, WindowFrameBound,
WindowFrameUnits, lit,
};
use datafusion::optimizer::analyzer::type_coercion::TypeCoercionRewriter;
use datafusion_hash_grouped_order::gather::contains_dictionary;
use crate::planning::NamedExpr;
use crate::planning::define::StaticAnalysis;
use crate::planning::expr_safety::scalar_value_type_is_safe;
use crate::planning::logical::utils::causal_window_frame;
use crate::planning::logical::utils::materialize_windows;
#[derive(Debug)]
struct CrossSymbolNavigationRewrite {
source: Expr,
value: NavigationValue,
value_type: DataType,
default: ScalarValue,
is_matched: Expr,
classifier_mask: Expr,
compound_anchor: Option<(Expr, Expr)>,
}
#[derive(Debug)]
enum NavigationValue {
Prepared(Expr),
Candidate {
expr: Expr,
inputs: Vec<(Column, Expr)>,
presence: Expr,
},
}
impl NavigationValue {
fn windows(&self) -> impl Iterator<Item = &Expr> {
let (inputs, last) = match self {
Self::Prepared(window) => ([].as_slice(), window),
Self::Candidate {
inputs, presence, ..
} => (inputs.as_slice(), presence),
};
inputs
.iter()
.map(|(_, window)| window)
.chain(std::iter::once(last))
}
}
fn eligible_cross_symbol_navigation(
expr: &Expr,
table_schema: &Arc<DFSchema>,
partition_by: &[Expr],
order_by: &[SortExpr],
static_analysis: StaticAnalysis<'_>,
rewrite_next: bool,
options: &ConfigOptions,
) -> Option<CrossSymbolNavigationRewrite> {
let Expr::WindowFunction(window) = expr else {
return None;
};
let WindowFunctionDefinition::AggregateUDF(function) = &window.fun else {
return None;
};
let prev = function.as_ref() == crate::functions::udaf::mr_prev_udaf().as_ref();
let next = rewrite_next
&& function.as_ref() == crate::functions::udaf::mr_next_udaf().as_ref();
let is_compound = window.params.args.len() == 7;
if (!prev && !next)
|| (!is_compound && window.params.args.len() != 5)
|| window.params.filter.is_some()
|| window.params.distinct
|| window.params.null_treatment.is_some()
{
return None;
}
if is_compound {
let (
Expr::Literal(ScalarValue::Boolean(Some(_)), _),
Expr::Literal(logical_offset, _),
) = (&window.params.args[5], &window.params.args[6])
else {
return None;
};
crate::planning::bound_expr_lowering::literal_nonnegative_u64(logical_offset)?;
}
let value = &window.params.args[0];
if value.is_volatile()
|| !crate::planning::define::is_static(value, static_analysis)
|| !value
.column_refs()
.into_iter()
.all(|column| table_schema.is_column_from_schema(column))
|| !find_aggregate_exprs(std::iter::once(value)).is_empty()
|| !find_window_exprs(std::iter::once(value)).is_empty()
{
return None;
}
let (_, value_field) = value
.clone()
.rewrite(&mut TypeCoercionRewriter::new(table_schema.as_ref()))
.ok()?
.data
.to_field(table_schema.as_ref())
.ok()?;
let value_type = value_field.data_type().clone();
if !scalar_value_type_is_safe(&value_type) || contains_dictionary(&value_type) {
return None;
}
let Expr::Literal(offset_value, _) = &window.params.args[1] else {
return None;
};
let offset =
crate::planning::bound_expr_lowering::literal_nonnegative_u64(offset_value)?;
if (prev || is_compound) && offset == 0 {
return None;
}
let mask_valid = match &window.params.args[4] {
Expr::Column(mask) => {
mask.relation.is_none()
&& mask.name.starts_with("__mr_classifier_")
&& !crate::planning::define::is_static(
&window.params.args[4],
static_analysis,
)
}
other if is_compound => {
other == &crate::planning::logical::valid_match_row_expr()
}
_ => false,
};
if !mask_valid {
return None;
}
let Expr::Literal(default, _) =
crate::planning::bound_expr_lowering::simplified_literal(
&window.params.args[2],
options,
)?
else {
return None;
};
if !scalar_value_type_is_safe(&default.data_type())
|| contains_dictionary(&default.data_type())
{
return None;
}
let window_default = if value_type.is_null() {
default
} else if default.is_null() {
ScalarValue::Null
} else {
default.cast_to(&value_type).ok()?
};
let (function, frame) = if prev {
(
datafusion::functions_window::lead_lag::lag_udwf(),
causal_window_frame(),
)
} else {
(
datafusion::functions_window::lead_lag::lead_udwf(),
WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
if offset == 0 {
WindowFrameBound::CurrentRow
} else {
WindowFrameBound::Following(ScalarValue::UInt64(Some(offset)))
},
),
)
};
let shift = |value, default| {
Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::WindowUDF(Arc::clone(&function)),
params: WindowFunctionParams {
args: vec![value, window.params.args[1].clone(), default],
partition_by: partition_by.to_vec(),
order_by: order_by.to_vec(),
window_frame: frame.clone(),
filter: None,
distinct: false,
null_treatment: None,
},
}))
};
let prepare_value = crate::planning::expr_safety::can_precompute(value, table_schema);
let value = if prepare_value {
NavigationValue::Prepared(shift(value.clone(), lit(window_default.clone())))
} else {
if !value_field.metadata().is_empty() {
return None;
}
if !value.column_refs().into_iter().all(|column| {
table_schema.data_type(column).is_ok_and(|data_type| {
scalar_value_type_is_safe(data_type) && !contains_dictionary(data_type)
})
}) {
return None;
}
NavigationValue::Candidate {
expr: value.clone(),
inputs: value
.column_refs()
.into_iter()
.cloned()
.collect::<BTreeSet<_>>()
.into_iter()
.map(|column| {
let shifted =
shift(Expr::Column(column.clone()), lit(ScalarValue::Null));
(column, shifted)
})
.collect(),
presence: shift(lit(1_i64), lit(ScalarValue::Null)),
}
};
Some(CrossSymbolNavigationRewrite {
source: expr.clone(),
value,
value_type,
default: window_default,
is_matched: window.params.args[3].clone(),
classifier_mask: window.params.args[4].clone(),
compound_anchor: is_compound
.then(|| (window.params.args[5].clone(), window.params.args[6].clone())),
})
}
#[expect(
clippy::too_many_arguments,
reason = "navigation preparation keeps source bindings and rewrite policy explicit"
)]
pub(super) fn materialize_cross_symbol_navigation(
input: LogicalPlan,
definitions: &mut [NamedExpr],
table_schema: &Arc<DFSchema>,
partition_by: &[Expr],
order_by: &[SortExpr],
static_analysis: StaticAnalysis<'_>,
rewrite_next: bool,
options: &ConfigOptions,
) -> Result<(LogicalPlan, Vec<NamedExpr>)> {
if partition_by.iter().any(Expr::is_volatile)
|| order_by.iter().any(|sort| sort.expr.is_volatile())
{
return Ok((input, Vec::new()));
}
let mut rewrites = Vec::new();
for definition in definitions.iter() {
definition.expr.apply(|node| {
if let Some(rewrite) = eligible_cross_symbol_navigation(
node,
table_schema,
partition_by,
order_by,
static_analysis,
rewrite_next,
options,
) && !rewrites.iter().any(|known: &CrossSymbolNavigationRewrite| {
known.source == rewrite.source
}) {
rewrites.push(rewrite);
}
Ok(TreeNodeRecursion::Continue)
})?;
}
if rewrites.is_empty() {
return Ok((input, Vec::new()));
}
let static_windows =
find_window_exprs(definitions.iter().map(|definition| &definition.expr));
let window_exprs = rewrites
.iter()
.flat_map(|rewrite| rewrite.value.windows().cloned())
.chain(
static_windows
.into_iter()
.filter(|expr| crate::planning::define::is_static(expr, static_analysis)),
)
.collect::<Vec<_>>();
let (input, bindings) = materialize_windows(input, &window_exprs, [])?;
let mut replacements = Vec::with_capacity(rewrites.len());
for rewrite in &rewrites {
let select = |window: &Expr, default: Expr| -> Result<Expr> {
let mut args = vec![
Expr::Column(bindings.column(window)?),
lit(0_u64),
default,
rewrite.is_matched.clone(),
rewrite.classifier_mask.clone(),
];
if let Some((is_first, lo)) = &rewrite.compound_anchor {
args.push(is_first.clone());
args.push(lo.clone());
}
Ok(Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(
crate::functions::udaf::mr_prev_udaf(),
),
params:
crate::planning::bound_expr_lowering::canonical_define_navigation_window_params(
partition_by,
args,
),
})))
};
let replacement = match &rewrite.value {
NavigationValue::Prepared(window) => {
select(window, lit(rewrite.default.clone()))?
}
NavigationValue::Candidate {
expr,
inputs,
presence,
} => {
let selected = inputs
.iter()
.map(|(column, window)| {
Ok((column.clone(), select(window, lit(ScalarValue::Null))?))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let value = expr
.clone()
.transform_up(|node| {
if let Expr::Column(column) = &node
&& let Some(selected) = selected.get(column)
{
return Ok(Transformed::yes(selected.clone()));
}
Ok(Transformed::no(node))
})?
.data;
let default = if rewrite.default.data_type().is_null() {
ScalarValue::try_from(&rewrite.value_type)?
} else {
rewrite.default.clone()
};
Expr::Case(Case::new(
None,
vec![(
Box::new(select(presence, lit(ScalarValue::Null))?.is_not_null()),
Box::new(value),
)],
Some(Box::new(lit(default))),
))
}
};
replacements.push((rewrite.source.clone(), replacement));
}
for definition in definitions {
let rewritten = definition
.expr
.clone()
.transform_up(|node| {
if let Some((_, replacement)) =
replacements.iter().find(|(source, _)| source == &node)
{
Ok(Transformed::yes(replacement.clone()))
} else {
Ok(Transformed::no(node))
}
})?
.data;
definition.expr = bindings.rebase(&rewritten)?;
}
Ok((input, bindings.into_named_exprs()))
}
#[cfg(test)]
mod tests {
use super::super::preparation::{
CandidatePredicate, prepare_input_from_planned_symbols,
};
use super::*;
use crate::core::{
EmptyMatchesMode, MatchMetadataColumn, RowsPerMatch, classifier_bits_col_name,
};
use crate::planning::MatchRecognizePlanningContext;
use crate::planning::bound_expr_lowering::canonical_define_navigation_window_params;
use crate::planning::logical::valid_match_row_expr;
use crate::planning::phases::PreparedInput;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::logical_expr::{EmptyRelation, col};
struct NavigationContext {
options: ConfigOptions,
disable_managed: bool,
}
impl MatchRecognizePlanningContext for NavigationContext {
fn options(&self) -> &ConfigOptions {
&self.options
}
fn match_recognize_options(
&self,
) -> crate::planning::MatchRecognizePlanningOptions {
crate::planning::MatchRecognizePlanningOptions {
disable_managed_aggregates: self.disable_managed,
..Default::default()
}
}
}
struct NavFixture {
schema: Arc<DFSchema>,
symbols: BTreeSet<String>,
classifiers: BTreeSet<String>,
options: ConfigOptions,
}
impl NavFixture {
fn new(fields: Vec<Field>) -> Result<Self> {
Ok(Self {
schema: Arc::new(DFSchema::try_from(Schema::new(fields))?),
symbols: BTreeSet::from(["A".into(), "B".into()]),
classifiers: BTreeSet::from([classifier_bits_col_name("A")]),
options: ConfigOptions::default(),
})
}
fn analysis(&self) -> StaticAnalysis<'_> {
StaticAnalysis::new(&self.classifiers)
}
fn empty_plan(&self) -> LogicalPlan {
LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::clone(&self.schema),
})
}
fn eligible(
&self,
expr: &Expr,
managed_enabled: bool,
) -> Option<CrossSymbolNavigationRewrite> {
eligible_cross_symbol_navigation(
expr,
&self.schema,
&[],
&[],
self.analysis(),
managed_enabled,
&self.options,
)
}
fn materialize(
&self,
expr: Expr,
managed_enabled: bool,
) -> Result<(LogicalPlan, Vec<NamedExpr>, Expr)> {
let mut definitions = vec![NamedExpr {
name: "B".into(),
expr,
}];
let (input, bindings) = materialize_cross_symbol_navigation(
self.empty_plan(),
&mut definitions,
&self.schema,
&[],
&[],
self.analysis(),
managed_enabled,
&self.options,
)?;
Ok((input, bindings, definitions.pop().unwrap().expr))
}
fn prepare(
&self,
predicate: Expr,
partition_by: &[Expr],
order_by: &[SortExpr],
disable_managed: bool,
) -> Result<PreparedInput> {
let mut context = NavigationContext {
options: self.options.clone(),
disable_managed,
};
prepare_input_from_planned_symbols(
&mut context,
self.empty_plan(),
self.symbols.clone(),
vec![
NamedExpr {
name: "A".into(),
expr: lit(true),
},
NamedExpr {
name: "B".into(),
expr: predicate,
},
],
partition_by,
order_by,
&RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
true,
false,
)
}
}
fn nav_window(
is_next: bool,
value: Expr,
offset: u64,
default: Expr,
mask: Expr,
anchor: Option<(Expr, Expr)>,
) -> WindowFunction {
let mut args = vec![value, lit(offset), default, valid_match_row_expr(), mask];
if let Some((is_first, logical_offset)) = anchor {
args.extend([is_first, logical_offset]);
}
let mut params = canonical_define_navigation_window_params(&[], args);
let udaf = if is_next {
params.window_frame = WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
WindowFrameBound::Following(ScalarValue::UInt64(Some(offset))),
);
crate::functions::udaf::mr_next_udaf()
} else {
crate::functions::udaf::mr_prev_udaf()
};
WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(udaf),
params,
}
}
fn nav_expr(
is_next: bool,
value: Expr,
offset: u64,
default: Expr,
mask: Expr,
anchor: Option<(Expr, Expr)>,
) -> Expr {
Expr::WindowFunction(Box::new(nav_window(
is_next, value, offset, default, mask, anchor,
)))
}
fn mask_a() -> Expr {
col(classifier_bits_col_name("A"))
}
fn cast_expr(expr: Expr, data_type: DataType) -> Expr {
Expr::Cast(datafusion::logical_expr::expr::Cast::new(
Box::new(expr),
data_type,
))
}
fn fallible_case(divisor: &str, then_expr: Expr, else_expr: Option<Expr>) -> Expr {
Expr::Case(Case::new(
None,
vec![(
Box::new((lit(1_i64) / col(divisor)).gt(lit(0_i64))),
Box::new(then_expr),
)],
else_expr.map(Box::new),
))
}
fn prepare_scoped_prev(
depth: u64,
value: Expr,
partition_by: &[Expr],
order_by: &[SortExpr],
disable_managed: bool,
) -> PreparedInput {
let fixture = NavFixture::new(vec![
Field::new("v", DataType::Int64, true),
Field::new("d", DataType::Decimal128(37, 0), true),
Field::new("e", DataType::Decimal128(37, 0), true),
])
.expect("schema");
let prev = Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(
crate::functions::udaf::mr_prev_udaf(),
),
params: canonical_define_navigation_window_params(
partition_by,
vec![
value,
lit(depth),
lit(-1_i64),
valid_match_row_expr(),
mask_a(),
],
),
}))
.gt(lit(0_i64));
fixture
.prepare(prev, partition_by, order_by, disable_managed)
.expect("navigation preparation")
}
#[test]
fn unsafe_types_and_decorated_navigation_stay_deferred() -> Result<()> {
use datafusion::logical_expr::expr::NullTreatment;
let ree = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int16, false)),
Arc::new(Field::new("values", DataType::Int64, true)),
);
let fixture = NavFixture::new(vec![
Field::new("r", ree.clone(), true),
Field::new("v", DataType::Int64, true),
])?;
for is_next in [false, true] {
let plain =
nav_window(is_next, col("v"), 1, lit(ScalarValue::Null), mask_a(), None);
assert!(
fixture
.eligible(&Expr::WindowFunction(Box::new(plain.clone())), true)
.is_some()
);
let mut filtered = plain.clone();
filtered.params.filter = Some(Box::new(lit(false)));
let mut distinct = plain.clone();
distinct.params.distinct = true;
let mut ignore_nulls = plain.clone();
ignore_nulls.params.null_treatment = Some(NullTreatment::IgnoreNulls);
let mut respect_nulls = plain;
respect_nulls.params.null_treatment = Some(NullTreatment::RespectNulls);
assert!(
fixture
.eligible(
&nav_expr(
is_next,
col("r").is_null(),
1,
lit(false),
mask_a(),
None
),
true,
)
.is_some()
);
for window in [
nav_window(is_next, col("r"), 1, lit(ScalarValue::Null), mask_a(), None),
nav_window(
is_next,
fallible_case("v", col("r"), Some(col("r"))),
1,
lit(ScalarValue::Null),
mask_a(),
None,
),
nav_window(
is_next,
fallible_case("v", col("r").is_null(), Some(col("r").is_null())),
1,
lit(false),
mask_a(),
None,
),
nav_window(
is_next,
lit(ScalarValue::Null),
1,
lit(ScalarValue::try_from(&ree)?),
mask_a(),
None,
),
filtered,
distinct,
ignore_nulls,
respect_nulls,
] {
let expr = Expr::WindowFunction(Box::new(window));
assert!(fixture.eligible(&expr, true).is_none(), "{expr}");
let prepared = fixture.prepare(expr.is_not_null(), &[], &[], false)?;
assert!(prepared.prepared_exprs.is_empty());
assert!(prepared.managed_aggregates.is_empty());
assert!(matches!(
prepared.symbol_plans[1].predicate.match_aware(),
Some(CandidatePredicate::History { local: None, .. })
));
}
for (first, offset) in [
(lit(ScalarValue::Boolean(None)), lit(1_u64)),
(col("v").is_null(), lit(1_u64)),
(lit(true), col("v")),
(lit(false), lit(-1_i64)),
] {
let expr = nav_expr(
is_next,
col("v"),
1,
lit(ScalarValue::Null),
mask_a(),
Some((first, offset)),
);
assert!(fixture.eligible(&expr, true).is_none());
}
}
Ok(())
}
#[test]
fn dictionary_navigation_declines_eager_windows_and_candidate_input_shifts()
-> Result<()> {
let dictionary =
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
for data_type in [
dictionary.clone(),
DataType::Struct(vec![Field::new("d", dictionary, true)].into()),
] {
let fixture = NavFixture::new(vec![
Field::new("v", data_type.clone(), true),
Field::new("n", DataType::Int64, true),
])?;
let candidate = fallible_case("n", col("v").is_null(), Some(lit(false)));
assert_eq!(
candidate.get_type(fixture.schema.as_ref())?,
DataType::Boolean
);
assert!(!crate::planning::expr_safety::can_precompute(
&candidate,
&fixture.schema
));
for is_next in [false, true] {
for anchor in [None, Some(true), Some(false)] {
for (value, default, eligible) in [
(col("v"), ScalarValue::Null, false),
(candidate.clone(), ScalarValue::Boolean(None), false),
(
lit(ScalarValue::Null),
ScalarValue::try_from(&data_type)?,
false,
),
(col("v").is_null(), ScalarValue::Boolean(None), true),
] {
let nav = nav_expr(
is_next,
value,
1,
lit(default),
mask_a(),
anchor.map(|is_first| (lit(is_first), lit(0_u64))),
);
assert_eq!(
fixture.eligible(&nav, true).is_some(),
eligible,
"{data_type}: {nav}"
);
if !eligible {
let (input, bindings, rewritten) =
fixture.materialize(nav.clone(), true)?;
assert!(bindings.is_empty(), "{data_type}: {nav}");
assert!(matches!(input, LogicalPlan::EmptyRelation(_)));
assert_eq!(rewritten, nav);
}
}
}
}
}
Ok(())
}
#[test]
fn navigation_default_coercion_and_invalid_values() -> Result<()> {
let fixture = NavFixture::new(vec![
Field::new("i", DataType::Int64, true),
Field::new("f", DataType::Float64, true),
Field::new("v32", DataType::Int32, true),
Field::new("s16", DataType::Int16, true),
Field::new("d", DataType::Date32, true),
Field::new("dec", DataType::Decimal128(15, 2), true),
Field::new("items", DataType::new_list(DataType::Int64, true), true),
])?;
let case_i = |condition: Expr, other: Expr| {
Expr::Case(Case::new(
None,
vec![(Box::new(condition), Box::new(col("i")))],
Some(Box::new(other)),
))
};
for (value, candidate) in [
(
datafusion::functions::core::coalesce().call(vec![col("i"), col("f")]),
false,
),
(case_i(col("i").gt(lit(0_i64)), col("f")), false),
(
case_i((lit(1_i64) / col("i")).gt(lit(0_i64)), col("f")),
true,
),
] {
for default in [ScalarValue::Float64(Some(1.5)), ScalarValue::Null] {
let nav = nav_expr(
false,
value.clone(),
1,
lit(default.clone()),
mask_a(),
None,
);
let rewrite = fixture
.eligible(&nav, false)
.expect("mixed numeric branches must be eligible");
assert_eq!(rewrite.value_type, DataType::Float64);
assert_eq!(rewrite.default, default);
assert_eq!(
matches!(rewrite.value, NavigationValue::Candidate { .. }),
candidate
);
if !candidate {
let NavigationValue::Prepared(Expr::WindowFunction(window)) =
rewrite.value
else {
panic!("expected prepared navigation");
};
assert_eq!(window.params.args[2], lit(default));
} else {
let (_, _, rewritten) = fixture.materialize(nav, false)?;
let Expr::Case(rewritten) = rewritten else {
panic!("fallible value must retain candidate evaluation");
};
let expected = if default.is_null() {
ScalarValue::Float64(None)
} else {
default
};
assert_eq!(rewritten.else_expr.as_deref(), Some(&lit(expected)));
}
}
}
for value in [
datafusion::functions::core::coalesce().call(vec![col("i"), col("items")]),
case_i(col("i").gt(lit(0_i64)), col("items")),
] {
let nav = nav_expr(
false,
value,
1,
lit(ScalarValue::Float64(Some(1.5))),
mask_a(),
None,
);
assert!(
fixture.eligible(&nav, false).is_none(),
"invalid branch coercion must decline the rewrite"
);
}
for (label, value, offset, expected_type) in [
("bare Date32", col("d"), 1, DataType::Date32),
(
"bare Decimal128",
col("dec"),
1,
DataType::Decimal128(15, 2),
),
(
"compound Decimal128",
col("dec") + col("dec"),
2,
DataType::Decimal128(16, 2),
),
] {
let nav = nav_expr(
true,
value,
offset,
lit(ScalarValue::Boolean(None)),
mask_a(),
None,
);
let rewrite = fixture
.eligible(&nav, true)
.unwrap_or_else(|| panic!("{label} must be eligible"));
let NavigationValue::Prepared(Expr::WindowFunction(window)) = rewrite.value
else {
panic!("{label} must prepare a LEAD window");
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(
datafusion::functions_window::lead_lag::lead_udwf()
)
);
assert_eq!(window.params.args[2], lit(ScalarValue::Null), "{label}");
assert_eq!(
Expr::WindowFunction(window).get_type(fixture.schema.as_ref())?,
expected_type,
"{label}"
);
}
for (value, candidate) in [
(lit(ScalarValue::Null), false),
(fallible_case("i", lit(ScalarValue::Null), None), true),
] {
let nav = nav_expr(
false,
value,
1,
lit(ScalarValue::Boolean(None)),
valid_match_row_expr(),
Some((lit(true), lit(0_u64))),
);
let (input, bindings, rewritten) = fixture.materialize(nav, false)?;
assert!(!bindings.is_empty(), "navigation must be rewritten");
assert_eq!(matches!(&rewritten, Expr::Case(_)), candidate);
let expression_schema =
crate::planning::logical::utils::build_match_aware_schema(
input.schema(),
&fixture.symbols,
)?;
assert_eq!(rewritten.get_type(&expression_schema)?, DataType::Boolean);
}
let cast_s_i32 = cast_expr(col("s16"), DataType::Int32);
for (label, is_next, value, default, expected_default, expected_type) in [
(
"bare NEXT(i, 1, -1)",
true,
col("i"),
lit(-1_i64),
lit(-1_i64),
DataType::Int64,
),
(
"PREV(v32, 1, 0.5)",
false,
col("v32"),
lit(0.5_f64),
lit(0_i32),
DataType::Int32,
),
(
"NEXT(v32, 1, 0.5)",
true,
col("v32"),
lit(0.5_f64),
lit(0_i32),
DataType::Int32,
),
(
"PREV(v32, 1, 1)",
false,
col("v32"),
lit(1_i64),
lit(1_i32),
DataType::Int32,
),
(
"NEXT(v32, 1, 1)",
true,
col("v32"),
lit(1_i64),
lit(1_i32),
DataType::Int32,
),
(
"PREV(v32, 1, '42')",
false,
col("v32"),
lit("42"),
lit(42_i32),
DataType::Int32,
),
(
"compound PREV(CAST(s16 AS INT), 1, 0.5)",
false,
cast_s_i32.clone(),
lit(0.5_f64),
lit(0_i32),
DataType::Int32,
),
(
"compound NEXT(CAST(s16 AS INT), 1, 0.5)",
true,
cast_s_i32.clone(),
lit(0.5_f64),
lit(0_i32),
DataType::Int32,
),
] {
let nav = nav_expr(is_next, value, 1, default, mask_a(), None);
let rewrite = fixture
.eligible(&nav, true)
.unwrap_or_else(|| panic!("{label} must be eligible"));
assert_eq!(lit(rewrite.default), expected_default, "{label}");
let NavigationValue::Prepared(Expr::WindowFunction(window)) = rewrite.value
else {
panic!("{label} must prepare a physical window");
};
assert_eq!(window.params.args[2], expected_default, "{label}");
assert_eq!(
Expr::WindowFunction(window).get_type(fixture.schema.as_ref())?,
expected_type,
"{label}"
);
}
for (label, is_next, value, default) in [
(
"bare PREV uncastable string",
false,
col("v32"),
lit("not_an_int"),
),
(
"bare NEXT uncastable string",
true,
col("v32"),
lit("not_an_int"),
),
("bare PREV overflow", false, col("v32"), lit(i64::MAX)),
(
"compound PREV uncastable string",
false,
cast_s_i32,
lit("not_an_int"),
),
(
"candidate PREV uncastable string",
false,
col("v32") + col("v32"),
lit("not_an_int"),
),
] {
let nav = nav_expr(is_next, value, 1, default, mask_a(), None);
assert!(
fixture.eligible(&nav, true).is_none(),
"{label} must fall back to Deferred"
);
}
Ok(())
}
#[test]
fn cross_symbol_prev_uses_input_lag_in_all_modes() {
for disable_managed in [false, true] {
for depth in [0, 2] {
let prepared = prepare_scoped_prev(
depth,
col("v"),
&[],
&[SortExpr::new(col("v"), true, false)],
disable_managed,
);
assert_eq!(
prepared.input.display_indent().to_string().contains("lag("),
depth > 0
);
if disable_managed {
let Some(CandidatePredicate::History { expr, local: None }) =
prepared.symbol_plans[1].predicate.match_aware()
else {
panic!(
"managed-disabled navigation must retain its rewritten residual"
)
};
assert!(expr.exists(|node| Ok(matches!(node, Expr::WindowFunction(window)
if matches!(&window.params.args[1], Expr::Literal(ScalarValue::UInt64(Some(0)), _))
&& (depth == 0 || matches!(&window.params.args[0], Expr::Column(column)
if prepared.prepared_exprs.iter().any(|expr| expr.name == column.name)))))).unwrap());
} else {
let aggregates = &prepared.managed_aggregates;
assert_eq!(aggregates.len(), 1);
assert_eq!(aggregates[0].func.params.args[1], lit(0_u64));
}
}
}
}
#[test]
fn compound_prev_prepares_only_safe_values_and_preserves_each_lag_input() {
let cast = cast_expr(col("v"), DataType::Float64);
for (value, expected_inputs) in [
(col("d") + col("e"), vec![col("d") + col("e")]),
(col("d") - col("e"), vec![col("d") - col("e")]),
(col("d") / col("e"), vec![col("d"), col("e"), lit(1_i64)]),
(col("v") + col("v"), vec![col("v"), lit(1_i64)]),
(cast.clone(), vec![cast]),
] {
let prepared = prepare_scoped_prev(1, value.clone(), &[], &[], false);
assert_eq!(
prepared.managed_aggregates.len(),
expected_inputs.len(),
"{value}"
);
let inputs = prepared
.prepared_exprs
.iter()
.map(|named| {
let Expr::WindowFunction(window) = &named.expr else {
panic!("prepared LAG window")
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(
datafusion::functions_window::lead_lag::lag_udwf()
)
);
assert_eq!(window.params.args[1], lit(1_u64));
assert!(window.params.partition_by.is_empty());
assert!(window.params.order_by.is_empty());
window.params.args[0].clone()
})
.collect::<Vec<_>>();
assert_eq!(inputs, expected_inputs, "{value}");
}
}
#[test]
fn declined_cross_symbol_prev_remains_deferred() {
let random = datafusion::functions::math::random().call(vec![]);
for (value, partition_by, order_by) in [
(
col("v") + random.clone(),
vec![],
vec![SortExpr::new(col("v"), true, false)],
),
(
col("v"),
vec![random.clone()],
vec![SortExpr::new(col("v"), true, false)],
),
(col("v"), vec![], vec![SortExpr::new(random, true, false)]),
] {
let prepared = prepare_scoped_prev(2, value, &partition_by, &order_by, false);
assert!(prepared.managed_aggregates.is_empty());
assert!(matches!(
prepared.symbol_plans[1].predicate.match_aware(),
Some(CandidatePredicate::History { local: None, .. })
));
}
}
#[test]
fn metadata_and_unqualified_navigation_values_remain_deferred() -> Result<()> {
let fixture = NavFixture::new(vec![Field::new("v", DataType::Int64, true)])?;
let classifier_is_not_null =
col(MatchMetadataColumn::Classifier.as_ref()).is_not_null();
let cast_match_number = cast_expr(
col(MatchMetadataColumn::MatchNumber.as_ref()),
DataType::Int64,
);
let cast_v_plus_match_number = cast_expr(
col("v") + col(MatchMetadataColumn::MatchNumber.as_ref()),
DataType::Int64,
);
let cast_missing_column = cast_expr(col("missing"), DataType::Int64);
for (label, nav) in [
(
"unqualified NEXT(CLASSIFIER() IS NOT NULL)",
nav_expr(
true,
classifier_is_not_null.clone(),
1,
lit(false),
valid_match_row_expr(),
None,
),
),
(
"scoped NEXT(CLASSIFIER() IS NOT NULL)",
nav_expr(
true,
classifier_is_not_null.clone(),
1,
lit(false),
mask_a(),
None,
),
),
(
"unqualified NEXT(CAST(MATCH_NUMBER() AS BIGINT))",
nav_expr(
true,
cast_match_number.clone(),
1,
lit(0_i64),
valid_match_row_expr(),
None,
),
),
(
"scoped NEXT(CAST(MATCH_NUMBER() AS BIGINT))",
nav_expr(
true,
cast_match_number.clone(),
1,
lit(0_i64),
mask_a(),
None,
),
),
(
"scoped PREV(CAST(v + MATCH_NUMBER() AS BIGINT))",
nav_expr(
false,
cast_v_plus_match_number.clone(),
1,
lit(0_i64),
mask_a(),
None,
),
),
(
"unqualified NEXT(v) with validity mask",
nav_expr(true, col("v"), 1, lit(0_i64), valid_match_row_expr(), None),
),
(
"NEXT(v) with unknown classifier mask",
nav_expr(
true,
col("v"),
1,
lit(0_i64),
col("__mr_classifier_unknown"),
None,
),
),
(
"scoped PREV(CAST(missing AS BIGINT))",
nav_expr(false, cast_missing_column, 1, lit(0_i64), mask_a(), None),
),
] {
assert!(
fixture.eligible(&nav, true).is_none(),
"{label} must remain Deferred"
);
}
assert!(
fixture
.eligible(
&nav_expr(true, col("v"), 1, lit(0_i64), mask_a(), None),
true
)
.is_some()
);
for (label, predicate) in [
(
"NEXT(CLASSIFIER() IS NOT NULL, 1, false)",
nav_expr(
true,
classifier_is_not_null,
1,
lit(false),
valid_match_row_expr(),
None,
),
),
(
"NEXT(CAST(MATCH_NUMBER() AS BIGINT), 1, 0) > 0",
nav_expr(
true,
cast_match_number,
1,
lit(0_i64),
valid_match_row_expr(),
None,
)
.gt(lit(0_i64)),
),
(
"PREV(CAST(A.v + MATCH_NUMBER() AS BIGINT), 1, 0) > 0",
nav_expr(
false,
cast_v_plus_match_number,
1,
lit(0_i64),
mask_a(),
None,
)
.gt(lit(0_i64)),
),
] {
let prepared = fixture.prepare(predicate, &[], &[], false)?;
let plan_text = prepared.input.display_indent().to_string();
assert!(
!plan_text.contains("lag(") && !plan_text.contains("lead("),
"{label}: {plan_text}"
);
assert!(prepared.managed_aggregates.is_empty(), "{label}");
assert!(
matches!(
prepared.symbol_plans[1].predicate.match_aware(),
Some(CandidatePredicate::History { local: None, .. })
),
"{label}"
);
}
Ok(())
}
#[test]
fn compound_seven_arg_navigation_rewrites_qualified_and_unqualified_and_declines_zero_offset()
-> Result<()> {
let fixture = NavFixture::new(vec![Field::new("v", DataType::Int64, true)])?;
for (label, is_next, mask, is_first, lo) in [
("qualified PREV(FIRST(A.v, 1), 2)", false, mask_a(), true, 1),
("qualified NEXT(LAST(A.v, 2), 2)", true, mask_a(), false, 2),
(
"unqualified PREV(FIRST(v, 1), 2)",
false,
valid_match_row_expr(),
true,
1,
),
(
"unqualified NEXT(FIRST(v, 0), 2)",
true,
valid_match_row_expr(),
true,
0,
),
] {
let nav = nav_expr(
is_next,
col("v"),
2,
lit(-1_i64),
mask.clone(),
Some((lit(is_first), lit(lo))),
);
let rewrite = fixture
.eligible(&nav, true)
.unwrap_or_else(|| panic!("{label} must be eligible"));
assert_eq!(
rewrite.compound_anchor,
Some((lit(is_first), lit(lo))),
"{label}"
);
assert_eq!(rewrite.classifier_mask, mask, "{label}");
}
for is_next in [false, true] {
let nav = nav_expr(
is_next,
col("v"),
0,
lit(-1_i64),
valid_match_row_expr(),
Some((lit(true), lit(1_u64))),
);
assert!(fixture.eligible(&nav, true).is_none());
}
Ok(())
}
}