datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// 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.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Compile checked logical history specifications into shared physical bindings.

use std::fmt::{Debug, Formatter};
use std::sync::Arc;

use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion::catalog::Session;
use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion::common::{DFSchema, DFSchemaRef, Result, internal_err, plan_err};
use datafusion::logical_expr::expr::AggregateFunction;
use datafusion::logical_expr::{
    Expr, Volatility, physical_planning_context::PhysicalPlanningContext,
};
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_planner::PhysicalPlanner;
use datafusion_physical_expr::ScalarFunctionExpr;
use datafusion_physical_expr::aggregate::{LoweredAggregate, LoweredAggregateBuilder};

use crate::core::{MatchMetadataColumn, NavigationOffset, SymbolId};
use crate::execution::common::expression::{
    plan_predicate_expr, validate_predicate_type,
};
use crate::planning::{
    DeferredHistorySlotOwner, DeferredOperationSpec, DeferredProgramSpec,
};

use super::history::MetadataEncoder;
use super::runtime::CandidateHistory;

#[derive(Debug, Clone, Copy)]
pub(crate) enum DeferredMetadataColumnOwner {
    Metadata(MatchMetadataColumn),
    Classifier(SymbolId),
}

#[cfg(test)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum HistorySource {
    Input(usize),
    Encoded(DeferredMetadataColumnOwner),
}

#[derive(Debug)]
pub(crate) struct DeferredSchemaColumnPlan {
    pub(crate) schema: SchemaRef,
    pub(crate) input_ordinals: Vec<usize>,
    pub(crate) metadata: Arc<[(usize, DeferredMetadataColumnOwner)]>,
}

