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
// 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.

//! Small borrowed values. Numeric errors occur only when an instruction is reached.
use super::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Value<'a> {
    Null,
    Bool(bool),
    I64(i64),
    U64(u64),
    F32(f32),
    F64(f64),
    Decimal(i128, u8, i8),
    Str(&'a str),
}
impl<'a> Value<'a> {
    #[inline]
    pub(super) fn truth(v: VmTriBool) -> Self {
        match v {
            VmTriBool::True => Self::Bool(true),
            VmTriBool::False => Self::Bool(false),
            VmTriBool::Unknown => Self::Null,
        }
    }
    #[inline]
    pub(super) fn boolean(self) -> Result<VmTriBool, VmError> {
        match self {
            Self::Null => Ok(VmTriBool::Unknown),
            Self::Bool(true) => Ok(VmTriBool::True),
            Self::Bool(false) => Ok(VmTriBool::False),
            _ => Err(VmError::TypeMismatch),
        }
    }
    pub(super) fn owned<'b>(self) -> Result<Value<'b>, VmError> {
        Ok(match self {
            Self::Null => Value::Null,
            Self::Bool(v) => Value::Bool(v),
            Self::I64(v) => Value::I64(v),
            Self::U64(v) => Value::U64(v),
            Self::F32(v) => Value::F32(v),
            Self::F64(v) => Value::F64(v),
            Self::Decimal(v, p, s) => Value::Decimal(v, p, s),
            Self::Str(_) => return Err(VmError::TypeMismatch),
        })
    }
    pub(super) fn scalar(v: &'a ScalarValue) -> Result<Self, VmError> {
        use ScalarValue as S;
        if v.is_null() {
            return Ok(Self::Null);
        }
        Ok(match v {
            S::Boolean(Some(v)) => Self::Bool(*v),
            S::Int8(Some(v)) => Self::I64((*v).into()),
            S::Int16(Some(v)) => Self::I64((*v).into()),
            S::Int32(Some(v))
            | S::Date32(Some(v))
            | S::Time32Second(Some(v))
            | S::Time32Millisecond(Some(v)) => Self::I64((*v).into()),
            S::Int64(Some(v))
            | S::Date64(Some(v))
            | S::Time64Microsecond(Some(v))
            | S::Time64Nanosecond(Some(v))
            | S::DurationSecond(Some(v))
            | S::DurationMillisecond(Some(v))
            | S::DurationMicrosecond(Some(v))
            | S::DurationNanosecond(Some(v))
            | S::TimestampSecond(Some(v), _)
            | S::TimestampMillisecond(Some(v), _)
            | S::TimestampMicrosecond(Some(v), _)
            | S::TimestampNanosecond(Some(v), _) => Self::I64(*v),
            S::UInt8(Some(v)) => Self::U64((*v).into()),
            S::UInt16(Some(v)) => Self::U64((*v).into()),
            S::UInt32(Some(v)) => Self::U64((*v).into()),
            S::UInt64(Some(v)) => Self::U64(*v),
            S::Float32(Some(v)) => Self::F32(*v),
            S::Float64(Some(v)) => Self::F64(*v),
            S::Decimal128(Some(v), p, s) => Self::Decimal(*v, *p, *s),
            S::Utf8(Some(v)) | S::LargeUtf8(Some(v)) | S::Utf8View(Some(v)) => {
                Self::Str(v)
            }
            _ => Self::I64(
                crate::core::vm::temporal_scalar_to_bits(v)
                    .ok_or(VmError::TypeMismatch)? as i64,
            ),
        })
    }
    #[inline]
    pub(super) fn word(word: u64, ty: VmScalarType) -> Result<Self, VmError> {
        use VmScalarType as T;
        Ok(match ty {
            T::Bool => Self::Bool(word != 0),
            T::UInt8 => Self::U64(word as u8 as u64),
            T::UInt16 => Self::U64(word as u16 as u64),
            T::UInt32 => Self::U64(word as u32 as u64),
            T::UInt64 => Self::U64(word),
            T::Float32 => Self::F32(f32::from_bits(word as u32)),
            T::Float64 => Self::F64(f64::from_bits(word)),
            T::Int8 => Self::I64(word as i8 as i64),
            T::Int16 => Self::I64(word as i16 as i64),
            T::Int32 | T::Date32 | T::Time32(_) => Self::I64(word as i32 as i64),
            T::Int64 | T::MetadataI64 => Self::I64(word as i64),
            ty if ty.is_temporal() => Self::I64(word as i64),
            _ => return Err(VmError::TypeMismatch),
        })
    }
    // Narrowing casts validate coefficient precision; decimal arithmetic does not.
    pub(super) fn decimal(v: i128, p: u8, s: i8) -> Result<Self, VmError> {
        let bound = 10_i128.checked_pow(p.into()).ok_or(VmError::Overflow)?;
        if v <= -bound || v >= bound {
            return Err(VmError::Overflow);
        }
        Ok(Self::Decimal(v, p, s))
    }
    #[inline]
    pub(super) fn cast(self, target: VmScalarType) -> Result<Self, VmError> {
        use VmScalarType as T;
        Ok(match (self, target) {
            (Self::Null, _) => Self::Null,
            (Self::I64(v), T::Float64) => Self::F64(v as f64),
            (Self::U64(v), T::Float64) => Self::F64(v as f64),
            (Self::F32(v), T::Float32) => Self::F32(v),
            (Self::F32(v), T::Float64) => Self::F64(f64::from(v)),
            (Self::Decimal(v, _, s), T::Float64) => Self::F64(f64::from_bits(
                crate::execution::storage::bound_columns::decode_decimal128_to_f64_bits(
                    v, s,
                ),
            )),
            (Self::F64(v), T::Decimal128 { precision, scale }) => {
                let raw = datafusion::arrow::compute::float_to_decimal::<
                    datafusion::arrow::datatypes::Decimal128Type,
                >(v, precision, scale)
                .map_err(VmError::from)?;
                Self::Decimal(raw, precision, scale)
            }
            (Self::Decimal(v, _, s), T::Decimal128 { precision, scale }) => {
                let power = u32::try_from(i16::from(scale) - i16::from(s))
                    .map_err(|_| VmError::TypeMismatch)?;
                // Zero remains zero even when the scale multiplier exceeds i128.
                let v = if v == 0 {
                    0
                } else {
                    v.checked_mul(10_i128.checked_pow(power).ok_or(VmError::Overflow)?)
                        .ok_or(VmError::Overflow)?
                };
                Self::decimal(v, precision, scale)?
            }
            (Self::F32(_), _) | (_, T::Float32) => return Err(VmError::TypeMismatch),
            (v, _) => v,
        })
    }
    #[inline]
    pub(super) fn unary(self, op: VmUnaryOp, ty: VmScalarType) -> Result<Self, VmError> {
        Ok(match (self, op) {
            (Self::Null | Self::Bool(false), VmUnaryOp::IsTrue) => Self::Bool(false),
            (Self::Bool(true), VmUnaryOp::IsTrue) => Self::Bool(true),
            (Self::Null, _) => Self::Null,
            (Self::F64(v), VmUnaryOp::Abs) => Self::F64(v.abs()),
            (Self::F64(v), _) => Self::F64(-v),
            (Self::Decimal(v, p, s), VmUnaryOp::Abs) => {
                // Pinned DataFusion ABS wraps even for Decimal128's i128::MIN.
                Self::Decimal(v.wrapping_abs(), p, s)
            }
            (Self::Decimal(v, p, s), _) => {
                Self::Decimal(v.checked_neg().ok_or(VmError::Overflow)?, p, s)
            }
            (Self::I64(v), VmUnaryOp::Abs) => {
                let n = v.checked_abs().ok_or(VmError::Overflow)?;
                Self::I64(check_signed_width(n, ty)?)
            }
            (Self::I64(v), _) => {
                // DataFusion's array NegativeExpr wraps at the declared width;
                // literal-only expressions use ScalarValue's checked negation.
                let n = if op == VmUnaryOp::CheckedNeg {
                    v.checked_neg().ok_or(VmError::Overflow)?
                } else {
                    v.wrapping_neg()
                };
                let narrowed = match ty {
                    VmScalarType::Int8 => n as i8 as i64,
                    VmScalarType::Int16 => n as i16 as i64,
                    VmScalarType::Int32 => n as i32 as i64,
                    _ => n,
                };
                if op == VmUnaryOp::CheckedNeg && narrowed != n {
                    return Err(VmError::Overflow);
                }
                Self::I64(narrowed)
            }
            _ => return Err(VmError::TypeMismatch),
        })
    }
    #[inline]
    fn compare_order(self, rhs: Self) -> Result<std::cmp::Ordering, VmError> {
        Ok(match (self, rhs) {
            (Self::Bool(a), Self::Bool(b)) => a.cmp(&b),
            (Self::I64(a), Self::I64(b)) => a.cmp(&b),
            (Self::U64(a), Self::U64(b)) => a.cmp(&b),
            (Self::Decimal(a, _, s), Self::Decimal(b, _, t)) if s == t => a.cmp(&b),
            (Self::Str(a), Self::Str(b)) => a.cmp(b),
            // Pinned DataFusion uses totalOrder for NaNs, with signed zeros equal.
            (Self::F32(a), Self::F32(b)) => {
                let a = if a.to_bits() << 1 == 0 { 0.0 } else { a };
                let b = if b.to_bits() << 1 == 0 { 0.0 } else { b };
                a.total_cmp(&b)
            }
            (Self::F64(a), Self::F64(b)) => {
                let a = if a.to_bits() << 1 == 0 { 0.0 } else { a };
                let b = if b.to_bits() << 1 == 0 { 0.0 } else { b };
                a.total_cmp(&b)
            }
            _ => return Err(VmError::TypeMismatch),
        })
    }
    #[inline]
    pub(super) fn binary(
        self,
        op: VmBinaryOp,
        ty: VmScalarType,
        rhs: Self,
    ) -> Result<Self, VmError> {
        use VmBinaryOp as O;
        if op == O::And {
            return Ok(Self::truth(self.boolean()?.and(rhs.boolean()?)));
        }
        if op == O::Or {
            return Ok(Self::truth(self.boolean()?.or(rhs.boolean()?)));
        }
        if matches!(op, O::IsDistinctFrom | O::IsNotDistinctFrom) {
            let distinct = match (self, rhs) {
                (Self::Null, Self::Null) => false,
                (Self::Null, _) | (_, Self::Null) => true,
                (lhs, rhs) => !lhs.compare_order(rhs)?.is_eq(),
            };
            return Ok(Self::Bool(if op == O::IsDistinctFrom {
                distinct
            } else {
                !distinct
            }));
        }
        if matches!(self, Self::Null) || matches!(rhs, Self::Null) {
            return Ok(Self::Null);
        }
        if matches!(op, O::Eq | O::Ne | O::Lt | O::Le | O::Gt | O::Ge) {
            let order = self.compare_order(rhs)?;
            return Ok(Self::Bool(match op {
                O::Eq => order.is_eq(),
                O::Ne => !order.is_eq(),
                O::Lt => order.is_lt(),
                O::Le => !order.is_gt(),
                O::Gt => order.is_gt(),
                O::Ge => !order.is_lt(),
                _ => unreachable!(),
            }));
        }
        if matches!(op, O::AddInterval | O::SubInterval) {
            let (Self::I64(a), Self::I64(b)) = (self, rhs) else {
                return Err(VmError::TypeMismatch);
            };
            return eval_temporal_interval(a, b, op, ty).map(Self::I64);
        }
        macro_rules! checked {
            ($a:expr, $b:expr) => {
                match op {
                    O::Add => $a.checked_add($b),
                    O::Sub => $a.checked_sub($b),
                    O::Mul => $a.checked_mul($b),
                    _ => return Err(VmError::TypeMismatch),
                }
                .ok_or(VmError::Overflow)?
            };
        }
        macro_rules! wrapping {
            ($a:expr, $b:expr) => {
                match op {
                    O::Add => $a.wrapping_add($b),
                    O::Sub => $a.wrapping_sub($b),
                    O::Mul => $a.wrapping_mul($b),
                    _ => return Err(VmError::TypeMismatch),
                }
            };
        }
        Ok(match (self, rhs) {
            (Self::I64(a), Self::I64(b)) => Self::I64(match ty {
                // Pinned DataFusion BinaryExpr defaults to `fail_on_overflow = false`
                // and wraps integers at their declared width via Arrow `*_wrapping`
                // kernels; temporal (Duration/Timestamp) arithmetic remains checked.
                VmScalarType::Int8 => i64::from(wrapping!(a as i8, b as i8)),
                VmScalarType::Int16 => i64::from(wrapping!(a as i16, b as i16)),
                VmScalarType::Int32 => i64::from(wrapping!(a as i32, b as i32)),
                VmScalarType::Int64 | VmScalarType::MetadataI64 => wrapping!(a, b),
                _ => check_signed_width(checked!(a, b), ty)?,
            }),
            (Self::U64(a), Self::U64(b)) => Self::U64(match ty {
                VmScalarType::UInt8 => u64::from(wrapping!(a as u8, b as u8)),
                VmScalarType::UInt16 => u64::from(wrapping!(a as u16, b as u16)),
                VmScalarType::UInt32 => u64::from(wrapping!(a as u32, b as u32)),
                VmScalarType::UInt64 => wrapping!(a, b),
                _ => return Err(VmError::TypeMismatch),
            }),
            (Self::F64(a), Self::F64(b)) => Self::F64(match op {
                O::Add => a + b,
                O::Sub => a - b,
                O::Mul => a * b,
                _ => return Err(VmError::TypeMismatch),
            }),
            (Self::Decimal(a, _, s), Self::Decimal(b, _, t)) => {
                let VmScalarType::Decimal128 { precision, scale } = ty else {
                    return Err(VmError::TypeMismatch);
                };
                let (lhs, rhs) = if op == O::Mul {
                    if i16::from(scale) != i16::from(s) + i16::from(t) {
                        return Err(VmError::TypeMismatch);
                    }
                    (a, b)
                } else {
                    if scale != s.max(t) {
                        return Err(VmError::TypeMismatch);
                    }
                    (rescale_decimal(a, s, scale)?, rescale_decimal(b, t, scale)?)
                };
                // Arrow checks native overflow, but only attaches precision metadata.
                Self::Decimal(checked!(lhs, rhs), precision, scale)
            }
            _ => return Err(VmError::TypeMismatch),
        })
    }
}

