datafusion-match-recognize 0.56.1

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

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::config::MatchRecognizeConfig;
use datafusion::arrow::compute::concat_batches;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::execution::SessionStateBuilder;
use datafusion::execution::options::ArrowReadOptions;
use datafusion::physical_optimizer::optimizer::ConfigOnlyContext;
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties, collect};
use datafusion::prelude::{SessionConfig, SessionContext};

use super::optimize;
use crate::{advanced, new_match_recognize_context};

static NEXT_TEMP_ID: AtomicU64 = AtomicU64::new(0);

struct TempDataDir {
    path: PathBuf,
}

impl TempDataDir {
    fn new(prefix: &str) -> Result<Self> {
        let id = NEXT_TEMP_ID.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "mr_{prefix}_{}_{}",
            std::process::id(),
            id
        ));
        std::fs::create_dir_all(&path)?;
        Ok(Self { path })
    }

    fn file_uri(&self, name: &str) -> String {
        self.path.join(name).to_string_lossy().replace('\\', "/")
    }
}

impl Drop for TempDataDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

fn session_config(
    target_partitions: usize,
    disable_hash_grouped_ordering: bool,
) -> SessionConfig {
    let mut mr = MatchRecognizeConfig::default();
    mr.diagnostics.disable_hash_grouped_ordering = disable_hash_grouped_ordering;
    let mut config = SessionConfig::new().with_target_partitions(target_partitions);
    config.options_mut().extensions.insert(mr);
    config
}

async fn write_skewed_arrow(dir: &TempDataDir) -> Result<String> {
    let writer = SessionContext::new();
    let file = dir.file_uri("items.arrow");
    // Four rows in bucket 105 (l_orderkey % 4 in {2, 3}, l_suppkey = 5) plus
    // rows in other buckets (0, 1..10, 106) so the CSE CASE key is non-trivial.
    let copy_sql = format!(
        "COPY (
            SELECT * FROM (VALUES
                (2::BIGINT, 5::BIGINT, 1::INT, 10::INT),
                (3::BIGINT, 5::BIGINT, 2::INT, 20::INT),
                (6::BIGINT, 5::BIGINT, 3::INT, 12::INT),
                (7::BIGINT, 5::BIGINT, 4::INT, 18::INT),
                (4::BIGINT, 5::BIGINT, 1::INT, 10::INT),
                (5::BIGINT, 5::BIGINT, 1::INT, 10::INT),
                (2::BIGINT, 6::BIGINT, 1::INT, 10::INT)
            ) AS v(l_orderkey, l_suppkey, seq, qty)
        ) TO '{file}' STORED AS ARROW"
    );
    writer.sql(&copy_sql).await?.collect().await?;
    Ok(file)
}

async fn register_table(ctx: &SessionContext, table: &str, path: &str) -> Result<()> {
    ctx.register_arrow(table, path, ArrowReadOptions::default())
        .await
}

fn context_with_workaround(
    target_partitions: usize,
    disable_hash_grouped_ordering: bool,
) -> Result<SessionContext> {
    let builder = SessionStateBuilder::new()
        .with_default_features()
        .with_config(session_config(
            target_partitions,
            disable_hash_grouped_ordering,
        ));
    new_match_recognize_context(builder)
}

/// Build a context with MATCH_RECOGNIZE query planning and logical rules, but
/// WITHOUT `MatchRecognizePhysicalOptimizer`, so tests can confirm whether the
/// upstream DataFusion 56.0.0 bug (#27318) still triggers on the dependency.
fn context_without_physical_rule(target_partitions: usize) -> Result<SessionContext> {
    let mut state = SessionStateBuilder::new()
        .with_default_features()
        .with_config(session_config(target_partitions, false))
        .with_query_planner(advanced::query_planner_with_extensions(vec![]))
        .build();
    advanced::register_state(&mut state)?;
    let ctx = SessionContext::new_with_state(state);
    advanced::register_optimizer_rules(&ctx);
    Ok(ctx)
}