impl DeferredSchemaColumnPlan {
    /// Input schemas may already contain generated names. Validate those fields
    /// here even when the logical specification supplied their semantic owners.
    fn validate(&self, require_path: bool) -> Result<()> {
        let schema = &self.schema;
        if require_path {
            let path = MatchMetadataColumn::PathId;
            let Some((path_index, field)) = schema.column_with_name(path.as_ref()) else {
                return internal_err!(
                    "deferred history schema is missing required internal column {}",
                    path.as_ref()
                );
            };
            if field.data_type() != &path.data_type() || field.is_nullable() {
                return internal_err!(
                    "deferred history schema requires {} to be non-nullable Int64, found {field:?}",
                    path.as_ref()
                );
            }
            if !self.metadata.iter().any(|(index, owner)| {
                *index == path_index
                    && matches!(
                        owner,
                        DeferredMetadataColumnOwner::Metadata(
                            MatchMetadataColumn::PathId
                        )
                    )
            }) {
                return internal_err!(
                    "deferred history schema must bind {} to path metadata",
                    path.as_ref()
                );
            }
        }
        for &(index, owner) in self.metadata.iter() {
            let field = schema.field(index);
            // Joined input names can repeat. Internal metadata names must be unique.
            if schema
                .fields()
                .iter()
                .filter(|f| f.name() == field.name())
                .count()
                != 1
            {
                return internal_err!(
                    "deferred history schema contains duplicate internal column {}",
                    field.name()
                );
            }
            let (ty, nullable) = match owner {
                DeferredMetadataColumnOwner::Metadata(column) => {
                    (column.data_type(), column.is_nullable())
                }
                DeferredMetadataColumnOwner::Classifier(_) => (DataType::Boolean, true),
            };
            if field.data_type() != &ty || field.is_nullable() != nullable {
                return internal_err!(
                    "deferred history column {} must be {ty:?} nullable={nullable}, found {field:?}",
                    field.name()
                );
            }
        }
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn try_new(schema: SchemaRef) -> Result<Self> {
        let sources = schema.fields().iter().enumerate().map(|(i, field)| {
            MatchMetadataColumn::all()
                .into_iter()
                .find(|column| column.as_ref() == field.name())
                .map_or(HistorySource::Input(i), |column| {
                    HistorySource::Encoded(DeferredMetadataColumnOwner::Metadata(column))
                })
        });
        Self::bind(Arc::clone(&schema), sources)
    }

    #[cfg(test)]
    pub(crate) fn try_new_history(
        schema: SchemaRef,
        sources: Vec<HistorySource>,
    ) -> Result<Self> {
        Self::from_sources(schema, sources.into_iter(), true)
    }

    #[cfg(test)]
    pub(crate) fn bind(
        schema: SchemaRef,
        sources: impl ExactSizeIterator<Item = HistorySource>,
    ) -> Result<Self> {
        Self::from_sources(schema, sources, false)
    }

    #[cfg(test)]
    fn from_sources(
        schema: SchemaRef,
        sources: impl ExactSizeIterator<Item = HistorySource>,
        require_path: bool,
    ) -> Result<Self> {
        if sources.len() != schema.fields().len() {
            return internal_err!("deferred history must bind every schema field");
        }
        let mut input_ordinals = Vec::new();
        let mut metadata = Vec::new();
        for (index, source) in sources.enumerate() {
            match source {
                HistorySource::Input(ordinal) => input_ordinals.push(ordinal),
                HistorySource::Encoded(owner) => metadata.push((index, owner)),
            }
        }
        let plan = Self {
            schema,
            input_ordinals,
            metadata: metadata.into(),
        };
        plan.validate(require_path)?;
        Ok(plan)
    }
}

/// One DataFusion-lowered aggregate used by Deferred evaluation.
pub(crate) struct DeferredAggregateOperation {
    pub(crate) lowered: LoweredAggregate,
    pub(crate) input_exprs: Vec<Arc<dyn PhysicalExpr>>,
}

impl DeferredAggregateOperation {
    pub(crate) fn new(lowered: LoweredAggregate) -> Self {
        let mut input_exprs = lowered.aggregate.expressions();
        let ordering = lowered.aggregate.order_bys();
        input_exprs.extend(ordering.iter().map(|sort| Arc::clone(&sort.expr)));
        Self {
            lowered,
            input_exprs,
        }
    }
}

/// Test adapter for constructing a shared physical projection.
#[cfg(test)]
pub(crate) struct DeferredPredicateProgram {
    pub(crate) expressions: Vec<Option<Arc<dyn PhysicalExpr>>>,
    pub(crate) schema: SchemaRef,
    pub(crate) extra_columns: Vec<usize>,
}

/// Only the operations and direct history values demanded by one symbol.
pub(super) struct DeferredSymbolPredicateProgram {
    pub(super) operation_indices: Vec<usize>,
    pub(super) extra_ordinals: Vec<usize>,
    pub(super) predicate_schema: SchemaRef,
    pub(super) max_lookahead_rows: NavigationOffset,
    pub(super) save_history_inputs: bool,
    pub(super) predicate: Option<Arc<dyn PhysicalExpr>>,
}

/// Factory created after deferred expressions and input columns are checked.
pub(crate) struct DeferredEvaluatorFactory {
    program: Arc<BoundHistoryProgram>,
}

impl DeferredEvaluatorFactory {
    #[cfg(test)]
    pub(crate) fn try_new(
        history: DeferredSchemaColumnPlan,
        operations: Vec<DeferredAggregateOperation>,
        predicates: DeferredPredicateProgram,
        symbol_names: &[Option<String>],
    ) -> Result<Self> {
        let symbol_predicates = predicates
            .expressions
            .into_iter()
            .map(|predicate| {
                Some(DeferredSymbolPredicateProgram {
                    operation_indices: (0..operations.len()).collect(),
                    extra_ordinals: predicates.extra_columns.clone(),
                    predicate_schema: Arc::clone(&predicates.schema),
                    max_lookahead_rows: NavigationOffset::ZERO,
                    save_history_inputs: false,
                    predicate,
                })
            })
            .collect();
        Ok(Self {
            program: BoundHistoryProgram::bind(
                operations,
                symbol_predicates,
                history,
                symbol_names,
            )?,
        })
    }