fn rescale_decimal(value: i128, from_scale: i8, to_scale: i8) -> Result<i128, VmError> {
    if from_scale == to_scale {
        return Ok(value);
    }
    let diff = u32::try_from(i16::from(to_scale) - i16::from(from_scale))
        .map_err(|_| VmError::TypeMismatch)?;
    let factor = 10_i128.checked_pow(diff).ok_or(VmError::Overflow)?;
    value.checked_mul(factor).ok_or(VmError::Overflow)
}

fn check_signed_width(value: i64, ty: VmScalarType) -> Result<i64, VmError> {
    match ty {
        VmScalarType::Int8 => i8::try_from(value).map(i64::from),
        VmScalarType::Int16 => i16::try_from(value).map(i64::from),
        VmScalarType::Int32 | VmScalarType::Date32 => i32::try_from(value).map(i64::from),
        _ => Ok(value),
    }
    .map_err(|_| VmError::Overflow)
}

/// Strictly inside chrono's +/-262,000-year `NaiveDate` calendar bounds; dates
/// beyond this threshold (and non-midnight `Date64` values) delegate directly
/// to Arrow's calendar helpers on the cold path. Overflows return
/// `VmError::Overflow` so `transition_eval` replays the bound `PhysicalExpr`
/// and preserves Arrow's exact error message.
const SAFE_CALENDAR_DAYS: i64 = 90_000_000;