async fn plan_and_collect(
    ctx: &SessionContext,
    sql: &str,
) -> Result<(Arc<dyn ExecutionPlan>, RecordBatch)> {
    let plan = ctx.sql(sql).await?.create_physical_plan().await?;
    let schema = plan.schema();
    let batches = collect(Arc::clone(&plan), ctx.task_ctx()).await?;
    Ok((plan, concat_batches(&schema, &batches)?))
}

async fn run_concat(ctx: &SessionContext, sql: &str) -> Result<RecordBatch> {
    Ok(plan_and_collect(ctx, sql).await?.1)
}

const SKEWED_CTE: &str = "
WITH skewed AS (
    SELECT
        CASE
            WHEN l_orderkey % 4 = 0 THEN 0
            WHEN l_orderkey % 4 = 1 THEN 1 + (l_orderkey % 10)
            ELSE 100 + l_suppkey
        END AS skew_bucket,
        l_orderkey,
        seq,
        qty
    FROM items
)";

#[tokio::test]
async fn upstream_datafusion_56_reproducer_fails_without_repair_and_succeeds_with_it()
-> Result<()> {
    let dir = TempDataDir::new("repair_repro")?;
    let file = write_skewed_arrow(&dir).await?;

    let post_filter_sql = format!(
        "{SKEWED_CTE}
        SELECT bucket_id, start_order, match_len
        FROM skewed
        MATCH_RECOGNIZE (
            PARTITION BY skew_bucket
            ORDER BY seq, l_orderkey
            MEASURES
                FIRST(skew_bucket) AS bucket_id,
                FIRST(A.l_orderkey) AS start_order,
                COUNT(*) AS match_len
            ONE ROW PER MATCH
            PATTERN (A B)
            DEFINE
                A AS qty <= 15,
                B AS qty > 15
        )
        WHERE bucket_id = 105
        ORDER BY bucket_id, start_order"
    );

    // Without our physical optimizer rule, DataFusion 56.0.0 rejects this plan
    // with SanityCheckPlan after ProjectionPushdown (apache/datafusion#27318).
    // When DataFusion adopts #27319, this check will start succeeding and
    // `repair_requirements.rs` can be removed.
    let raw_ctx = context_without_physical_rule(2)?;
    register_table(&raw_ctx, "items", &file).await?;
    let raw_err = raw_ctx
        .sql(&post_filter_sql)
        .await?
        .create_physical_plan()
        .await
        .expect_err(
            "expected DataFusion 56.0.0 #27318 SanityCheckPlan failure without workaround; \
             if DataFusion was upgraded past #27319, remove repair_requirements.rs",
        )
        .to_string();
    assert!(
        raw_err.contains("SanityCheckPlan") && raw_err.contains("ProjectionPushdown"),
        "unexpected upstream error: {raw_err}"
    );

    // Reference query avoids single-value constant pinning via a 2-value IN list.
    let reference_sql =
        post_filter_sql.replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");

    // Verify both multi-partition and single-partition execution, and with
    // HashGroupedOrderExec enabled and disabled.
    for (partitions, disable_grouped) in [(2, false), (2, true), (1, false)] {
        let ctx = context_with_workaround(partitions, disable_grouped)?;
        register_table(&ctx, "items", &file).await?;

        let expected = run_concat(&ctx, &reference_sql).await?;
        assert_eq!(expected.num_rows(), 2);

        let (post_plan, actual_post) = plan_and_collect(&ctx, &post_filter_sql).await?;
        assert_eq!(
            post_plan.output_partitioning().partition_count(),
            1,
            "ORDER BY root must stay single-partition (partitions={partitions}, disable_grouped={disable_grouped})"
        );
        assert_eq!(
            actual_post, expected,
            "post-matcher constant filter mismatch (partitions={partitions}, disable_grouped={disable_grouped})"
        );

        // Pre-matcher CTE filter pinning the CSE partition key directly.
        let pre_filter_sql = format!(
            "{SKEWED_CTE},
            filtered AS (SELECT * FROM skewed WHERE skew_bucket = 105)
            SELECT bucket_id, start_order, match_len
            FROM filtered
            MATCH_RECOGNIZE (
                PARTITION BY skew_bucket
                ORDER BY seq, l_orderkey
                MEASURES
                    FIRST(skew_bucket) AS bucket_id,
                    FIRST(A.l_orderkey) AS start_order,
                    COUNT(*) AS match_len
                ONE ROW PER MATCH
                PATTERN (A B)
                DEFINE
                    A AS qty <= 15,
                    B AS qty > 15
            )
            ORDER BY bucket_id, start_order"
        );
        let (pre_plan, actual_pre) = plan_and_collect(&ctx, &pre_filter_sql).await?;
        assert_eq!(
            pre_plan.output_partitioning().partition_count(),
            1,
            "pre-matcher ORDER BY root must stay single-partition (partitions={partitions}, disable_grouped={disable_grouped})"
        );
        assert_eq!(
            actual_pre, expected,
            "pre-matcher constant filter mismatch (partitions={partitions}, disable_grouped={disable_grouped})"
        );
    }

    Ok(())
}

