datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache 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
// 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.

//! Binds supported aggregate writers and navigation sources to their state layouts.
//!
//! Recipes construct register and navigation storage and projections together.
//! Predicate truth is compiled separately and cannot be changed by this phase.
//!
//! Register assembly is all-or-nothing for one match program. Capacity,
//! binding, or cross-artifact validation failure returns one
//! typed downgrade reason and publishes no writers, layout, or partial
//! navigation plan from the failed attempt.

use crate::core::vm::NavigationSource;
use std::collections::{BTreeMap, HashMap};

use crate::planning::ManagedAggregateBackend;
use crate::planning::logical::LogicalMatchProgram;
use datafusion::common::DFSchema;
// These types define the program layout consumed by the execution module.
use crate::core::vm::{
    AggregateKind, AggregateLayout, AggregateValueSource, MAX_NAV_SLOTS,
    MAX_PREV_BUFFERS, MAX_REGISTERS, NavSlotInfo, NavigationLayout, NavigationLocation,
    NavigationValueDomain, PrevBufferInfo, RegisterLayout, RegisterWriter, SlotInfo,
    SlotValueType,
};
use crate::planning::logical::LogicalSymbolId;
use recipe::{NavigationRequestKind, RegisterAggregateRecipe};

mod recipe;

pub(crate) use recipe::{AggregateAssembly, build_aggregate_assemblies};

/// A complete, internally consistent state-update program produced by planning.
///
/// Assembly never exposes partial writers or a layout from a failed
/// attempt. Consumers either receive this value or a typed downgrade reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AssembledMatchVm {
    /// Dense per-symbol state updates in logical symbol order.
    pub(crate) register_writers: Vec<Vec<RegisterWriter>>,
    /// Register, input-binding, and navigation storage layout for the program.
    pub(crate) register_layout: RegisterLayout,
}

impl AssembledMatchVm {
    pub(crate) fn empty(symbol_count: usize, aggregate_count: usize) -> Self {
        Self {
            register_writers: vec![Vec::new(); symbol_count],
            register_layout: RegisterLayout::empty_compact(aggregate_count),
        }
    }
}

/// Why register-backed state-update assembly must be abandoned for one match program.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum VmAssemblyDowngrade {
    /// A referenced input name resolves to more than one column.
    AmbiguousInputColumn {
        /// Ambiguous input column name.
        column: String,
    },
    /// The aggregate state would exceed the register-file capacity.
    RegisterCapacity {
        /// Stable managed-aggregate index whose allocation failed.
        aggregate_id: usize,
        /// Registers allocated before this aggregate.
        used: usize,
        /// Registers required by this aggregate.
        required: usize,
        /// Total register capacity.
        capacity: usize,
    },
    /// Navigation state would exceed the Standard arena capacity.
    NavigationCapacity {
        /// FIRST/LAST/PREV slots allocated before the rejected request.
        nav_slots: usize,
        /// Deep-PREV buffers allocated before the rejected request.
        prev_buffers: usize,
    },
    /// Assembly could not assign a runtime source for an aggregate result.
    MissingAggregateValueSource {
        /// Stable managed-aggregate index.
        aggregate_id: usize,
    },
    /// Cross-artifact validation rejected the assembled state-update program.
    InvalidArtifacts {
        /// Validation error suitable for diagnostics.
        detail: String,
    },
}