    pub(crate) fn input_ordinals(&self) -> &[usize] {
        &self.program.history.input_ordinals
    }

    pub(crate) fn candidate_history(
        &self,
        memory: &datafusion_execution::memory_pool::MemoryReservation,
    ) -> Result<CandidateHistory> {
        // The caller retains the global halo; each bound predicate owns its
        // narrower lookahead budget for evaluation.
        CandidateHistory::new(Arc::clone(&self.program), memory)
    }

    /// Return every physical-expression root evaluated by the candidate history evaluator.
    pub(crate) fn physical_expr_roots(&self) -> Vec<Arc<dyn PhysicalExpr>> {
        let mut roots = Vec::new();
        for operation in &self.program.operations {
            let operation = &operation.planned;
            roots.extend(operation.input_exprs.iter().cloned());
            roots.extend(operation.lowered.filter.iter().cloned());
        }
        roots.extend(
            self.program
                .predicates
                .iter()
                .flatten()
                .filter_map(|p| p.predicate.clone()),
        );
        roots
    }

    pub(crate) fn immutable_roots(roots: &[Arc<dyn PhysicalExpr>]) -> bool {
        roots.iter().all(|root| {
            let mut immutable = true;
            root.apply(|node| {
                if node.is_volatile_node()
                    || node
                        .downcast_ref::<ScalarFunctionExpr>()
                        .is_some_and(|function| {
                            function.fun().signature().volatility != Volatility::Immutable
                        })
                {
                    immutable = false;
                    Ok(TreeNodeRecursion::Stop)
                } else {
                    Ok(TreeNodeRecursion::Continue)
                }
            })
            .expect("infallible expression inspection");
            immutable
        })
    }
}

impl Debug for DeferredEvaluatorFactory {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeferredEvaluatorFactory")
            .field("input_schema", &self.program.history.schema)
            .finish()
    }
}

pub(super) struct BoundHistoryOperation {
    pub(super) planned: DeferredAggregateOperation,
    pub(super) types: Vec<DataType>,
}

/// Physical expression bindings shared by every scan of the same plan.
pub(super) struct BoundHistoryProgram {
    pub(super) history: DeferredSchemaColumnPlan,
    pub(super) encoder: MetadataEncoder,
    pub(super) operations: Vec<BoundHistoryOperation>,
    pub(super) predicates: Vec<Option<DeferredSymbolPredicateProgram>>,
}

impl BoundHistoryProgram {
    #[cfg(test)]
    pub(super) fn try_new(
        operations: Vec<DeferredAggregateOperation>,
        predicate_program: DeferredPredicateProgram,
        history: DeferredSchemaColumnPlan,
        symbol_names: &[Option<String>],
    ) -> Result<Arc<Self>> {
        Ok(DeferredEvaluatorFactory::try_new(
            history,
            operations,
            predicate_program,
            symbol_names,
        )?
        .program)
    }

    fn bind(
        operations: Vec<DeferredAggregateOperation>,
        mut predicates: Vec<Option<DeferredSymbolPredicateProgram>>,
        history: DeferredSchemaColumnPlan,
        symbol_names: &[Option<String>],
    ) -> Result<Arc<Self>> {
        let encoder = MetadataEncoder::try_new(&history, symbol_names)?;
        // Replaying raw rows must never invoke a volatile aggregate argument again.
        // Immutable inputs can instead re-read a competing prefix from the arena.
        for predicate in predicates.iter_mut().flatten() {
            predicate.save_history_inputs =
                predicate.operation_indices.iter().any(|&index| {
                    let op = &operations[index];
                    op.lowered.aggregate.fun().signature().volatility
                        != Volatility::Immutable
                        || !DeferredEvaluatorFactory::immutable_roots(&op.input_exprs)
                        || op.lowered.filter.as_ref().is_some_and(|filter| {
                            !DeferredEvaluatorFactory::immutable_roots(
                                std::slice::from_ref(filter),
                            )
                        })
                });
        }
        Ok(Arc::new(Self {
            operations: operations
                .into_iter()
                .map(|planned| {
                    let types = planned
                        .input_exprs
                        .iter()
                        .chain(planned.lowered.filter.iter())
                        .map(|expr| {
                            expr.return_field(&history.schema)
                                .map(|field| field.data_type().clone())
                        })
                        .collect::<Result<_>>()?;
                    Ok(BoundHistoryOperation { planned, types })
                })
                .collect::<Result<Vec<_>>>()?,
            history,
            encoder,
            predicates,
        }))
    }
}