#[tokio::test]
async fn constant_cse_partition_key_variants_preserve_rows_and_root_order() -> Result<()>
{
    let dir = TempDataDir::new("repair_variants")?;
    let file = write_skewed_arrow(&dir).await?;

    for partitions in [1, 2] {
        let ctx = context_with_workaround(partitions, false)?;
        register_table(&ctx, "items", &file).await?;

        // 1. Root ORDER BY without the partition key (exercises SortPreservingMerge
        //    alignment when the matcher's repaired sort prepends skew_bucket).
        let order_without_key = format!(
            "{SKEWED_CTE}
            SELECT bucket_id, seq, l_orderkey
            FROM skewed
            MATCH_RECOGNIZE (
                PARTITION BY skew_bucket
                ORDER BY seq, l_orderkey
                MEASURES FIRST(skew_bucket) AS bucket_id
                ALL ROWS PER MATCH
                PATTERN (A B)
                DEFINE A AS qty <= 15, B AS qty > 15
            )
            WHERE bucket_id = 105
            ORDER BY seq DESC, l_orderkey DESC"
        );
        let ref_order = order_without_key
            .replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
        assert_eq!(
            run_concat(&ctx, &order_without_key).await?,
            run_concat(&ctx, &ref_order).await?,
            "ALL ROWS + root ORDER BY mismatch (partitions={partitions})"
        );

        // 2. Root ORDER BY matching inner ORDER BY (outer sort elided before
        //    ProjectionPushdown) and with LIMIT (fetch must remain single-partition).
        let elided_outer_sort = format!(
            "{SKEWED_CTE}
            SELECT bucket_id, seq, l_orderkey
            FROM skewed
            MATCH_RECOGNIZE (
                PARTITION BY skew_bucket
                ORDER BY seq, l_orderkey
                MEASURES FIRST(skew_bucket) AS bucket_id
                ALL ROWS PER MATCH
                PATTERN (A B)
                DEFINE A AS qty <= 15, B AS qty > 15
            )
            WHERE bucket_id = 105
            ORDER BY seq, l_orderkey"
        );
        let ref_elided = elided_outer_sort
            .replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
        let (elided_plan, actual_elided) =
            plan_and_collect(&ctx, &elided_outer_sort).await?;
        assert_eq!(
            elided_plan.output_partitioning().partition_count(),
            1,
            "elided outer ORDER BY must keep single-partition root (partitions={partitions})"
        );
        assert!(
            elided_plan.output_ordering().is_some(),
            "elided outer ORDER BY must preserve output ordering (partitions={partitions})"
        );
        assert_eq!(
            actual_elided,
            run_concat(&ctx, &ref_elided).await?,
            "elided outer ORDER BY rows mismatch (partitions={partitions})"
        );

        let limited_order = format!("{elided_outer_sort} LIMIT 2");
        let ref_limited = format!("{ref_elided} LIMIT 2");
        let (limited_plan, actual_limited) =
            plan_and_collect(&ctx, &limited_order).await?;
        assert_eq!(
            limited_plan.output_partitioning().partition_count(),
            1,
            "ORDER BY LIMIT must keep single-partition root (partitions={partitions})"
        );
        assert_eq!(
            actual_limited,
            run_concat(&ctx, &ref_limited).await?,
            "ORDER BY LIMIT rows mismatch (partitions={partitions})"
        );

        // 3. Multi-key PARTITION BY with one constant CSE key and one dynamic key.
        let multi_key = format!(
            "{SKEWED_CTE}
            SELECT bucket_id, parity, match_len
            FROM skewed
            MATCH_RECOGNIZE (
                PARTITION BY skew_bucket, l_orderkey % 2
                ORDER BY seq, l_orderkey
                MEASURES
                    FIRST(skew_bucket) AS bucket_id,
                    FIRST(l_orderkey % 2) AS parity,
                    COUNT(*) AS match_len
                ONE ROW PER MATCH
                PATTERN (A+)
                DEFINE A AS qty > 0
            )
            WHERE bucket_id = 105
            ORDER BY bucket_id, parity"
        );
        let ref_multi =
            multi_key.replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
        let (multi_plan, actual_multi) = plan_and_collect(&ctx, &multi_key).await?;
        assert_eq!(
            multi_plan.output_partitioning().partition_count(),
            1,
            "multi-key ORDER BY root must stay single-partition (partitions={partitions})"
        );
        assert_eq!(
            actual_multi,
            run_concat(&ctx, &ref_multi).await?,
            "multi-key PARTITION BY mismatch (partitions={partitions})"
        );

        // 4. Hidden sort key under LIMIT (Projection drops sort key before
        //    GlobalLimitExec so output_ordering() is None at the root; end_qty
        //    is 20 for start_order=2 and 18 for start_order=6, so DESC LIMIT 1
        //    only matches if the hidden sort survives repair).
        let hidden_sort_limit = format!(
            "SELECT bucket_id, end_qty FROM (
                {SKEWED_CTE}
                SELECT bucket_id, start_order, end_qty
                FROM skewed
                MATCH_RECOGNIZE (
                    PARTITION BY skew_bucket
                    ORDER BY seq, l_orderkey
                    MEASURES
                        FIRST(skew_bucket) AS bucket_id,
                        FIRST(A.l_orderkey) AS start_order,
                        LAST(B.qty) AS end_qty
                    ONE ROW PER MATCH
                    PATTERN (A B)
                    DEFINE A AS qty <= 15, B AS qty > 15
                )
                WHERE bucket_id = 105
                ORDER BY start_order DESC
            ) LIMIT 1"
        );
        let ref_hidden_sort = hidden_sort_limit
            .replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
        let (hidden_plan, actual_hidden) =
            plan_and_collect(&ctx, &hidden_sort_limit).await?;
        assert_eq!(
            hidden_plan.output_partitioning().partition_count(),
            1,
            "hidden-sort LIMIT root must stay single-partition (partitions={partitions})"
        );
        assert_eq!(actual_hidden.num_rows(), 1);
        assert_eq!(
            actual_hidden,
            run_concat(&ctx, &ref_hidden_sort).await?,
            "hidden-sort LIMIT mismatch (partitions={partitions})"
        );

        // 5. PARTITION BY CSE key with no inner ORDER BY clause.
        let no_inner_order = format!(
            "{SKEWED_CTE}
            SELECT bucket_id, total_rows
            FROM skewed
            MATCH_RECOGNIZE (
                PARTITION BY skew_bucket
                MEASURES
                    FIRST(skew_bucket) AS bucket_id,
                    COUNT(*) AS total_rows
                ONE ROW PER MATCH
                PATTERN (A+)
                DEFINE A AS qty > 0
            )
            WHERE bucket_id = 105"
        );
        let ref_no_inner = no_inner_order
            .replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
        assert_eq!(
            run_concat(&ctx, &no_inner_order).await?,
            run_concat(&ctx, &ref_no_inner).await?,
            "no-ORDER-BY matcher mismatch (partitions={partitions})"
        );
    }

    Ok(())
}

