File size: 33,055 Bytes
5a9e79d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
diff --git a/datafusion/core/tests/lolbench_aug.rs b/datafusion/core/tests/lolbench_aug.rs
new file mode 100644
index 0000000..c665a88
--- /dev/null
+++ b/datafusion/core/tests/lolbench_aug.rs
@@ -0,0 +1,718 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Augmented suite (lolbench-aug). The requirement keeps literal values
+//! working as plain scalars everywhere (the optional metadata is additive),
+//! so every literal-producing and literal-consuming surface must keep its
+//! observable behavior: SQL constant folding, scalar subqueries, grouping,
+//! projections, unparsing, typed `lit` construction, table functions and
+//! partition pruning. All scenarios run through the public SessionContext /
+//! DataFrame / SQL surface.
+
+use std::sync::Arc;
+
+use arrow::array::{Int32Array, StringArray};
+use arrow::datatypes::{DataType, Field, Schema};
+use arrow::record_batch::RecordBatch;
+use datafusion::assert_batches_eq;
+use datafusion::error::Result;
+use datafusion::prelude::*;
+use datafusion::logical_expr::lit_with_metadata;
+
+/// The requirement makes literal expressions carry an optional metadata slot;
+/// the public `Expr::Literal` variant therefore has the (value, metadata)
+/// shape. Constructing it with an empty slot pins that public shape — and
+/// makes every test in this binary compile-flip at pre-state, exactly like
+/// the original suite's updated test files.
+fn plain_literal_expr(v: i64) -> Expr {
+    Expr::Literal(datafusion::scalar::ScalarValue::Int64(Some(v)), None)
+}
+
+async fn ctx_with_table() -> Result<SessionContext> {
+    let ctx = SessionContext::new();
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("k", DataType::Int32, false),
+        Field::new("v", DataType::Int32, false),
+        Field::new("s", DataType::Utf8, false),
+    ]));
+    let batch = RecordBatch::try_new(
+        schema.clone(),
+        vec![
+            Arc::new(Int32Array::from(vec![1, 1, 2])),
+            Arc::new(Int32Array::from(vec![10, 20, 30])),
+            Arc::new(StringArray::from(vec!["prefix_a", "prefix_b", "other"])),
+        ],
+    )?;
+    ctx.register_batch("t1", batch)?;
+    let schema2 = Arc::new(Schema::new(vec![
+        Field::new("k", DataType::Int32, false),
+        Field::new("y", DataType::Int32, false),
+    ]));
+    let batch2 = RecordBatch::try_new(
+        schema2.clone(),
+        vec![
+            Arc::new(Int32Array::from(vec![1, 2])),
+            Arc::new(Int32Array::from(vec![100, 200])),
+        ],
+    )?;
+    ctx.register_batch("t2", batch2)?;
+    Ok(ctx)
+}
+
+async fn sql_rows(ctx: &SessionContext, q: &str) -> Result<Vec<RecordBatch>> {
+    // Literal-shape guard (see plain_literal_expr): lit(v) must produce the
+    // same expression as the public two-slot literal with an empty slot.
+    assert_eq!(plain_literal_expr(7), lit(7i64));
+    ctx.sql(q).await?.collect().await
+}
+
+#[tokio::test]
+async fn aug_string_function_literal_folding() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let batches = sql_rows(
+        &ctx,
+        "SELECT concat('a', '', 'b') AS c1, \
+                concat_ws(',', 'x', NULL, 'y') AS c2, \
+                concat('p:', s) AS c3, \
+                starts_with(s, 'prefix_') AS c4 \
+         FROM t1 ORDER BY v LIMIT 1",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+----+-----+------------+------+",
+            "| c1 | c2  | c3         | c4   |",
+            "+----+-----+------------+------+",
+            "| ab | x,y | p:prefix_a | true |",
+            "+----+-----+------------+------+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_math_datetime_and_cast_folding() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let batches = sql_rows(
+        &ctx,
+        "SELECT power(2, 10) AS p, \
+                log(2, 8) AS l, \
+                arrow_cast('41', 'Int32') + 1 AS ac, \
+                substring('hello world', 7, 5) AS sub, \
+                current_date() = current_date() AS cd, \
+                current_time() = current_time() AS ct",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+------+-----+----+-------+------+------+",
+            "| p    | l   | ac | sub   | cd   | ct   |",
+            "+------+-----+----+-------+------+------+",
+            "| 1024 | 3.0 | 42 | world | true | true |",
+            "+------+-----+----+-------+------+------+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_scalar_subqueries_decorrelate() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    // Correlated scalar subquery in WHERE (decorrelated to a join).
+    let correlated = sql_rows(
+        &ctx,
+        "SELECT k, v FROM t1 \
+         WHERE v < (SELECT max(y) FROM t2 WHERE t2.k = t1.k) \
+         ORDER BY v",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+---+----+",
+            "| k | v  |",
+            "+---+----+",
+            "| 1 | 10 |",
+            "| 1 | 20 |",
+            "| 2 | 30 |",
+            "+---+----+",
+        ],
+        &correlated
+    );
+    // Uncorrelated scalar subquery in the projection.
+    let uncorrelated = sql_rows(
+        &ctx,
+        "SELECT v, (SELECT max(y) FROM t2) AS gmax FROM t1 ORDER BY v LIMIT 1",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+----+------+",
+            "| v  | gmax |",
+            "+----+------+",
+            "| 10 | 200  |",
+            "+----+------+",
+        ],
+        &uncorrelated
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_grouping_sets_and_grouping_function() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let batches = sql_rows(
+        &ctx,
+        "SELECT k, grouping(k) AS g, count(*) AS c \
+         FROM t1 GROUP BY GROUPING SETS ((k), ()) \
+         ORDER BY g, k NULLS LAST",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+---+---+---+",
+            "| k | g | c |",
+            "+---+---+---+",
+            "| 1 | 0 | 2 |",
+            "| 2 | 0 | 1 |",
+            "|   | 1 | 3 |",
+            "+---+---+---+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_plan_eliminations_with_constant_predicates() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    // eliminate_filter (WHERE true / WHERE false), eliminate_group_by_constant,
+    // optimize_projections over a constant-rich projection.
+    let all = sql_rows(&ctx, "SELECT v FROM t1 WHERE true ORDER BY v").await?;
+    assert_eq!(all[0].num_rows(), 3);
+    let none = sql_rows(&ctx, "SELECT v FROM t1 WHERE 1 = 0").await?;
+    assert!(none.is_empty() || none.iter().all(|b| b.num_rows() == 0));
+    let grouped = sql_rows(
+        &ctx,
+        "SELECT 'const' AS tag, k, sum(v) AS sv FROM t1 GROUP BY 'const', k ORDER BY k",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+-------+---+----+",
+            "| tag   | k | sv |",
+            "+-------+---+----+",
+            "| const | 1 | 30 |",
+            "| const | 2 | 30 |",
+            "+-------+---+----+",
+        ],
+        &grouped
+    );
+    let pruned = sql_rows(
+        &ctx,
+        "SELECT a + 1 AS b FROM (SELECT v AS a, k AS unused, 99 AS dead FROM t1) ORDER BY b LIMIT 1",
+    )
+    .await?;
+    assert_batches_eq!(
+        ["+----+", "| b  |", "+----+", "| 11 |", "+----+",],
+        &pruned
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_boolean_inlist_between_and_case_simplification() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let batches = sql_rows(
+        &ctx,
+        "SELECT v FROM t1 \
+         WHERE v IN (10, 20, 30, 10) \
+           AND v BETWEEN 0 AND 100 \
+           AND (true OR k = 5) \
+           AND CASE WHEN 1 = 1 THEN true ELSE false END \
+           AND s ~ '^prefix_a$' IS NOT NULL \
+           AND coalesce(NULL, true) \
+         ORDER BY v",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+----+", "| v  |", "+----+", "| 10 |", "| 20 |", "| 30 |", "+----+",
+        ],
+        &batches
+    );
+    // guarantees: a second predicate already implied by the first.
+    let g = sql_rows(&ctx, "SELECT v FROM t1 WHERE v > 5 AND v > 5 AND v >= 10 ORDER BY v LIMIT 1").await?;
+    assert_eq!(g[0].num_rows(), 1);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_typed_literals_through_dataframe_api() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let df = ctx.table("t1").await?;
+    let projected = df
+        .select(vec![
+            lit(1i8).alias("c_i8"),
+            lit(2i16).alias("c_i16"),
+            lit(3i32).alias("c_i32"),
+            lit(4i64).alias("c_i64"),
+            lit(5u8).alias("c_u8"),
+            lit(6u16).alias("c_u16"),
+            lit(7u32).alias("c_u32"),
+            lit(8u64).alias("c_u64"),
+            lit(1.5f32).alias("c_f32"),
+            lit(2.5f64).alias("c_f64"),
+            lit("str").alias("c_str"),
+            lit(String::from("string")).alias("c_string"),
+            lit(true).alias("c_bool"),
+            lit(Vec::<u8>::from([1u8, 2u8])).alias("c_bin"),
+        ])?
+        .limit(0, Some(1))?;
+    // expr_schema: literal types and nullability flow into the schema.
+    let schema = projected.schema().clone();
+    assert_eq!(schema.field_with_unqualified_name("c_i8")?.data_type(), &DataType::Int8);
+    assert_eq!(schema.field_with_unqualified_name("c_u64")?.data_type(), &DataType::UInt64);
+    assert_eq!(schema.field_with_unqualified_name("c_str")?.data_type(), &DataType::Utf8);
+    let batches = projected.collect().await?;
+    assert_eq!(batches[0].num_rows(), 1);
+    assert_eq!(batches[0].num_columns(), 14);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_count_star_table_functions_and_struct_access() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    // DataFrame::count goes through count(Literal(COUNT_STAR_EXPANSION)).
+    let n = ctx.table("t1").await?.count().await?;
+    assert_eq!(n, 3);
+    let gs = sql_rows(&ctx, "SELECT * FROM generate_series(1, 3)").await?;
+    let total: usize = gs.iter().map(|b| b.num_rows()).sum();
+    assert_eq!(total, 3);
+    let batches = sql_rows(
+        &ctx,
+        "SELECT struct(1 AS a, 'x' AS b)['a'] AS field, \
+                array_has([1, 2, 3], 2) AS has2, \
+                count(1) AS c1 \
+         FROM t1",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+-------+------+----+",
+            "| field | has2 | c1 |",
+            "+-------+------+----+",
+            "| 1     | true | 3  |",
+            "+-------+------+----+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_window_functions_with_literal_arguments() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    let batches = sql_rows(
+        &ctx,
+        "SELECT v, row_number() OVER (ORDER BY v) AS rn, \
+                nth_value(v, 2) OVER (ORDER BY v ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS nth \
+         FROM t1 ORDER BY v",
+    )
+    .await?;
+    assert_batches_eq!(
+        [
+            "+----+----+-----+",
+            "| v  | rn | nth |",
+            "+----+----+-----+",
+            "| 10 | 1  | 20  |",
+            "| 20 | 2  | 20  |",
+            "| 30 | 3  | 20  |",
+            "+----+----+-----+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_decimal_null_and_negative_literals_parse() -> Result<()> {
+    // parse_float_as_decimal drives the SQL decimal literal construction paths.
+    let config = SessionConfig::new().set_str("datafusion.sql_parser.parse_float_as_decimal", "true");
+    let ctx = SessionContext::new_with_config(config);
+    let batches = sql_rows(
+        &ctx,
+        "SELECT 12.345 AS dec_small, \
+                CAST(NULL AS INT) AS null_lit, \
+                -42 AS neg, \
+                12345678901234567890123456789012345678.5 AS dec_big",
+    )
+    .await?;
+    assert_eq!(batches[0].num_rows(), 1);
+    let schema = batches[0].schema();
+    assert!(matches!(schema.field(0).data_type(), DataType::Decimal128(_, _)));
+    assert!(matches!(schema.field(3).data_type(), DataType::Decimal256(_, _)));
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_unparser_roundtrips_literal_plans() -> Result<()> {
+    use datafusion::sql::unparser::plan_to_sql;
+    let ctx = ctx_with_table().await?;
+    let df = ctx
+        .sql(
+            "SELECT k, sum(v) AS sv, row_number() OVER (ORDER BY k) AS rn \
+             FROM t1 WHERE v > 5 AND s LIKE 'prefix%' GROUP BY k, v, s ORDER BY k LIMIT 2",
+        )
+        .await?;
+    let plan = df.logical_plan().clone();
+    let sql = plan_to_sql(&plan)?.to_string();
+    assert!(sql.contains("5"), "unparsed SQL keeps the literal: {sql}");
+    assert!(sql.to_lowercase().contains("limit"), "{sql}");
+    // Round-trip: the unparsed SQL must execute to the same shape.
+    let again = ctx.sql(&sql).await?.collect().await?;
+    let rows: usize = again.iter().map(|b| b.num_rows()).sum();
+    assert_eq!(rows, 2);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_literal_metadata_flows_to_schema_and_execution() -> Result<()> {
+    use std::collections::HashMap;
+    use datafusion::scalar::ScalarValue;
+
+    let ctx = ctx_with_table().await?;
+    let lit_md = lit_with_metadata(
+        ScalarValue::Int32(Some(7)),
+        HashMap::from([("purpose".to_string(), "lolbench".to_string())]),
+    );
+
+    // The literal's metadata must surface on the logical output field...
+    let df = ctx.table("t1").await?.select(vec![lit_md.clone().alias("c")])?;
+    let field = df.schema().field_with_unqualified_name("c")?;
+    assert_eq!(field.metadata().get("purpose").map(String::as_str), Some("lolbench"));
+
+    // ...and survive optimization + physical planning into execution output.
+    let batches = df.collect().await?;
+    assert_eq!(
+        batches[0].schema().field(0).metadata().get("purpose").map(String::as_str),
+        Some("lolbench")
+    );
+
+    // An alias carrying its own metadata merges it with the literal's — on the
+    // logical schema AND through the physical planner into execution output.
+    let Expr::Alias(mut alias) = lit_md.alias("c2") else { unreachable!() };
+    alias.metadata = Some(HashMap::from([("origin".to_string(), "alias".to_string())]));
+    let df2 = ctx.table("t1").await?.select(vec![Expr::Alias(alias)])?;
+    let field2 = df2.schema().field_with_unqualified_name("c2")?;
+    assert_eq!(field2.metadata().get("origin").map(String::as_str), Some("alias"));
+    assert_eq!(field2.metadata().get("purpose").map(String::as_str), Some("lolbench"));
+    let batches2 = df2.collect().await?;
+    let exec_field2 = batches2[0].schema();
+    let exec_field2 = exec_field2.field(0);
+    assert_eq!(exec_field2.metadata().get("origin").map(String::as_str), Some("alias"));
+    assert_eq!(exec_field2.metadata().get("purpose").map(String::as_str), Some("lolbench"));
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_literal_metadata_reaches_scalar_udf_return_field() -> Result<()> {
+    use std::any::Any;
+    use std::collections::HashMap;
+    use arrow::datatypes::FieldRef;
+    use datafusion::logical_expr::{
+        ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
+        Signature, Volatility,
+    };
+    use datafusion::scalar::ScalarValue;
+
+    // A probe function that republishes its first argument's field metadata on
+    // its return field — the requirement's "when return_field_from_args gets
+    // called, the metadata would be available" contract.
+    #[derive(Debug)]
+    struct MetadataProbe {
+        signature: Signature,
+    }
+    impl ScalarUDFImpl for MetadataProbe {
+        fn as_any(&self) -> &dyn Any {
+            self
+        }
+        fn name(&self) -> &str {
+            "aug_metadata_probe"
+        }
+        fn signature(&self) -> &Signature {
+            &self.signature
+        }
+        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
+            Ok(DataType::Int32)
+        }
+        fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
+            let metadata = args.arg_fields[0].metadata().clone();
+            Ok(Arc::new(
+                Field::new(self.name(), DataType::Int32, true).with_metadata(metadata),
+            ))
+        }
+        fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+            Ok(args.args[0].clone())
+        }
+    }
+
+    let ctx = ctx_with_table().await?;
+    let probe = ScalarUDF::from(MetadataProbe {
+        signature: Signature::exact(vec![DataType::Int32], Volatility::Immutable),
+    });
+    let arg = lit_with_metadata(
+        ScalarValue::Int32(Some(7)),
+        HashMap::from([("purpose".to_string(), "lolbench".to_string())]),
+    );
+    let expr = probe.call(vec![arg]).alias("p");
+
+    let df = ctx.table("t1").await?.select(vec![expr])?;
+    let field = df.schema().field_with_unqualified_name("p")?;
+    assert_eq!(field.metadata().get("purpose").map(String::as_str), Some("lolbench"));
+    // The physical literal's field metadata must reach the physical scalar
+    // function's return field and survive into the executed output schema.
+    let batches = df.collect().await?;
+    assert_eq!(batches[0].num_rows(), 3);
+    let exec_schema = batches[0].schema();
+    assert_eq!(
+        exec_schema.field(0).metadata().get("purpose").map(String::as_str),
+        Some("lolbench")
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_metadata_literals_drive_rewrites_and_functions() -> Result<()> {
+    use std::collections::HashMap;
+    use datafusion::functions::expr_fn::{concat, concat_ws, log, power, starts_with};
+    use datafusion::functions_aggregate::expr_fn::count;
+    use datafusion::functions_nested::expr_fn::{array_has, make_array};
+    use datafusion::scalar::ScalarValue;
+
+    fn md_lit(sv: ScalarValue) -> Expr {
+        lit_with_metadata(
+            sv,
+            HashMap::from([("purpose".to_string(), "lolbench".to_string())]),
+        )
+    }
+
+    let ctx = ctx_with_table().await?;
+    let t = ctx.table("t1").await?;
+
+    // Metadata-bearing literals flowing through the simplifier's function
+    // rewrites and scalar-evaluation arms: every projected expression must
+    // still evaluate to its plain-literal result.
+    let df = t.clone().select(vec![
+        concat(vec![md_lit(ScalarValue::from("p:")), col("s")]).alias("e1"),
+        concat_ws(md_lit(ScalarValue::from(",")), vec![md_lit(ScalarValue::from("x")), col("s")]).alias("e2"),
+        starts_with(col("s"), md_lit(ScalarValue::from("prefix_"))).alias("e3"),
+        power(md_lit(ScalarValue::Float64(Some(2.0))), cast(col("v"), DataType::Float64)).alias("e4"),
+        log(md_lit(ScalarValue::Float64(Some(2.0))), cast(col("v"), DataType::Float64)).alias("e5"),
+        array_has(make_array(vec![md_lit(ScalarValue::Int32(Some(1))), md_lit(ScalarValue::Int32(Some(2)))]), col("k")).alias("e6"),
+        md_lit(ScalarValue::Int32(Some(5))).between(md_lit(ScalarValue::Int32(Some(1))), md_lit(ScalarValue::Int32(Some(9)))).alias("e7"),
+        col("v").in_list(vec![md_lit(ScalarValue::Int32(Some(10))), md_lit(ScalarValue::Int32(Some(20)))], false).alias("e8"),
+        (md_lit(ScalarValue::Int32(Some(2))) + md_lit(ScalarValue::Int32(Some(3)))).alias("e9"),
+        md_lit(ScalarValue::from("foo")).like(md_lit(ScalarValue::from("f%"))).alias("e10"),
+    ])?;
+    let batches = df.collect().await?;
+    assert_eq!(batches[0].num_rows(), 3);
+
+    // A filter mixing metadata literals with guaranteed-true predicates keeps
+    // its plain semantics through the boolean simplifier.
+    let filtered = t
+        .clone()
+        .filter(
+            col("v")
+                .gt(md_lit(ScalarValue::Int32(Some(5))))
+                .and(md_lit(ScalarValue::Boolean(Some(true))))
+                .and(col("v").gt(md_lit(ScalarValue::Int32(Some(5))))),
+        )?
+        .select(vec![col("v")])?;
+    let fb = filtered.collect().await?;
+    let rows: usize = fb.iter().map(|b| b.num_rows()).sum();
+    assert_eq!(rows, 3);
+
+    // Aggregation with a metadata-literal count argument.
+    let agg = t
+        .clone()
+        .aggregate(vec![col("k")], vec![count(md_lit(ScalarValue::Int32(Some(1)))).alias("c")])?
+        .sort(vec![col("k").sort(true, true)])?;
+    let ab = agg.collect().await?;
+    let total: i64 = ab
+        .iter()
+        .flat_map(|b| {
+            let arr = b.column(1).as_any().downcast_ref::<arrow::array::Int64Array>().unwrap();
+            (0..arr.len()).map(|i| arr.value(i)).collect::<Vec<_>>()
+        })
+        .sum();
+    assert_eq!(total, 3);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_typed_identity_arms_and_const_lists_simplify() -> Result<()> {
+    let ctx = ctx_with_table().await?;
+    // Multiply/add/power identity arms are matched per literal type; a literal
+    // on the left of a comparison takes the operand-swap arm; fully-literal
+    // array constructions const-evaluate to (Large)List scalars.
+    let batches = sql_rows(
+        &ctx,
+        "SELECT v * CAST(0 AS BIGINT UNSIGNED) AS z_u64, \
+                CAST(v AS FLOAT) + CAST(0.0 AS FLOAT) AS z_f32, \
+                CAST(v AS DOUBLE) * CAST(1.0 AS DOUBLE) AS one_f64, \
+                v * CAST(1.0 AS DECIMAL(5,2)) AS one_dec, \
+                v + CAST(0 AS DECIMAL(5,2)) AS z_dec, \
+                power(CAST(v AS DOUBLE), 0) AS pow_zero, \
+                power(CAST(v AS DOUBLE), 1) AS pow_one, \
+                log(2.0, CAST(1 AS DOUBLE)) AS log_one, \
+                [1, 2, 3] AS const_list, \
+                arrow_cast([1, 2], 'LargeList(Int64)') AS const_large, \
+                5 < v AS lit_left, \
+                (v > 5) IS NOT UNKNOWN AS not_unknown \
+         FROM t1 ORDER BY v LIMIT 1",
+    )
+    .await?;
+    assert_eq!(batches[0].num_rows(), 1);
+    let mixed = sql_rows(
+        &ctx,
+        "SELECT concat(arrow_cast('a', 'LargeUtf8'), s, arrow_cast('', 'Utf8View'), arrow_cast(NULL, 'LargeUtf8')) AS c1, \
+                concat_ws(',', arrow_cast('x', 'Utf8View'), arrow_cast(NULL, 'Utf8'), arrow_cast('y', 'LargeUtf8'), s) AS c2 \
+         FROM t1 ORDER BY v LIMIT 1",
+    )
+    .await?;
+    assert_eq!(mixed[0].num_rows(), 1);
+    // Layered redundant range/IN predicates drive the guarantee rewriter.
+    let g = sql_rows(
+        &ctx,
+        "SELECT v FROM t1 WHERE v BETWEEN 1 AND 100 AND v BETWEEN 1 AND 100 \
+           AND v IN (10, 20, 30) AND v IN (10, 20, 30) AND s ~ '^prefix_a$' IS NOT NULL ORDER BY v",
+    )
+    .await?;
+    let rows: usize = g.iter().map(|b| b.num_rows()).sum();
+    assert_eq!(rows, 3);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_planner_sql_and_unparser_literal_paths() -> Result<()> {
+    use datafusion::sql::unparser::plan_to_sql;
+    let ctx = ctx_with_table().await?;
+
+    // count(*) expansions: aggregate and windowed; correlated COUNT scalar
+    // subquery takes the null-to-zero decorrelation arm; empty-input scalar
+    // subquery takes the NULL else arm; JOIN ON false is eliminated.
+    let batches = sql_rows(
+        &ctx,
+        "SELECT k, count(*) AS c, count(*) OVER () AS cw, \
+                (SELECT count(*) FROM t2 WHERE t2.k = t1.k AND t2.y > 1000) AS zero_cnt, \
+                (SELECT max(y) FROM t2 WHERE false) AS none_max \
+         FROM t1 GROUP BY k, v ORDER BY k, v",
+    )
+    .await?;
+    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
+    let joined = sql_rows(&ctx, "SELECT t1.v FROM t1 JOIN t2 ON false").await?;
+    assert!(joined.is_empty() || joined.iter().all(|b| b.num_rows() == 0));
+
+    // grouping() over a plain GROUP BY takes the zero-literal arm.
+    let grouped = sql_rows(&ctx, "SELECT k, grouping(k) AS g FROM t1 GROUP BY k ORDER BY k").await?;
+    assert_eq!(grouped.iter().map(|b| b.num_rows()).sum::<usize>(), 2);
+
+    // Placeholder parameters replace into plain literals; literal-typed NULL
+    // VALUES rows are back-filled; LIMIT folds a constant expression;
+    // FROM-only substring; intervals; now(); coalesce; lag/lead offsets.
+    let df = ctx
+        .sql("SELECT $1 + v AS pv FROM t1 ORDER BY v LIMIT 1")
+        .await?
+        .with_param_values(vec![datafusion::scalar::ScalarValue::Int32(Some(100))])?;
+    assert_eq!(df.collect().await?[0].num_rows(), 1);
+    let misc = sql_rows(
+        &ctx,
+        "SELECT a FROM (VALUES (NULL), (7)) AS vt(a) ORDER BY a NULLS FIRST LIMIT 1 + 1",
+    )
+    .await?;
+    assert_eq!(misc.iter().map(|b| b.num_rows()).sum::<usize>(), 2);
+    let exprs = sql_rows(
+        &ctx,
+        "SELECT substring('hello' FROM 2) AS sub, \
+                INTERVAL '1' YEAR AS iy, INTERVAL '2' DAY AS idt, INTERVAL '1 month 1 day 1 second' AS imdn, \
+                now() <= now() AS nw, coalesce(NULL, 5) AS co, \
+                lag(v, 2) OVER (ORDER BY v) AS lg, lead(v, 1) OVER (ORDER BY v) AS ld, \
+                struct(1 AS a, 'x' AS b)['a'] AS brfield \
+         FROM t1 ORDER BY v",
+    )
+    .await?;
+    assert_eq!(exprs.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
+    let gs_null = sql_rows(&ctx, "SELECT * FROM generate_series(1, NULL)").await?;
+    assert_eq!(gs_null.iter().map(|b| b.num_rows()).sum::<usize>(), 0);
+
+    // Unparse plans exercising date_part/date_trunc, struct-field access and
+    // window functions; the unparsed SQL must execute again.
+    let df2 = ctx
+        .sql(
+            "SELECT date_part('year', now()) AS yr, date_trunc('day', now()) AS dy, \
+                    row_number() OVER (ORDER BY v) AS rn \
+             FROM t1",
+        )
+        .await?;
+    let plan = df2.logical_plan().clone();
+    let sql = plan_to_sql(&plan)?.to_string();
+    let again = ctx.sql(&sql).await?.collect().await?;
+    assert_eq!(again.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_partitioned_listing_table_pruning() -> Result<()> {
+    use std::fs;
+    let tmp = std::env::temp_dir().join("lolbench_aug_part");
+    let _ = fs::remove_dir_all(&tmp);
+    fs::create_dir_all(tmp.join("part=1"))?;
+    fs::create_dir_all(tmp.join("part=2"))?;
+    fs::write(tmp.join("part=1/a.csv"), "x\n10\n20\n")?;
+    fs::write(tmp.join("part=2/a.csv"), "x\n30\n")?;
+    let ctx = SessionContext::new();
+    ctx.sql(&format!(
+        "CREATE EXTERNAL TABLE pt (x INT) STORED AS CSV PARTITIONED BY (part INT) \
+         LOCATION '{}' OPTIONS ('format.has_header' 'true')",
+        tmp.display()
+    ))
+    .await?
+    .collect()
+    .await?;
+    let batches = ctx
+        .sql("SELECT x FROM pt WHERE part = 1 ORDER BY x")
+        .await?
+        .collect()
+        .await?;
+    assert_batches_eq!(
+        ["+----+", "| x  |", "+----+", "| 10 |", "| 20 |", "+----+",],
+        &batches
+    );
+    // Literal-on-the-left partition predicate takes the swapped match arm.
+    let swapped = ctx
+        .sql("SELECT x FROM pt WHERE 2 = part ORDER BY x")
+        .await?
+        .collect()
+        .await?;
+    assert_batches_eq!(
+        ["+----+", "| x  |", "+----+", "| 30 |", "+----+",],
+        &swapped
+    );
+    Ok(())
+}
diff --git a/datafusion/core/tests/lolbench_aug_p2p.rs b/datafusion/core/tests/lolbench_aug_p2p.rs
new file mode 100644
index 0000000..4b6813d
--- /dev/null
+++ b/datafusion/core/tests/lolbench_aug_p2p.rs
@@ -0,0 +1,72 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Augmented suite (lolbench-aug, P2P). The requirement adds an optional
+//! metadata slot to literals; everything that does not involve metadata must
+//! behave exactly as before. These tests pin adjacent unchanged behaviors
+//! (string functions and arithmetic untouched by the change) and deliberately
+//! avoid the new literal shape so they compile and pass at pre-state.
+
+use datafusion::assert_batches_eq;
+use datafusion::error::Result;
+use datafusion::prelude::*;
+
+#[tokio::test]
+async fn aug_p2p_unmodified_string_functions_keep_behavior() -> Result<()> {
+    let ctx = SessionContext::new();
+    let batches = ctx
+        .sql("SELECT upper('ab') AS u, lower('CD') AS l, trim('  x  ') AS t, length('abcd') AS n")
+        .await?
+        .collect()
+        .await?;
+    assert_batches_eq!(
+        [
+            "+----+----+---+---+",
+            "| u  | l  | t | n |",
+            "+----+----+---+---+",
+            "| AB | cd | x | 4 |",
+            "+----+----+---+---+",
+        ],
+        &batches
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn aug_p2p_arithmetic_and_ordering_keep_behavior() -> Result<()> {
+    let ctx = SessionContext::new();
+    let batches = ctx
+        .sql(
+            "SELECT a, a * 2 AS d FROM (VALUES (3), (1), (2)) AS v(a) ORDER BY a DESC",
+        )
+        .await?
+        .collect()
+        .await?;
+    assert_batches_eq!(
+        [
+            "+---+---+",
+            "| a | d |",
+            "+---+---+",
+            "| 3 | 6 |",
+            "| 2 | 4 |",
+            "| 1 | 2 |",
+            "+---+---+",
+        ],
+        &batches
+    );
+    Ok(())
+}
diff --git a/datafusion/proto/tests/lolbench_aug.rs b/datafusion/proto/tests/lolbench_aug.rs
new file mode 100644
index 0000000..419d87a
--- /dev/null
+++ b/datafusion/proto/tests/lolbench_aug.rs
@@ -0,0 +1,41 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! Augmented suite (lolbench-aug): literal expressions must survive the
+//! protobuf logical-plan round trip unchanged, through the public bytes API.
+
+use datafusion::prelude::*;
+use datafusion_proto::bytes::{logical_plan_from_bytes, logical_plan_to_bytes};
+
+#[tokio::test]
+async fn aug_literals_roundtrip_through_proto() -> datafusion::error::Result<()> {
+    // Literal-shape guard: the public Expr::Literal carries (value, metadata);
+    // compile-flips this binary at pre-state like the original suite files.
+    assert_eq!(
+        Expr::Literal(datafusion::scalar::ScalarValue::Int64(Some(7)), None),
+        lit(7i64)
+    );
+    let ctx = SessionContext::new();
+    let df = ctx
+        .sql("SELECT 1 AS i, 2.5 AS f, 'txt' AS s, true AS b, CAST(NULL AS INT) AS n")
+        .await?;
+    let plan = df.logical_plan().clone();
+    let bytes = logical_plan_to_bytes(&plan)?;
+    let restored = logical_plan_from_bytes(&bytes, &ctx)?;
+    assert_eq!(format!("{plan}"), format!("{restored}"));
+    Ok(())
+}