/// Assembles typed writers and layouts for register-backed aggregate state.
///
/// Successful entries use dense logical-symbol order. A failed attempt returns
/// only a typed downgrade reason; partial writers and layouts are discarded.
pub(crate) fn assemble_match_vm_state(
    program: &LogicalMatchProgram,
    aggregates: &[AggregateAssembly],
    input_schema: &DFSchema,
) -> Result<AssembledMatchVm, VmAssemblyDowngrade> {
    debug_assert_eq!(program.managed_aggregates().len(), aggregates.len());
    if !aggregates
        .iter()
        .any(|aggregate| aggregate.backend == ManagedAggregateBackend::Registers)
    {
        return Ok(AssembledMatchVm::empty(
            program.symbols().len(),
            aggregates.len(),
        ));
    }

    // Duplicate input names make every case-insensitive recipe binding suspect.
    // Preserve this whole-program preflight before inspecting any one recipe.
    if let Some(column) = ambiguous_input_column(input_schema) {
        return Err(VmAssemblyDowngrade::AmbiguousInputColumn { column });
    }

    let mut layouts = vec![AggregateLayout::default(); aggregates.len()];
    let mut register_writers = vec![Vec::new(); program.symbols().len()];
    let mut row_input_names = Vec::new();
    let mut row_input_as_float = Vec::new();
    let mut row_inputs = HashMap::new();
    let mut statistical_states = HashMap::new();
    let mut sum_avg_states = HashMap::<
        (Option<LogicalSymbolId>, String, SlotValueType, i8, bool),
        usize,
    >::new();
    let mut next_slot = 0;
    let mut navigation_requests = Vec::new();

    for (index, aggregate) in aggregates.iter().enumerate() {
        if aggregate.backend != ManagedAggregateBackend::Registers {
            continue;
        }
        let recipe = aggregate.recipe.register().ok_or(
            VmAssemblyDowngrade::MissingAggregateValueSource {
                aggregate_id: aggregate.logical.id().index(),
            },
        )?;
        match recipe {
            RegisterAggregateRecipe::LeadingFirst { column } => {
                layouts[index].value_source = AggregateValueSource::CandidateStart {
                    column: column.clone(),
                };
                continue;
            }
            RegisterAggregateRecipe::Navigation(request) => {
                navigation_requests.push(request);
                continue;
            }
            _ => {}
        }
        let (value_type, scale, kind, input) = match recipe {
            RegisterAggregateRecipe::Algebraic { kind, input, .. } => (
                input.value_type,
                input.scale,
                *kind,
                Some((&input.column, input.nullable, input.as_float)),
            ),
            RegisterAggregateRecipe::Variance { input, .. } => (
                SlotValueType::Float64,
                0,
                AggregateKind::Variance,
                Some((&input.column, input.nullable, input.as_float)),
            ),
            RegisterAggregateRecipe::NonNullCount { input } => (
                SlotValueType::Int64,
                0,
                AggregateKind::Additive,
                Some((&input.column, true, false)),
            ),
            RegisterAggregateRecipe::RowCount => {
                (SlotValueType::Int64, 0, AggregateKind::Additive, None)
            }
            _ => unreachable!("navigation projections were handled above"),
        };
        // Preserve input order, first spelling and nullability. Native and
        // Float64-coerced reads of the same column have distinct bindings.
        let input = input.map(|(column, nullable, as_float)| {
            *row_inputs
                .entry((column.to_ascii_lowercase(), as_float))
                .or_insert_with(|| {
                    let index = row_input_names.len();
                    row_input_names.push(column.clone());
                    row_input_as_float.push(as_float);
                    (index, nullable)
                })
        });
        let statistical_key = match recipe {
            RegisterAggregateRecipe::Variance { input, .. } => Some((
                aggregate.logical.symbol(),
                input.column.to_ascii_lowercase(),
            )),
            _ => None,
        };
        let sum_avg_key = match recipe {
            RegisterAggregateRecipe::Algebraic {
                kind: AggregateKind::Additive,
                track_nonnull: true,
                input,
            }
            | RegisterAggregateRecipe::Algebraic {
                kind: AggregateKind::Avg,
                input,
                ..
            } => Some((
                aggregate.logical.symbol(),
                input.column.to_ascii_lowercase(),
                input.value_type,
                input.scale,
                input.as_float,
            )),
            _ => None,
        };
        let shared = statistical_key
            .as_ref()
            .and_then(|key| statistical_states.get(key).copied())
            .or_else(|| {
                sum_avg_key
                    .as_ref()
                    .and_then(|key| sum_avg_states.get(key).copied())
                    .map(|start| SlotInfo::with_kind(start, value_type, scale, kind))
            });
        let slot = shared
            .unwrap_or_else(|| SlotInfo::with_kind(next_slot, value_type, scale, kind));
        let nonnull_count_slot = matches!(
            recipe,
            RegisterAggregateRecipe::Algebraic {
                track_nonnull: true,
                ..
            }
        )
        .then_some(slot.start_slot + slot.slot_count);
        if shared.is_none() {
            let required = slot.slot_count + usize::from(nonnull_count_slot.is_some());
            if next_slot + required > MAX_REGISTERS {
                return Err(VmAssemblyDowngrade::RegisterCapacity {
                    aggregate_id: aggregate.logical.id().index(),
                    used: next_slot,
                    required,
                    capacity: MAX_REGISTERS,
                });
            }
            next_slot += required;
            if let Some(key) = statistical_key {
                statistical_states.insert(key, slot);
            }
            if let Some(key) = sum_avg_key {
                sum_avg_states.insert(key, slot.start_slot);
            }
            let writer = match recipe {
                RegisterAggregateRecipe::RowCount
                | RegisterAggregateRecipe::NonNullCount { .. } => RegisterWriter::Count {
                    aggregate: index,
                    input: input.map(|(index, _)| index),
                },
                _ => {
                    let (input, nullable) = input.expect("numeric recipes have an input");
                    RegisterWriter::Accumulate {
                        aggregate: index,
                        input,
                        nullable,
                    }
                }
            };
            if let Some(owner) = aggregate.logical.symbol() {
                register_writers[owner.index()].push(writer);
            } else {
                for writers in &mut register_writers {
                    writers.push(writer);
                }
            }
        }
        layouts[index] = AggregateLayout {
            slot: Some(slot),
            value_source: register_value_source(recipe, &slot),
            nonnull_count_slot,
        };
    }

    let mut layout = NavigationLayout::default();
    let mut primitive_column_names = Vec::new();
    let mut decimal128_column_names = Vec::new();
    let mut locations = HashMap::<NavigationKey, usize>::new();

    // Coalesce multiple LAST/PREV depths on the same (scope, domain, column)
    // into one shared PrevBuffer sized to the maximum requested depth when any
    // depth exceeds 1; shallow depth-0/1-only tracks keep compact Last/Prev slots.
    let mut max_last_depth =
        HashMap::<(Option<LogicalSymbolId>, NavigationValueDomain, &str), usize>::new();
    for request in &navigation_requests {
        if let NavigationRequestKind::LastOffset { depth, .. } = &request.kind {
            let col_key = match request.domain {
                NavigationValueDomain::Classifier => "",
                NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
                    request.column.as_str()
                }
            };
            let entry = max_last_depth
                .entry((request.scope, request.domain, col_key))
                .or_insert(0);
            *entry = (*entry).max(*depth);
        }
    }

    for request in navigation_requests {
        let col_key = match request.domain {
            NavigationValueDomain::Classifier => "",
            NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
                request.column.as_str()
            }
        };
        let (storage, default_value, buffer_max_depth) = match &request.kind {
            NavigationRequestKind::First {
                offset,
                default_value,
            } => (NavigationStorage::First(*offset), default_value.clone(), 0),
            NavigationRequestKind::LastOffset { default_value, .. } => {
                let max_depth = max_last_depth
                    .get(&(request.scope, request.domain, col_key))
                    .copied()
                    .unwrap_or(0);
                if max_depth <= 1 {
                    (NavigationStorage::Last, default_value.clone(), max_depth)
                } else {
                    (
                        NavigationStorage::PrevBuffer,
                        default_value.clone(),
                        max_depth,
                    )
                }
            }
        };
        // All scopes read the same row value for an exact column binding.
        // Classifier navigation reads the transition's runtime symbol ID directly.
        let value_idx = match request.domain {
            NavigationValueDomain::Classifier => 0,
            NavigationValueDomain::Primitive | NavigationValueDomain::Decimal128 => {
                let names = if request.domain == NavigationValueDomain::Primitive {
                    &mut primitive_column_names
                } else {
                    &mut decimal128_column_names
                };
                names
                    .iter()
                    .position(|name| name == &request.column)
                    .unwrap_or_else(|| {
                        let index = names.len();
                        names.push(request.column.clone());
                        index
                    })
            }
        };
        let key = NavigationKey {
            scope: request.scope,
            domain: request.domain,
            value_idx,
            storage,
        };
        let make_slot = |nav_slot| NavSlotInfo {
            symbol_idx: request.scope.map(LogicalSymbolId::index),
            nav_slot,
            value_idx,
            domain: request.domain,
        };
        let width = request.domain.storage_width();
        let (used, capacity) = match storage {
            NavigationStorage::First(_) | NavigationStorage::Last => {
                (&mut layout.num_nav_slots, MAX_NAV_SLOTS)
            }
            NavigationStorage::PrevBuffer => {
                (&mut layout.num_prev_buffers, MAX_PREV_BUFFERS)
            }
        };
        let index = match locations.entry(key) {
            std::collections::hash_map::Entry::Occupied(entry) => *entry.get(),
            std::collections::hash_map::Entry::Vacant(entry) => {
                let index = *used;
                if index + width > capacity {
                    return Err(VmAssemblyDowngrade::NavigationCapacity {
                        nav_slots: layout.num_nav_slots,
                        prev_buffers: layout.num_prev_buffers,
                    });
                }
                *used += width;
                entry.insert(index);
                match storage {
                    NavigationStorage::First(offset) => {
                        let pos = layout.first_slots.len();
                        layout.first_slots.push(make_slot(index));
                        if offset > 0 || !layout.first_offsets.is_empty() {
                            layout.first_offsets.resize(pos, 0);
                            layout.first_offsets.push(offset);
                        }
                    }
                    NavigationStorage::Last => layout.last_slots.push(make_slot(index)),
                    NavigationStorage::PrevBuffer => {
                        layout.prev_buffer_slots.push(PrevBufferInfo {
                            symbol_idx: request.scope.map(LogicalSymbolId::index),
                            depth: buffer_max_depth,
                            buffer_idx: index,
                            value_idx,
                            domain: request.domain,
                        });
                    }
                }
                index
            }
        };
        let location = match (storage, &request.kind) {
            (NavigationStorage::First(_), _) => NavigationLocation::First(index),
            (
                NavigationStorage::Last,
                NavigationRequestKind::LastOffset { depth: 1, .. },
            ) => {
                if !layout.prev_slots.iter().any(|slot| slot.nav_slot == index) {
                    layout.prev_slots.push(make_slot(index));
                }
                NavigationLocation::Prev(index)
            }
            (NavigationStorage::Last, _) => NavigationLocation::Last(index),
            (
                NavigationStorage::PrevBuffer,
                NavigationRequestKind::LastOffset { depth, .. },
            ) => NavigationLocation::PrevBuffer {
                index,
                depth: *depth,
            },
            (NavigationStorage::PrevBuffer, NavigationRequestKind::First { .. }) => {
                unreachable!("FIRST navigation never uses PrevBuffer storage")
            }
        };
        layouts[request.aggregate_id.index()].value_source =
            AggregateValueSource::Navigation(NavigationSource {
                location,
                domain: request.domain,
                default_value,
            });
    }

    // A later PREV can add a reader to an earlier LAST allocation.
    layout.prev_slots.sort_unstable_by_key(|slot| slot.nav_slot);
    let register_layout = RegisterLayout::builder(next_slot, layouts)
        .row_inputs(row_input_names, row_input_as_float)
        .navigation_inputs(
            primitive_column_names,
            decimal128_column_names,
            layout.has_navigation().then_some(layout),
        )
        .try_build()
        .map_err(|detail| VmAssemblyDowngrade::InvalidArtifacts { detail })?;
    Ok(AssembledMatchVm {
        register_writers,
        register_layout,
    })
}