#[tokio::test]
async fn ordered_aggregate_over_constant_cse_matcher_preserves_requirements() -> Result<()>
{
    use datafusion::common::test_util::batches_to_sort_string;
    use datafusion::common::tree_node::TreeNode;
    use datafusion::physical_expr::Distribution;
    use datafusion::physical_expr_common::sort_expr::OrderingRequirements;
    use datafusion::physical_optimizer::sanity_checker::{
        check_plan_tree_sanity, input_requirements_hold,
    };
    use datafusion::physical_plan::aggregates::AggregateExec;

    let dir = TempDataDir::new("repair_ordered_aggregate")?;
    let file = write_skewed_arrow(&dir).await?;
    let sql = format!(
        "{SKEWED_CTE},
        filtered AS (
            SELECT skew_bucket, (seq - 1) / 2 AS grp, l_orderkey, seq, qty
            FROM skewed
            WHERE skew_bucket = 105
        )
        SELECT skew_bucket, grp, ARRAY_AGG(end_qty ORDER BY end_qty) AS quantities
        FROM filtered
        MATCH_RECOGNIZE (
            PARTITION BY skew_bucket, grp ORDER BY seq, l_orderkey
            MEASURES LAST(B.qty) AS end_qty
            ONE ROW PER MATCH PATTERN (A B)
            DEFINE A AS qty <= 15, B AS qty > 15
        )
        GROUP BY skew_bucket, grp"
    );
    // Avoid the upstream constant-CSE loss in the reference and leave our
    // physical optimizer uninstalled. -1 is absent from the source data.
    let reference_sql =
        sql.replace("WHERE skew_bucket = 105", "WHERE skew_bucket IN (105, -1)");
    let reference_ctx = context_without_physical_rule(2)?;
    register_table(&reference_ctx, "items", &file).await?;
    let expected = run_concat(&reference_ctx, &reference_sql).await?;
    let raw_err = reference_ctx
        .sql(&sql)
        .await?
        .create_physical_plan()
        .await
        .expect_err("query must trigger upstream constant-CSE requirement failure")
        .to_string();
    assert!(
        raw_err.contains("SanityCheckPlan"),
        "unexpected upstream error: {raw_err}"
    );

    for disable_grouped in [false, true] {
        let ctx = context_with_workaround(2, disable_grouped)?;
        register_table(&ctx, "items", &file).await?;
        let (plan, actual) = plan_and_collect(&ctx, &sql).await?;
        assert!(input_requirements_hold(&plan));
        check_plan_tree_sanity(&plan, &ctx.state().config_options().optimizer)?;
        assert!(
            plan.exists(|node| {
                Ok(node.is::<AggregateExec>()
                    && node.maintains_input_order()[0]
                    && matches!(
                        node.required_input_ordering()[0],
                        Some(OrderingRequirements::Soft(_))
                    )
                    && matches!(
                        node.input_distribution_requirements().child_distribution(0),
                        Some(Distribution::KeyPartitioned(_))
                    ))
            })?,
            "regression must exercise a clustered aggregate with Soft ordering and KeyPartitioned input (disable_grouped={disable_grouped}):\n{}",
            datafusion::physical_plan::displayable(plan.as_ref()).indent(true)
        );
        // Do not add a root ORDER BY to the SQL: that would cause requirement
        // repair to start above the aggregate and hide the detached-ancestor bug.
        assert_eq!(actual.schema(), expected.schema());
        assert_eq!(
            batches_to_sort_string(std::slice::from_ref(&actual)),
            batches_to_sort_string(std::slice::from_ref(&expected)),
            "disable_grouped={disable_grouped}"
        );
        datafusion::common::assert_batches_sorted_eq!(
            [
                "+-------------+-----+------------+",
                "| skew_bucket | grp | quantities |",
                "+-------------+-----+------------+",
                "| 105         | 0   | [20]       |",
                "| 105         | 1   | [18]       |",
                "+-------------+-----+------------+",
            ],
            &[actual]
        );
    }
    Ok(())
}