fn rebase_physical_expr(
    expr: Arc<dyn PhysicalExpr>,
    target_schema: &SchemaRef,
    source_to_target: &[Option<usize>],
) -> Result<Arc<dyn PhysicalExpr>> {
    use datafusion::physical_expr::expressions::Column;

    expr.transform(|node| {
        let Some(column) = node.downcast_ref::<Column>() else {
            return Ok(Transformed::no(node));
        };
        let target_index = source_to_target
            .get(column.index())
            .copied()
            .ok_or_else(|| {
                datafusion_common::DataFusionError::Internal(format!(
                    "deferred expression column {} references index {} outside source mapping of length {}",
                    column.name(),
                    column.index(),
                    source_to_target.len()
                ))
            })?
            .ok_or_else(|| {
                datafusion_common::DataFusionError::Internal(format!(
                    "deferred expression requires source column {} at index {}, but the evaluator input does not provide it",
                    column.name(),
                    column.index()
                ))
            })?;
        let target_field = target_schema.fields().get(target_index).ok_or_else(|| {
            datafusion_common::DataFusionError::Internal(format!(
                "deferred expression maps source column {} to index {target_index} outside evaluator schema of length {}",
                column.name(),
                target_schema.fields().len()
            ))
        })?;
        Ok(Transformed::yes(Arc::new(Column::new(
            target_field.name(),
            target_index,
        ))))
    })
    .map(|transformed| transformed.data)
}

fn plan_history(
    spec: &DeferredProgramSpec,
    physical_input_schema: &SchemaRef,
    symbols: &[SymbolId],
) -> Result<DeferredSchemaColumnPlan> {
    let mut fields = Vec::with_capacity(spec.history_owners().len());
    let mut input_ordinals = Vec::new();
    let mut metadata = Vec::new();
    for (index, (&owner, expected)) in spec
        .history_owners()
        .iter()
        .zip(spec.history_schema().fields())
        .enumerate()
    {
        let field = match owner {
            DeferredHistorySlotOwner::Input { ordinal } => {
                let actual = physical_input_schema.fields().get(ordinal).ok_or_else(|| {
                    datafusion_common::DataFusionError::Internal(format!(
                        "deferred history input ordinal {ordinal} is outside physical input schema of length {}",
                        physical_input_schema.fields().len()
                    ))
                })?;
                // Physical projections may conservatively widen the
                // nullability of otherwise identical passthrough fields.
                if expected.name() != actual.name()
                    || expected.data_type() != actual.data_type()
                {
                    return internal_err!(
                        "deferred history field {} must be {:?}, found {} {:?}",
                        expected.name(),
                        expected.data_type(),
                        actual.name(),
                        actual.data_type()
                    );
                }
                input_ordinals.push(ordinal);
                Arc::clone(actual)
            }
            DeferredHistorySlotOwner::Metadata(column) => {
                metadata.push((index, DeferredMetadataColumnOwner::Metadata(column)));
                Arc::clone(expected)
            }
            DeferredHistorySlotOwner::Classifier(logical_id) => {
                let symbol = symbols[logical_id.index()];
                metadata.push((index, DeferredMetadataColumnOwner::Classifier(symbol)));
                Arc::clone(expected)
            }
        };
        fields.push(field);
    }
    let schema = Arc::new(Schema::new_with_metadata(
        fields,
        physical_input_schema.metadata().clone(),
    ));
    let history = DeferredSchemaColumnPlan {
        schema,
        input_ordinals,
        metadata: metadata.into(),
    };
    history.validate(true)?;
    Ok(history)
}