fn ambiguous_input_column(input_schema: &DFSchema) -> Option<String> {
    let mut first_name_by_normalized: BTreeMap<String, String> = BTreeMap::new();
    for field in input_schema.fields() {
        let normalized = field.name().to_ascii_lowercase();
        if let Some(first_name) = first_name_by_normalized.get(&normalized) {
            return Some(first_name.clone());
        }
        first_name_by_normalized.insert(normalized, field.name().to_string());
    }
    None
}

fn register_value_source(
    recipe: &RegisterAggregateRecipe,
    si: &SlotInfo,
) -> AggregateValueSource {
    use crate::core::vm::{AggregateKind, AggregateValueSource as AVS};

    let slot = si.start_slot;
    match recipe {
        RegisterAggregateRecipe::Variance { projection, .. } => AVS::Variance {
            state_slot: slot,
            projection: *projection,
        },
        RegisterAggregateRecipe::Algebraic {
            kind: AggregateKind::Avg,
            ..
        } => avg_value_source(slot, si),
        RegisterAggregateRecipe::Algebraic { input, .. }
            if si.value_type == SlotValueType::RetainedRow =>
        {
            AVS::RetainedRow {
                slot,
                column: input.column.clone(),
            }
        }
        RegisterAggregateRecipe::RowCount
        | RegisterAggregateRecipe::NonNullCount { .. }
        | RegisterAggregateRecipe::Algebraic { .. } => match si.value_type {
            SlotValueType::Decimal128 => AVS::RegisterD128 { slot },
            _ => AVS::Register { slot },
        },
        RegisterAggregateRecipe::Navigation(_)
        | RegisterAggregateRecipe::LeadingFirst { .. } => AVS::AccumulatorOwned,
    }
}

fn avg_value_source(slot: usize, si: &SlotInfo) -> AggregateValueSource {
    use crate::core::vm::AggregateValueSource as AVS;

    let count_slot = si.count_slot().unwrap();
    match si.value_type {
        SlotValueType::Decimal128 => {
            let target_scale = 38i8.min(si.scale + 4);
            let scale_diff = (target_scale - si.scale) as u32;
            let scale_factor = 10u32.pow(scale_diff);
            AVS::AvgDecimal128 {
                sum_slot: slot,
                count_slot,
                scale_factor,
            }
        }
        _ => AVS::Avg {
            sum_slot: slot,
            count_slot,
        },
    }
}

/// A storage key omits the read default. Shallow LAST/PREV (max depth <= 1)
/// share a Last/Prev slot; deeper history coalesces all depths for the same
/// (scope, domain, value_idx) into a single PrevBuffer sized to the max depth.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum NavigationStorage {
    First(usize),
    Last,
    PrevBuffer,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct NavigationKey {
    scope: Option<LogicalSymbolId>,
    domain: NavigationValueDomain,
    value_idx: usize,
    storage: NavigationStorage,
}

#[cfg(test)]
mod tests;