#[inline]
fn eval_temporal_interval(
    a: i64,
    b: i64,
    op: VmBinaryOp,
    ty: VmScalarType,
) -> Result<i64, VmError> {
    use datafusion::arrow::temporal_conversions::{
        MICROSECONDS_IN_DAY, MILLISECONDS_IN_DAY, SECONDS_IN_DAY,
    };

    let res = match op {
        VmBinaryOp::AddInterval => a.checked_add(b),
        VmBinaryOp::SubInterval => a.checked_sub(b),
        _ => return Err(VmError::TypeMismatch),
    }
    .ok_or(VmError::Overflow)?;

    let safe_limit = match ty {
        VmScalarType::Date32 => SAFE_CALENDAR_DAYS,
        VmScalarType::Date64 => {
            let safe = SAFE_CALENDAR_DAYS * MILLISECONDS_IN_DAY;
            if a % MILLISECONDS_IN_DAY == 0
                && (-safe..=safe).contains(&a)
                && (-safe..=safe).contains(&res)
            {
                return Ok(res);
            }
            return eval_temporal_interval_cold(a, b, res, op, ty);
        }
        VmScalarType::Timestamp {
            unit: TimeUnit::Second,
            timezone_aware: false,
        } => SAFE_CALENDAR_DAYS * SECONDS_IN_DAY,
        VmScalarType::Timestamp {
            unit: TimeUnit::Millisecond,
            timezone_aware: false,
        } => SAFE_CALENDAR_DAYS * MILLISECONDS_IN_DAY,
        VmScalarType::Timestamp {
            unit: TimeUnit::Microsecond,
            timezone_aware: false,
        } => SAFE_CALENDAR_DAYS * MICROSECONDS_IN_DAY,
        VmScalarType::Timestamp {
            unit: TimeUnit::Nanosecond,
            timezone_aware: false,
        } => return Ok(res),
        _ => return Err(VmError::TypeMismatch),
    };

    if (-safe_limit..=safe_limit).contains(&a)
        && (-safe_limit..=safe_limit).contains(&res)
    {
        return Ok(res);
    }
    eval_temporal_interval_cold(a, b, res, op, ty)
}

