-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_optimiser.rs
More file actions
2148 lines (2003 loc) · 102 KB
/
query_optimiser.rs
File metadata and controls
2148 lines (2003 loc) · 102 KB
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// query_optimiser.rs — query rewrite / optimisation pass
//
// ═══════════════════════════════════════════════════════════════════════════
// ALL OPTIMISATIONS:
//
// [OPT-01] Predicate Pushdown → push_filter_into, collect_cross_leaves
// [OPT-02] Filter Reordering → reorder_predicates_by_selectivity
// [OPT-03] Cross+Filter → Join → fuse_filter_cross, build_optimal_join
// [OPT-04] Projection Pushdown → fuse_project (through Sort+Filter+FScan)
// [OPT-05] Pipelining → FilteredScanData fused scan node
// [OPT-06] Materialization → spill() in giveoutput.rs
// [OPT-07] Grace Hash Join → grace_hash_join in giveoutput.rs
// [OPT-08] External Merge Sort → exec_sort in giveoutput.rs
// [OPT-09] Buffer management → safe_cap() in giveoutput.rs
// [OPT-10] Build-side selection → build_join_node (stat-driven)
// [OPT-11] IsPhysicallyOrdered → stat-driven via ColumnStat
// [OPT-12] Filter selectivity → full stat-driven (histogram/density/range/cardinality)
// [OPT-13] Join size estimation → estimated_rows_ctx (CardinalityStat row counts)
// [OPT-14] Join order optimisation → build_optimal_join (stat-driven, connectivity-aware)
// [OPT-15] Skew detection → grace_hash_join in giveoutput.rs
// [OPT-16] Partition count tuning → grace_partition_count free fn
// [OPT-17] Sort-Merge Join → sort_merge_join in giveoutput.rs
// [OPT-18] Reuse Sort Order → is_physically_ordered propagated
// [OPT-19] Early termination → FilteredScanData.is_physically_ordered_on
// [OPT-20] Dynamic memory split → set_memory_limit_mb in giveoutput.rs
// [OPT-21] Predicate reordering inside HashJoin extra_preds
// → reorder_predicates_by_selectivity called on extra_preds after join build
// [OPT-22] Multi-pass scalar pushdown
// → push_all_scalars_deep recurses through the full plan tree post-join-build
// so scalar preds that cross project/sort/filter barriers are still pushed
// [OPT-23] Redundant Project elimination
// → elide_redundant_projects removes Project nodes whose map is an identity
// on an already-projected FilteredScan (avoids double projection work)
// [OPT-24] Sort-order propagation through HashJoin output
// → subtree_is_ordered_on_specs checks whether the probe-side output of a
// HashJoin preserves order so downstream Sort can be skipped
// [OPT-25] Adaptive FilterCross → HashJoin upgrade in pass 3
// → distribute_predicates_deep attempts build_join_node on any
// Filter(FilterCross) or Filter(HashJoin) to upgrade NLJ to HJ
//
// KEY FIXES:
//
// [FIX-CROSS-OOM]
// collect_cross_leaves recurses through Filter(Cross) nodes, extracting
// their predicates into the global pool so all tables are joined optimally.
// build_join_node emits FilterCross (chunked NLJ) instead of bare Cross
// whenever the estimated product exceeds 4× memory budget, preventing
// the 20M-row cartesian product that caused the allocator to fail.
// distribute_predicates_deep (pass 3) catches any Filter(Cross) that
// escaped pass 1 and re-converts them.
//
// [FIX-COL-MATCH]
// known_col_prefix correctly disambiguates "p_" (part) from "ps_" (partsupp)
// so join predicates are never silently mis-attributed.
//
// [FIX-PROJ-SORT]
// fuse_project pushes projections through Sort(Filter*(FilteredScan)),
// reducing the row width seen by the external sort.
//
// [FIX-COMPOSITE-JOIN]
// build_join_node collects ALL equi-predicates between a table pair into a
// single HashJoin node with composite left_keys/right_keys, rather than
// chaining two separate HashJoin nodes. Critical for Q58.
//
// [FIX-NE-JOIN]
// build_join_node now separates equi-join predicates from non-equi (NE, GT,
// LT etc.) predicates. If at least one equi-predicate exists, a HashJoin is
// emitted using only the equi-predicates as keys, and the NE predicates go
// into extra_preds for post-join filtering.
//
// [FIX-ALIAS-COL]
// tree_has_col now correctly handles dotted alias names like "l1.l_orderkey"
// by checking the bare column name suffix against known prefixes.
//
// [FIX-SCALAR-PUSH-ALIAS]
// push_scalar_into_rel handles dotted alias predicates: for a predicate on
// "alias.bare_col", it finds the Project node whose output contains
// "alias.bare_col" and pushes the predicate there.
//
// [FIX-PROJ-PASSTHROUGH]
// fuse_project (Case C) now attempts to push the project through HashJoin,
// FilterCross and Filter nodes when the projected columns are a strict subset
// of what those operators output, eliminating wide intermediate rows.
//
// [FIX-SORT-EXTRA-COL]
// When fuse_project Case B adds extra key columns for Sort, those columns
// are now correctly mapped from their fully-qualified names (e.g.
// "lineitem.l_shipdate") to the bare sort key name so cmp_rows can find them.
//
// STATS POLICY:
// All cardinality and selectivity decisions use ColumnStat from DbContext.
// TPC-H SF-1 heuristics are used ONLY as a last-resort fallback when no
// ColumnStat is present, with an explicit warning logged.
//
// IsPhysicallyOrdered → OPT-11, OPT-19
// RangeStat → OPT-12 range selectivity
// HistogramStat → OPT-12 equality/range selectivity
// CardinalityStat → OPT-12 (1/NDV), OPT-13 (row counts)
// DensityStat → OPT-12 equality selectivity
// ═══════════════════════════════════════════════════════════════════════════
use common::query::*;
use db_config::{DbContext, statistics::ColumnStat};
// ─────────────────────────────────────────────────────────────────────────────
// Optimised plan node types
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct OptFilterData {
pub predicates: Vec<Predicate>,
pub underlying: Box<OptQueryOp>,
}
#[derive(Debug, Clone)]
pub struct FilterCrossData {
pub predicates: Vec<Predicate>,
pub left: Box<OptQueryOp>,
pub right: Box<OptQueryOp>,
}
#[derive(Debug, Clone)]
pub struct HashJoinData {
pub left_keys: Vec<String>,
pub right_keys: Vec<String>,
pub extra_preds: Vec<Predicate>,
pub left: Box<OptQueryOp>,
pub right: Box<OptQueryOp>,
}
#[derive(Debug, Clone)]
pub struct OptProjectData {
pub column_name_map: Vec<(String, String)>,
pub underlying: Box<OptQueryOp>,
}
#[derive(Debug, Clone)]
pub struct OptCrossData {
pub left: Box<OptQueryOp>,
pub right: Box<OptQueryOp>,
}
#[derive(Debug, Clone)]
pub struct OptSortData {
pub sort_specs: Vec<SortSpec>,
pub underlying: Box<OptQueryOp>,
/// [OPT-11][OPT-18] true → executor skips the sort entirely.
pub is_physically_ordered: bool,
}
/// [OPT-01][OPT-04][OPT-05] Fused scan+filter+project in one executor pass.
#[derive(Debug, Clone)]
pub struct FilteredScanData {
pub table_id: String,
pub predicates: Vec<Predicate>,
/// (original_col, output_col). None = emit every column.
pub project: Option<Vec<(String, String)>>,
/// [OPT-19] Stop scanning when this column exceeds the upper-bound predicate.
pub is_physically_ordered_on: Option<String>,
}
#[derive(Debug, Clone)]
pub enum OptQueryOp {
Scan(ScanData),
FilteredScan(FilteredScanData),
Filter(OptFilterData),
Project(OptProjectData),
Cross(OptCrossData),
Sort(OptSortData),
FilterCross(FilterCrossData),
HashJoin(HashJoinData),
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-12][OPT-13] Optimiser context
// ─────────────────────────────────────────────────────────────────────────────
pub struct OptContext<'a> {
pub db: &'a DbContext,
pub memory_budget_bytes: usize,
}
impl<'a> OptContext<'a> {
pub fn new(db: &'a DbContext) -> Self {
OptContext { db, memory_budget_bytes: 64 * 1024 * 1024 }
}
// ── [OPT-13] Row count from ColumnStat ───────────────────────────────────
pub fn table_row_count(&self, table_id: &str) -> u64 {
let resolved = self.resolve_table_id(table_id);
let spec = match self.db.get_table_specs().iter().find(|t| t.name == resolved) {
Some(s) => s,
None => {
eprintln!("[OPT-WARN][OPT-13] table '{}' (resolved: '{}') not in DbContext — fallback",
table_id, resolved);
return tpch_row_estimate(&resolved);
}
};
// Pass 1: PK column (IsPhysicallyOrdered + CardinalityStat).
for col in &spec.column_specs {
if let Some(stats) = &col.stats {
let ordered = stats.iter().any(|s| matches!(s, ColumnStat::IsPhysicallyOrdered));
if ordered {
for s in stats {
if let ColumnStat::CardinalityStat(c) = s {
eprintln!("[OPT-13] '{}' row_count={} (PK CardinalityStat col='{}')",
table_id, c.0, col.column_name);
return c.0;
}
}
}
}
}
// Pass 2: maximum CardinalityStat.
let mut max_card: u64 = 0;
for col in &spec.column_specs {
if let Some(stats) = &col.stats {
for s in stats {
if let ColumnStat::CardinalityStat(c) = s {
if c.0 > max_card { max_card = c.0; }
}
}
}
}
if max_card > 0 {
eprintln!("[OPT-13] '{}' row_count={} (max CardinalityStat)", table_id, max_card);
return max_card;
}
// Pass 3: histogram frequency sum.
for col in &spec.column_specs {
if let Some(stats) = &col.stats {
for s in stats {
if let ColumnStat::HistogramStat(h) = s {
let total: u64 = h.frequency_points.iter().map(|(_, f)| f.0).sum();
if total > 0 {
eprintln!("[OPT-13] '{}' row_count={} (histogram col='{}')",
table_id, total, col.column_name);
return total;
}
}
}
}
}
// Pass 4: TPC-H heuristic fallback.
let est = tpch_row_estimate(&resolved);
eprintln!("[OPT-WARN][OPT-13] '{}' no stats → TPC-H heuristic {}", table_id, est);
est
}
/// Resolve alias table IDs (e.g. "l1", "l2") to base table names.
pub fn resolve_table_id<'b>(&self, table_id: &'b str) -> String {
if self.db.get_table_specs().iter().any(|t| t.name == table_id) {
return table_id.to_string();
}
let base = table_id.trim_end_matches(|c: char| c.is_ascii_digit());
let candidates = [
("l", "lineitem"),
("o", "orders"),
("c", "customer"),
("p", "part"),
("ps", "partsupp"),
("s", "supplier"),
("n", "nation"),
("r", "region"),
("cn", "nation"),
("sn", "nation"),
("cr", "region"),
("sr", "region"),
];
for (pfx, tbl) in &candidates {
if base == *pfx {
return tbl.to_string();
}
}
table_id.to_string()
}
// ── [OPT-12] Selectivity estimation ──────────────────────────────────────
pub fn filter_selectivity(&self, table_id: &str, preds: &[Predicate]) -> f64 {
if preds.is_empty() { return 1.0; }
let resolved = self.resolve_table_id(table_id);
let total_rows = self.table_row_count(table_id) as f64;
let mut sel = 1.0f64;
for pred in preds {
if matches!(&pred.value, ComparisionValue::Column(_)) { continue; }
let col_spec = self.db.get_table_specs()
.iter()
.find(|t| t.name == resolved)
.and_then(|spec| spec.column_specs.iter().find(|c| {
let full = format!("{}.{}", resolved, c.column_name);
full == pred.column_name
|| c.column_name == pred.column_name
|| pred.column_name.ends_with(&format!(".{}", c.column_name))
|| {
let bare = pred.column_name.split('.').last().unwrap_or(&pred.column_name);
c.column_name == bare
}
}));
let col_sel = match &pred.operator {
ComparisionOperator::EQ =>
self.sel_eq(col_spec, &pred.value, total_rows),
ComparisionOperator::NE =>
1.0 - self.sel_eq(col_spec, &pred.value, total_rows),
ComparisionOperator::LT | ComparisionOperator::LTE |
ComparisionOperator::GT | ComparisionOperator::GTE =>
self.sel_range(col_spec, &pred.operator, &pred.value),
};
sel *= col_sel;
}
sel.clamp(1e-6, 1.0)
}
fn sel_eq(
&self,
col_spec: Option<&db_config::table::ColumnSpec>,
value: &ComparisionValue,
total_rows: f64,
) -> f64 {
let lit_f64 = comparison_value_as_f64(value);
if let Some(col) = col_spec {
if let Some(stats) = &col.stats {
// Priority 1: histogram.
for s in stats {
if let ColumnStat::HistogramStat(h) = s {
if let Some(lit) = lit_f64 {
for (range, freq) in &h.frequency_points {
if let (Some(lo), Some(hi)) = (
data_as_f64(&range.lower_bound),
data_as_f64(&range.upper_bound),
) {
if lit >= lo && lit <= hi && hi > lo {
let frac = 1.0 / (hi - lo).max(1.0);
return (freq.0 as f64 / total_rows.max(1.0) * frac)
.clamp(1e-6, 1.0);
}
}
}
} else if let ComparisionValue::String(s_lit) = value {
for (range, freq) in &h.frequency_points {
if let common::Data::String(ref lo_s) = range.lower_bound {
if s_lit == lo_s {
return (freq.0 as f64 / total_rows.max(1.0))
.clamp(1e-6, 1.0);
}
}
}
}
}
}
// Priority 2: DensityStat.
for s in stats {
if let ColumnStat::DensityStat(d) = s {
return (d.0 as f64).clamp(1e-6, 1.0);
}
}
// Priority 3: CardinalityStat → uniform 1/NDV.
for s in stats {
if let ColumnStat::CardinalityStat(c) = s {
if c.0 > 0 { return (1.0 / c.0 as f64).clamp(1e-6, 1.0); }
}
}
// Priority 4: DataType fallback.
return match col.data_type {
common::DataType::String => 0.05,
common::DataType::Int32 | common::DataType::Int64 => 0.02,
common::DataType::Float32 | common::DataType::Float64 => 0.01,
_ => 0.10,
};
}
}
0.10
}
fn sel_range(
&self,
col_spec: Option<&db_config::table::ColumnSpec>,
op: &ComparisionOperator,
value: &ComparisionValue,
) -> f64 {
let lit = match comparison_value_as_f64(value) {
Some(v) => v,
None => return 0.30,
};
if let Some(col) = col_spec {
if let Some(stats) = &col.stats {
// Priority 1: RangeStat fraction of domain.
for s in stats {
if let ColumnStat::RangeStat(r) = s {
if let (Some(lo), Some(hi)) = (
data_as_f64(&r.lower_bound), data_as_f64(&r.upper_bound),
) {
let domain = (hi - lo).abs();
if domain > 0.0 {
let covered = match op {
ComparisionOperator::LT | ComparisionOperator::LTE =>
(lit - lo).max(0.0).min(domain) / domain,
ComparisionOperator::GT | ComparisionOperator::GTE =>
(hi - lit).max(0.0).min(domain) / domain,
_ => 0.33,
};
return covered.clamp(1e-6, 1.0);
}
}
}
}
// Priority 2: histogram bucket counting.
for s in stats {
if let ColumnStat::HistogramStat(h) = s {
let total_freq: u64 = h.frequency_points.iter().map(|(_, f)| f.0).sum();
if total_freq == 0 { continue; }
let mut in_range: u64 = 0;
for (range, freq) in &h.frequency_points {
if let (Some(lo), Some(hi)) = (
data_as_f64(&range.lower_bound),
data_as_f64(&range.upper_bound),
) {
let fully_in = match op {
ComparisionOperator::LT => hi < lit,
ComparisionOperator::LTE => hi <= lit,
ComparisionOperator::GT => lo > lit,
ComparisionOperator::GTE => lo >= lit,
_ => false,
};
let partial = matches!(op,
ComparisionOperator::LT | ComparisionOperator::LTE |
ComparisionOperator::GT | ComparisionOperator::GTE)
&& lo < lit && hi > lit;
if fully_in {
in_range += freq.0;
} else if partial {
let bw = (hi - lo).max(1.0);
let frac = match op {
ComparisionOperator::LT | ComparisionOperator::LTE =>
(lit - lo) / bw,
_ => (hi - lit) / bw,
};
in_range += (freq.0 as f64 * frac.clamp(0.0, 1.0)) as u64;
}
}
}
return (in_range as f64 / total_freq as f64).clamp(1e-6, 1.0);
}
}
}
}
0.33
}
// ── [OPT-11] Physical order check from ColumnStat ────────────────────────
pub fn column_is_physically_ordered(&self, table_id: &str, col_name: &str) -> bool {
let resolved = self.resolve_table_id(table_id);
let bare = col_name.split('.').last().unwrap_or(col_name);
let found = self.db.get_table_specs()
.iter()
.find(|t| t.name == resolved)
.and_then(|spec| spec.column_specs.iter().find(|c| {
c.column_name == bare
|| c.column_name == col_name
|| col_name.ends_with(&format!(".{}", c.column_name))
|| format!("{}.{}", resolved, c.column_name) == col_name
}))
.and_then(|c| c.stats.as_ref())
.map(|stats| stats.iter().any(|s| matches!(s, ColumnStat::IsPhysicallyOrdered)))
.unwrap_or(false);
if !found {
return matches!(bare,
"l_orderkey" | "o_orderkey" |
"ps_partkey" | "p_partkey" |
"c_custkey" | "s_suppkey" |
"n_nationkey" | "r_regionkey"
);
}
found
}
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-16] Grace partition count
// ─────────────────────────────────────────────────────────────────────────────
pub fn grace_partition_count(
build_rows: u64,
avg_row_bytes: usize,
memory_budget_bytes: usize,
) -> usize {
let build_bytes = (build_rows as usize).saturating_mul(avg_row_bytes);
// Each partition's build side must fit in 1/8 of budget so the hash map
// for that partition fits comfortably alongside the probe read buffer.
let partition_budget = (memory_budget_bytes / 8).max(1);
let n = (build_bytes + partition_budget - 1) / partition_budget;
let result = n.clamp(8, 512);
eprintln!("[OPT-16] grace_parts build_rows={} → n_parts={}", build_rows, result);
result
}
// ─────────────────────────────────────────────────────────────────────────────
// Public entry point
// ─────────────────────────────────────────────────────────────────────────────
/// [OPT-26] Column pruning: given the set of columns needed by the parent,
/// push narrowing projections into HashJoin children to reduce row width.
/// `needed` = None means "all columns needed" (top of tree).
fn prune_columns_top_down(op: OptQueryOp, needed: Option<&[String]>) -> OptQueryOp {
match op {
OptQueryOp::Project(OptProjectData { column_name_map, underlying }) => {
let child_needed: Vec<String> = column_name_map.iter()
.map(|(from, _)| from.clone())
.collect();
let new_child = prune_columns_top_down(*underlying, Some(&child_needed));
OptQueryOp::Project(OptProjectData {
column_name_map,
underlying: Box::new(new_child),
})
}
OptQueryOp::Sort(OptSortData { sort_specs, underlying, is_physically_ordered }) => {
let sort_keys: Vec<String> = sort_specs.iter()
.map(|s| s.column_name.clone())
.collect();
let extended: Option<Vec<String>> = needed.map(|n| {
let mut v = n.to_vec();
for k in &sort_keys {
if !v.contains(k) { v.push(k.clone()); }
}
v
});
let new_child = prune_columns_top_down(*underlying, extended.as_deref());
OptQueryOp::Sort(OptSortData {
sort_specs,
underlying: Box::new(new_child),
is_physically_ordered,
})
}
OptQueryOp::HashJoin(hj) => {
let needed_set: Option<std::collections::HashSet<&str>> = needed.map(|n| {
n.iter().map(|s| s.as_str()).collect()
});
let left_out = tree_output_cols(&hj.left);
let right_out = tree_output_cols(&hj.right);
let join_cols_needed: Vec<String> = hj.left_keys.iter()
.cloned()
.chain(hj.right_keys.iter().cloned())
.chain(hj.extra_preds.iter().flat_map(|p| {
let mut v = vec![p.column_name.clone()];
if let ComparisionValue::Column(c) = &p.value { v.push(c.clone()); }
v
}))
.collect();
let left_needed: Vec<String> = left_out.iter().filter(|c| {
if c.ends_with(".*") { return true; }
let in_join = join_cols_needed.iter().any(|jc| jc == *c);
let in_parent = needed_set.as_ref()
.map(|ns| ns.contains(c.as_str()))
.unwrap_or(true);
in_join || in_parent
}).cloned().collect();
let right_needed: Vec<String> = right_out.iter().filter(|c| {
if c.ends_with(".*") { return true; }
let in_join = join_cols_needed.iter().any(|jc| jc == *c);
let in_parent = needed_set.as_ref()
.map(|ns| ns.contains(c.as_str()))
.unwrap_or(true);
in_join || in_parent
}).cloned().collect();
// Recurse into children with their needed sets
// Don't inject extra Project nodes — just recurse and let FilteredScan handle it
let left_child = Box::new(prune_columns_top_down(
*hj.left,
if left_needed.iter().any(|c| c.ends_with(".*")) { None } else { Some(&left_needed) }
));
let right_child = Box::new(prune_columns_top_down(
*hj.right,
if right_needed.iter().any(|c| c.ends_with(".*")) { None } else { Some(&right_needed) }
));
OptQueryOp::HashJoin(HashJoinData {
left: left_child,
right: right_child,
..hj
})
}
// KEY FIX: push needed columns directly into FilteredScan projection
OptQueryOp::FilteredScan(mut fs) => {
if let Some(needed_cols) = needed {
if fs.project.is_none() && !needed_cols.is_empty() {
// Build projection from what the scan outputs vs what's needed
let table_prefix = format!("{}.", fs.table_id);
let proj: Vec<(String, String)> = needed_cols.iter()
.filter(|c| {
c.starts_with(&table_prefix)
|| known_col_prefix(&fs.table_id, c)
})
.map(|c| (c.clone(), c.clone()))
.collect();
if !proj.is_empty() {
eprintln!("[OPT-26] FScan({}) pruned to {} cols (from needed={})",
fs.table_id, proj.len(), needed_cols.len());
fs.project = Some(proj);
}
}
}
OptQueryOp::FilteredScan(fs)
}
OptQueryOp::Filter(OptFilterData { predicates, underlying }) => {
let pred_cols: Vec<String> = predicates.iter().flat_map(|p| {
let mut v = vec![p.column_name.clone()];
if let ComparisionValue::Column(c) = &p.value { v.push(c.clone()); }
v
}).collect();
let extended: Option<Vec<String>> = needed.map(|n| {
let mut v = n.to_vec();
for c in &pred_cols { if !v.contains(c) { v.push(c.clone()); } }
v
});
OptQueryOp::Filter(OptFilterData {
predicates,
underlying: Box::new(prune_columns_top_down(*underlying, extended.as_deref())),
})
}
OptQueryOp::FilterCross(d) => OptQueryOp::FilterCross(FilterCrossData {
left: Box::new(prune_columns_top_down(*d.left, needed)),
right: Box::new(prune_columns_top_down(*d.right, needed)),
..d
}),
other => other,
}
}
pub fn optimise_with_ctx(op: QueryOp, ctx: &OptContext<'_>) -> OptQueryOp {
eprintln!("[OPT] start budget={}MB", ctx.memory_budget_bytes / (1024 * 1024));
let lowered = lower(op, ctx);
let fused = fuse_operators(lowered, ctx);
let cleaned = distribute_predicates_deep(fused, ctx);
let pushed = push_all_scalars_deep(cleaned, ctx);
let deduped = elide_redundant_projects(pushed);
let reordered = reorder_join_extra_preds(deduped, ctx);
// NEW: column pruning pass — trim wide join outputs
let pruned = prune_columns_top_down(reordered, None);
verify_scalar_pushdown(&pruned);
eprintln!("[OPT] final plan: {}", plan_summary(&pruned));
pruned
}
// ─────────────────────────────────────────────────────────────────────────────
// Pass 1: lower QueryOp → OptQueryOp
// ─────────────────────────────────────────────────────────────────────────────
fn lower(op: QueryOp, ctx: &OptContext<'_>) -> OptQueryOp {
match op {
QueryOp::Scan(d) => OptQueryOp::Scan(d),
QueryOp::Filter(FilterData { mut predicates, underlying }) => {
if queryop_contains_cross(underlying.as_ref()) {
let mut raw_leaves: Vec<QueryOp> = Vec::new();
collect_queryop_cross_leaves(*underlying, &mut raw_leaves, &mut predicates);
eprintln!("[OPT-03][FIX-CROSS-FLATTEN] {} relations, {} preds",
raw_leaves.len(), predicates.len());
let opt_leaves: Vec<OptQueryOp> = raw_leaves
.into_iter()
.map(|leaf| lower(leaf, ctx))
.collect();
return build_optimal_join(opt_leaves, predicates, ctx);
}
if let Some(tid) = scan_table_of_queryop(underlying.as_ref()) {
reorder_predicates_by_selectivity(&mut predicates, &tid, ctx);
}
push_filter_into(predicates, lower(*underlying, ctx), ctx)
}
QueryOp::Project(ProjectData { column_name_map, underlying }) =>
OptQueryOp::Project(OptProjectData {
column_name_map,
underlying: Box::new(lower(*underlying, ctx)),
}),
QueryOp::Cross(CrossData { left, right }) =>
OptQueryOp::Cross(OptCrossData {
left: Box::new(lower(*left, ctx)),
right: Box::new(lower(*right, ctx)),
}),
QueryOp::Sort(SortData { sort_specs, underlying }) => {
let child = lower(*underlying, ctx);
let already = subtree_is_ordered_on_specs(&child, &sort_specs, ctx);
if already {
eprintln!("[OPT-11] redundant sort on {:?}",
sort_specs.iter().map(|s| &s.column_name).collect::<Vec<_>>());
}
OptQueryOp::Sort(OptSortData {
sort_specs,
underlying: Box::new(child),
is_physically_ordered: already,
})
}
}
}
fn queryop_contains_cross(op: &QueryOp) -> bool {
match op {
QueryOp::Cross(_) => true,
QueryOp::Filter(FilterData { underlying, .. }) => queryop_contains_cross(underlying),
_ => false,
}
}
fn collect_queryop_cross_leaves(
op: QueryOp,
out: &mut Vec<QueryOp>,
preds: &mut Vec<Predicate>,
) {
match op {
QueryOp::Cross(CrossData { left, right }) => {
collect_queryop_cross_leaves(*left, out, preds);
collect_queryop_cross_leaves(*right, out, preds);
}
QueryOp::Filter(FilterData { predicates, underlying }) => {
match *underlying {
QueryOp::Cross(CrossData { left, right }) => {
preds.extend(predicates);
collect_queryop_cross_leaves(*left, out, preds);
collect_queryop_cross_leaves(*right, out, preds);
}
other => out.push(QueryOp::Filter(FilterData {
predicates,
underlying: Box::new(other),
})),
}
}
other => out.push(other),
}
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-01] push_filter_into
// ─────────────────────────────────────────────────────────────────────────────
fn push_filter_into(
predicates: Vec<Predicate>,
child: OptQueryOp,
ctx: &OptContext<'_>,
) -> OptQueryOp {
if predicates.is_empty() { return child; }
match child {
// [OPT-03][FIX-CROSS-OOM] Cross + Filter → optimal join tree.
OptQueryOp::Cross(OptCrossData { left, right }) =>
fuse_filter_cross(predicates, left, right, ctx),
// [OPT-25] Filter above HashJoin: try to absorb into extra_preds.
OptQueryOp::HashJoin(mut hj) => {
let mut leftover = Vec::new();
for pred in predicates {
if let ComparisionValue::Column(rhs) = &pred.value {
if (tree_has_col(&hj.left, &pred.column_name) && tree_has_col(&hj.right, rhs))
|| (tree_has_col(&hj.left, rhs) && tree_has_col(&hj.right, &pred.column_name))
{
hj.extra_preds.push(pred);
continue;
}
}
leftover.push(pred);
}
let base = OptQueryOp::HashJoin(hj);
if leftover.is_empty() { base }
else { OptQueryOp::Filter(OptFilterData { predicates: leftover, underlying: Box::new(base) }) }
}
other => OptQueryOp::Filter(OptFilterData {
predicates,
underlying: Box::new(other),
}),
}
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-03][FIX-CROSS-OOM] fuse_filter_cross
// ─────────────────────────────────────────────────────────────────────────────
fn fuse_filter_cross(
predicates: Vec<Predicate>,
left: Box<OptQueryOp>,
right: Box<OptQueryOp>,
ctx: &OptContext<'_>,
) -> OptQueryOp {
let mut leaves = Vec::new();
let mut extra_preds = predicates;
collect_cross_leaves(*left, &mut leaves, &mut extra_preds);
collect_cross_leaves(*right, &mut leaves, &mut extra_preds);
eprintln!("[OPT-03] Cross+Filter: {} relations, {} preds", leaves.len(), extra_preds.len());
build_optimal_join(leaves, extra_preds, ctx)
}
/// [FIX-CROSS-OOM] Flatten Cross nodes and recurse through Filter(Cross)
/// wrappers, extracting their predicates into the global pool.
fn collect_cross_leaves(
op: OptQueryOp,
out: &mut Vec<OptQueryOp>,
extra_preds: &mut Vec<Predicate>,
) {
match op {
OptQueryOp::Cross(OptCrossData { left, right }) => {
collect_cross_leaves(*left, out, extra_preds);
collect_cross_leaves(*right, out, extra_preds);
}
OptQueryOp::Filter(OptFilterData { predicates, underlying }) => {
match *underlying {
OptQueryOp::Cross(OptCrossData { left, right }) => {
extra_preds.extend(predicates);
collect_cross_leaves(*left, out, extra_preds);
collect_cross_leaves(*right, out, extra_preds);
}
other => out.push(OptQueryOp::Filter(OptFilterData {
predicates,
underlying: Box::new(other),
})),
}
}
other => out.push(other),
}
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-03][OPT-14][FIX-CROSS-OOM][FIX-ALIAS-COL] build_optimal_join
// ─────────────────────────────────────────────────────────────────────────────
fn build_optimal_join(
mut relations: Vec<OptQueryOp>,
mut predicates: Vec<Predicate>,
ctx: &OptContext<'_>,
) -> OptQueryOp {
if relations.is_empty() { panic!("build_optimal_join: no relations"); }
if relations.len() == 1 {
let rel = relations.remove(0);
return if predicates.is_empty() { rel }
else {
let mut scalar: Vec<Predicate> = Vec::new();
let mut col_col: Vec<Predicate> = Vec::new();
for p in predicates {
if matches!(&p.value, ComparisionValue::Column(_)) { col_col.push(p); }
else { scalar.push(p); }
}
let mut result = rel;
for p in scalar { push_scalar_into_rel(&mut result, p); }
if col_col.is_empty() { result }
else {
OptQueryOp::Filter(OptFilterData {
predicates: col_col,
underlying: Box::new(result),
})
}
};
}
// [OPT-01][FIX-ALIAS-COL] Push scalar predicates into the owning relation.
let mut leftover: Vec<Predicate> = Vec::new();
'pred: for pred in predicates.drain(..) {
if matches!(&pred.value, ComparisionValue::Column(_)) {
leftover.push(pred);
continue;
}
for rel in &mut relations {
if tree_has_col(rel, &pred.column_name) {
push_scalar_into_rel(rel, pred);
continue 'pred;
}
}
leftover.push(pred);
}
predicates = leftover;
// [OPT-14] Stat-driven ordering: smallest estimated output first.
relations.sort_by_key(|r| estimated_rows_ctx(r, ctx));
eprintln!("[OPT-14] join order (stat): {}",
relations.iter()
.map(|r| format!("{}~{}", relation_name(r), estimated_rows_ctx(r, ctx)))
.collect::<Vec<_>>()
.join(" ⋈ "));
let mut current = relations.remove(0);
let mut remaining = relations;
while !remaining.is_empty() {
let mut best_idx = None;
let mut best_has_join = false;
let mut best_est = u64::MAX;
for (i, rel) in remaining.iter().enumerate() {
let has_join = predicates.iter().any(|p| {
if let ComparisionValue::Column(rhs) = &p.value {
(tree_has_col(¤t, &p.column_name) && tree_has_col(rel, rhs))
|| (tree_has_col(¤t, rhs) && tree_has_col(rel, &p.column_name))
} else { false }
});
let est = estimated_rows_ctx(rel, ctx);
let better = if has_join && !best_has_join {
true
} else if has_join == best_has_join {
est < best_est
} else {
false
};
if better { best_idx = Some(i); best_has_join = has_join; best_est = est; }
}
let next = remaining.remove(best_idx.unwrap_or(0));
let mut join_preds: Vec<Predicate> = Vec::new();
let mut rest_preds: Vec<Predicate> = Vec::new();
for pred in predicates.drain(..) {
if let ComparisionValue::Column(rhs) = &pred.value {
let lc = tree_has_col(¤t, &pred.column_name);
let ln = tree_has_col(&next, &pred.column_name);
let rc = tree_has_col(¤t, rhs);
let rn = tree_has_col(&next, rhs);
if (lc && rn) || (ln && rc) { join_preds.push(pred); continue; }
}
rest_preds.push(pred);
}
predicates = rest_preds;
current = build_join_node(join_preds, Box::new(current), Box::new(next), ctx);
}
if !predicates.is_empty() {
current = OptQueryOp::Filter(OptFilterData {
predicates,
underlying: Box::new(current),
});
}
current
}
/// [FIX-ALIAS-COL][FIX-SCALAR-PUSH-ALIAS] Push a scalar predicate into a relation.
fn push_scalar_into_rel(rel: &mut OptQueryOp, pred: Predicate) {
let dummy = OptQueryOp::Scan(ScanData { table_id: String::new() });
let old = std::mem::replace(rel, dummy);
*rel = match old {
OptQueryOp::Filter(mut f) => { f.predicates.push(pred); OptQueryOp::Filter(f) }
other => OptQueryOp::Filter(OptFilterData {
predicates: vec![pred],
underlying: Box::new(other),
}),
};
}
// ─────────────────────────────────────────────────────────────────────────────
// [OPT-03][OPT-07][OPT-10][OPT-17][FIX-CROSS-OOM][FIX-COMPOSITE-JOIN][FIX-NE-JOIN]
// build_join_node
// ─────────────────────────────────────────────────────────────────────────────
fn build_join_node(
join_preds: Vec<Predicate>,
left: Box<OptQueryOp>,
right: Box<OptQueryOp>,
ctx: &OptContext<'_>,
) -> OptQueryOp {
let left_est = estimated_rows_ctx(&left, ctx);
let right_est = estimated_rows_ctx(&right, ctx);
if join_preds.is_empty() {
let product_bytes = left_est.saturating_mul(right_est).saturating_mul(512);
if product_bytes > ctx.memory_budget_bytes as u64 * 4 {
eprintln!("[FIX-CROSS-OOM] no join pred, product={}×{}≈{} MB > 4×budget → FilterCross",
left_est, right_est, product_bytes / (1024 * 1024));
return OptQueryOp::FilterCross(FilterCrossData {
predicates: Vec::new(), left, right,
});
}
eprintln!("[OPT-03] tiny cross {}×{} → Cross", left_est, right_est);
return OptQueryOp::Cross(OptCrossData { left, right });
}
// Separate equi-predicates from non-equi.
let mut equi_preds: Vec<Predicate> = Vec::new();
let mut nonequi_preds: Vec<Predicate> = Vec::new();
for pred in join_preds {
let is_equi = pred.operator == ComparisionOperator::EQ
&& matches!(&pred.value, ComparisionValue::Column(_));
if is_equi { equi_preds.push(pred); }
else { nonequi_preds.push(pred); }
}
if !equi_preds.is_empty() {
let mut left_keys: Vec<String> = Vec::new();
let mut right_keys: Vec<String> = Vec::new();
let mut unresolved: Vec<Predicate> = Vec::new();