fn plan_operation(
    index: usize,
    operation: &DeferredOperationSpec,
    session: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
    logical_schema: &DFSchemaRef,
    physical_schema: &SchemaRef,
) -> Result<(DeferredAggregateOperation, Field)> {
    let expression = operation.expr().clone().unalias();
    let Expr::WindowFunction(window) = expression else {
        return datafusion_common::internal_err!(
            "sealed deferred operation was not a window function"
        );
    };
    let udaf = match window.fun {
        datafusion::logical_expr::WindowFunctionDefinition::AggregateUDF(udaf) => udaf,
        other => {
            return datafusion_common::internal_err!(
                "sealed deferred operation uses non-aggregate window function {}",
                other.name()
            );
        }
    };
    let aggregate = Expr::AggregateFunction(AggregateFunction::new_udf(
        udaf,
        window.params.args,
        window.params.distinct,
        window.params.filter,
        window.params.order_by,
        window.params.null_treatment,
    ));
    let mut lowered = LoweredAggregateBuilder::new(
        &aggregate,
        logical_schema.as_ref(),
        physical_schema.as_ref(),
        session.execution_props(),
        planning_ctx,
    )
    .with_name(operation.result_field().name())
    .build()?;
    let sensitivity = lowered.aggregate.order_sensitivity();
    if sensitivity.hard_requires() {
        return plan_err!(
            "MATCH_RECOGNIZE Deferred aggregate '{}' cannot apply ORDER BY because its accumulator requires presorted input",
            lowered.aggregate.fun().name()
        );
    }
    if sensitivity.is_beneficial() {
        // The path deltas arrive chronologically. Let the accumulator apply
        // the SQL ordering using the separately evaluated sort keys.
        lowered.aggregate = Arc::clone(&lowered.aggregate)
            .with_beneficial_ordering(false)?
            .map(Arc::new)
            .ok_or_else(|| {
                datafusion::common::plan_datafusion_err!(
                    "MATCH_RECOGNIZE Deferred aggregate '{}' cannot accept unordered input for ORDER BY",
                    lowered.aggregate.fun().name()
                )
            })?;
    }
    let result_field = lowered.aggregate.field();
    let expected = operation.result_field();
    // Physical inputs may conservatively widen nullability or carry Arrow
    // field metadata that aggregates such as FIRST_VALUE/LAST_VALUE preserve.
    if result_field.name() != expected.name()
        || result_field.data_type() != expected.data_type()
        || (expected.is_nullable() && !result_field.is_nullable())
    {
        return internal_err!(
            "Deferred operation {index} lowered to field {:?}, expected {:?}",
            result_field,
            expected
        );
    }
    Ok((
        DeferredAggregateOperation::new(lowered),
        result_field.as_ref().clone(),
    ))
}

/// Scalar UDFs cache their return field from the DFSchema during lowering.
/// Preserve qualifiers, but bind against the actual Arrow fields and metadata.
fn physical_backed_schema(logical: &DFSchema, physical: &Schema) -> Result<DFSchema> {
    if logical.fields().len() != physical.fields().len() {
        return internal_err!("Deferred logical and physical schema widths disagree");
    }
    DFSchema::new_with_metadata(
        logical
            .iter()
            .zip(physical.fields())
            .map(|((qualifier, _), field)| (qualifier.cloned(), Arc::clone(field)))
            .collect(),
        physical.metadata().clone(),
    )
}

fn plan_operations(
    spec: &DeferredProgramSpec,
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
    history: &DeferredSchemaColumnPlan,
) -> Result<(Vec<DeferredAggregateOperation>, Vec<Field>)> {
    let logical_schema = Arc::new(physical_backed_schema(
        spec.history_schema(),
        &history.schema,
    )?);
    let mut operations = Vec::with_capacity(spec.operations().len());
    let mut fields = Vec::with_capacity(spec.operations().len());
    for (index, operation) in spec.operations().iter().enumerate() {
        let (planned, field) = plan_operation(
            index,
            operation,
            session_state,
            planning_ctx,
            &logical_schema,
            &history.schema,
        )?;
        operations.push(planned);
        fields.push(field);
    }
    Ok((operations, fields))
}