#[tokio::test]
async fn valid_and_non_matcher_plans_are_returned_unchanged() -> Result<()> {
    let ctx = crate::optimizer::input_constants::tests::context()?;
    let state = ctx.state();
    let config = state.config_options();
    let optimizer_ctx = ConfigOnlyContext::new(config);

    let plain: Arc<dyn ExecutionPlan> = ctx
        .sql("SELECT p, seq FROM ticks ORDER BY p, seq")
        .await?
        .create_physical_plan()
        .await?;
    let after_plain = optimize(Arc::clone(&plain), &optimizer_ctx)?;
    assert!(Arc::ptr_eq(&plain, &after_plain));

    let valid_matcher: Arc<dyn ExecutionPlan> = ctx
        .sql(
            "SELECT k, n FROM ticks
             MATCH_RECOGNIZE (
                 PARTITION BY p ORDER BY seq
                 MEASURES FIRST(p) AS k, COUNT(*) AS n
                 ONE ROW PER MATCH
                 PATTERN (A+)
                 DEFINE A AS v > 0
             )",
        )
        .await?
        .create_physical_plan()
        .await?;
    let after_valid = optimize(Arc::clone(&valid_matcher), &optimizer_ctx)?;
    assert!(Arc::ptr_eq(&valid_matcher, &after_valid));

    Ok(())
}