#[cold]
fn eval_temporal_interval_cold(
    a: i64,
    b: i64,
    res: i64,
    op: VmBinaryOp,
    ty: VmScalarType,
) -> Result<i64, VmError> {
    use datafusion::arrow::datatypes::{Date32Type, Date64Type, IntervalDayTime};
    use datafusion::arrow::temporal_conversions::{
        MILLISECONDS_IN_DAY, timestamp_ms_to_datetime, timestamp_s_to_datetime,
        timestamp_us_to_datetime,
    };

    match ty {
        VmScalarType::Date32 => {
            let valid = |d: i64| {
                i32::try_from(d)
                    .ok()
                    .and_then(Date32Type::to_naive_date_opt)
                    .is_some()
            };
            (valid(a) && valid(res))
                .then_some(res)
                .ok_or(VmError::Overflow)
        }
        VmScalarType::Date64 => {
            let days =
                i32::try_from(b / MILLISECONDS_IN_DAY).map_err(|_| VmError::Overflow)?;
            let iv = IntervalDayTime::new(days, 0);
            match op {
                VmBinaryOp::AddInterval => Date64Type::add_day_time_opt(a, iv),
                VmBinaryOp::SubInterval => Date64Type::subtract_day_time_opt(a, iv),
                _ => None,
            }
            .ok_or(VmError::Overflow)
        }
        VmScalarType::Timestamp {
            unit: TimeUnit::Second,
            timezone_aware: false,
        } => (timestamp_s_to_datetime(a).is_some()
            && timestamp_s_to_datetime(res).is_some())
        .then_some(res)
        .ok_or(VmError::Overflow),
        VmScalarType::Timestamp {
            unit: TimeUnit::Millisecond,
            timezone_aware: false,
        } => (timestamp_ms_to_datetime(a).is_some()
            && timestamp_ms_to_datetime(res).is_some())
        .then_some(res)
        .ok_or(VmError::Overflow),
        VmScalarType::Timestamp {
            unit: TimeUnit::Microsecond,
            timezone_aware: false,
        } => (timestamp_us_to_datetime(a).is_some()
            && timestamp_us_to_datetime(res).is_some())
        .then_some(res)
        .ok_or(VmError::Overflow),
        _ => Err(VmError::TypeMismatch),
    }
}