fn plan_predicates(
    spec: &DeferredProgramSpec,
    planner: &dyn PhysicalPlanner,
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
    symbols: &[SymbolId],
    operation_fields: &[Field],
    history: &DeferredSchemaColumnPlan,
) -> Result<Vec<Option<DeferredSymbolPredicateProgram>>> {
    let source_fields = history
        .schema
        .fields()
        .iter()
        .cloned()
        .chain(operation_fields.iter().cloned().map(Arc::new))
        .collect::<Vec<_>>();
    let source_schema = physical_backed_schema(
        spec.predicate_input_schema(),
        &Schema::new_with_metadata(source_fields, history.schema.metadata().clone()),
    )?;
    let mut predicates = (0..symbols.len() + 1).map(|_| None).collect::<Vec<_>>();
    for predicate in spec.predicates().iter().flatten() {
        let logical_id = predicate.symbol_id();
        let mut fields = Vec::new();
        let mut source_to_target = vec![None; source_schema.fields().len()];
        for &index in predicate.operation_indices() {
            source_to_target[history.schema.fields().len() + index] = Some(fields.len());
            fields.push(operation_fields[index].clone());
        }
        for &index in predicate.extra_ordinals() {
            source_to_target[index] = Some(fields.len());
            fields.push(history.schema.field(index).clone());
        }
        let schema = Arc::new(Schema::new(fields));
        let physical = plan_predicate_expr(
            predicate.expr().clone(),
            &source_schema,
            logical_id,
            planner,
            session_state,
            planning_ctx,
        )?;
        let physical = rebase_physical_expr(physical, &schema, &source_to_target)?;
        validate_predicate_type(physical.as_ref(), schema.as_ref(), logical_id)?;
        predicates[symbols[logical_id.index()].index()] =
            Some(DeferredSymbolPredicateProgram {
                operation_indices: predicate.operation_indices().to_vec(),
                extra_ordinals: predicate.extra_ordinals().to_vec(),
                predicate_schema: schema,
                max_lookahead_rows: predicate.max_lookahead_rows(),
                save_history_inputs: false,
                predicate: Some(physical),
            });
    }
    Ok(predicates)
}

impl DeferredEvaluatorFactory {
    pub(crate) fn try_from_spec(
        spec: &DeferredProgramSpec,
        planner: &dyn PhysicalPlanner,
        session_state: &dyn Session,
        planning_ctx: &PhysicalPlanningContext,
        physical_input_schema: &SchemaRef,
        symbols: &[SymbolId],
        symbol_names: &[Option<String>],
    ) -> Result<Self> {
        if symbols.len() != spec.predicates().len() {
            return internal_err!(
                "Deferred symbol table disagrees with its sealed predicates"
            );
        }
        let history = plan_history(spec, physical_input_schema, symbols)?;
        let (accumulators, operation_fields) =
            plan_operations(spec, session_state, planning_ctx, &history)?;
        let predicates = plan_predicates(
            spec,
            planner,
            session_state,
            planning_ctx,
            symbols,
            &operation_fields,
            &history,
        )?;
        // Predicate inputs above were built from these exact operation fields and
        // history extras, so no second schema-validation pass is necessary.
        Ok(Self {
            program: BoundHistoryProgram::bind(
                accumulators,
                predicates,
                history,
                symbol_names,
            )?,
        })
    }
}

#[cfg(test)]
#[path = "tests/evaluator.rs"]
mod evaluator_tests;

#[cfg(test)]
#[path = "tests/factory.rs"]
mod factory_tests;

#[cfg(test)]
#[path = "tests/compiler.rs"]
mod compiler_tests;