#[tokio::test]
async fn repair_preserves_hidden_descending_order_without_fetch() -> Result<()> {
    use datafusion::arrow::array::Int32Array;

    let dir = TempDataDir::new("repair_hidden_order")?;
    let file = write_skewed_arrow(&dir).await?;
    for partitions in [2, 4] {
        let ctx = context_with_workaround(partitions, true)?;
        register_table(&ctx, "items", &file).await?;
        for offset in [false, true] {
            let suffix = if offset { " OFFSET 1" } else { "" };
            let sql = format!(
                "{SKEWED_CTE}
                SELECT bucket_id, end_qty FROM (
                    SELECT bucket_id, start_order, end_qty
                    FROM skewed
                    MATCH_RECOGNIZE (
                        PARTITION BY skew_bucket ORDER BY seq, l_orderkey
                        MEASURES FIRST(skew_bucket) AS bucket_id,
                            FIRST(A.l_orderkey) AS start_order,
                            LAST(B.qty) AS end_qty
                        ONE ROW PER MATCH PATTERN (A B)
                        DEFINE A AS qty <= 15, B AS qty > 15
                    )
                    WHERE bucket_id = 105
                )
                ORDER BY start_order DESC{suffix}"
            );
            let reference =
                sql.replace("WHERE bucket_id = 105", "WHERE bucket_id IN (105, -1)");
            let (plan, actual) = plan_and_collect(&ctx, &sql).await?;
            assert_eq!(plan.output_partitioning().partition_count(), 1);
            assert!(plan.output_ordering().is_none(), "sort key must be hidden");
            assert_eq!(actual, run_concat(&ctx, &reference).await?);
            let quantities = actual
                .column(1)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap();
            let expected: &[i32] = if offset { &[20] } else { &[18, 20] };
            assert_eq!(
                quantities.values().as_ref(),
                expected,
                "partitions={partitions}, offset={offset}"
            );
        }
    }
    Ok(())
}