hawdb-optimizer-graph 0.27.0

An embedded Rust graph database for local data-plane workloads
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
// Copyright 2026 Nowledge
//
// 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.

use super::cardinality::{
    estimate_aggregate_rows, estimate_aggregate_work_rows, estimate_filter_rows,
    estimate_full_text_rows, estimate_optional_degree_work, PlanBindings, StatisticsUsage,
};
use super::{OptimizerCatalog, PhysicalPlan, PlanCost, PlanCostBreakdown};
use hawdb_core::Value;
use hawdb_cypher::RelationshipDirection;
use hawdb_plan_cypher::{
    CompositeRangeSeek, ExactPropertySeekBranch, NodeProjectionAccess, PlanChildren,
    ProjectionExpression, RelationshipCountLeg,
};
use std::collections::BTreeMap;

mod row_goal;
mod shape;
mod width;
mod work;

pub(super) const NODE_INDEX_EQ_STARTUP_COST: u64 = 1;
pub(super) const NODE_INDEX_RANGE_STARTUP_COST: u64 = 2;
pub(super) const NODE_INDEX_TEXT_STARTUP_COST: u64 = 3;

const NODE_FULL_SCAN_STARTUP_COST: u64 = 4;
/// Labels at or below this size deliberately prefer scans over scalar indexes.
/// Plan caches can track this cost class using maintained counts alone.
pub const NODE_INDEX_SMALL_LABEL_SCAN_THRESHOLD: u64 = 8;
const VECTOR_SEED_TOTAL_COST_PER_ROW: u64 = 10;

#[cfg(test)]
thread_local! {
    static COST_EVALUATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
pub(super) fn take_cost_evaluations() -> usize {
    COST_EVALUATIONS.with(|count| count.replace(0))
}

pub(super) fn estimate_node_cartesian_product_cost(
    left_cost: PlanCost,
    right_cost: PlanCost,
) -> PlanCost {
    combine_node_cartesian_product_cost(
        PlanCostBreakdown::from_scalar(left_cost),
        PlanCostBreakdown::from_scalar(right_cost),
    )
    .as_plan_cost()
}

fn combine_node_cartesian_product_cost(
    left_cost: PlanCostBreakdown,
    right_cost: PlanCostBreakdown,
) -> PlanCostBreakdown {
    let rows = left_cost
        .estimated_rows
        .saturating_mul(right_cost.estimated_rows)
        .max(1);
    PlanCostBreakdown::combine_with_cpu(left_cost, right_cost, rows, rows, 0)
}

pub(super) fn estimate_node_full_scan_cost(label_count: u64) -> u64 {
    node_full_scan_work(label_count).cost
}

pub(super) fn estimate_node_index_seek_cost(estimated_rows: u64, startup_cost: u64) -> u64 {
    node_index_seek_work(estimated_rows, startup_cost).cost
}

fn node_full_scan_work(rows: u64) -> PlanCostBreakdown {
    PlanCostBreakdown::new(
        rows,
        0,
        0,
        rows.saturating_add(NODE_FULL_SCAN_STARTUP_COST),
        0,
    )
}

fn node_index_seek_work(rows: u64, startup: u64) -> PlanCostBreakdown {
    // Locating a candidate and materializing it are distinct work components.
    // Both access ranking and final costing consume this unweighted breakdown.
    PlanCostBreakdown::new(rows, rows, rows.saturating_add(startup), 0, 0)
}

fn projected_access_cost(
    access: &NodeProjectionAccess,
    label: &str,
    catalog: &OptimizerCatalog,
) -> PlanCostBreakdown {
    match access {
        NodeProjectionAccess::LabelScan => {
            let rows = catalog.label_count(label).max(1);
            node_full_scan_work(rows)
        }
        NodeProjectionAccess::PropertyValues { property, values } => {
            let rows = if values.len() == 1 {
                catalog.estimate_property_index_eq_rows(label, property)
            } else {
                catalog.estimate_property_index_in_rows(label, property, values.len() as u64)
            }
            .max(1);
            node_index_seek_work(rows, values.len().max(1) as u64)
        }
        NodeProjectionAccess::PropertyUnion { branches } => {
            exact_property_union_cost(branches, label, catalog)
        }
        NodeProjectionAccess::CompositeEquality { predicates } => {
            let properties = predicates
                .iter()
                .map(|(property, _)| property.clone())
                .collect::<Vec<_>>();
            let rows = catalog
                .estimate_composite_property_index_rows(label, &properties)
                .max(1);
            node_index_seek_work(rows, predicates.len().max(1) as u64)
        }
        NodeProjectionAccess::CompositeRange { seek } => composite_range_cost(seek, label, catalog),
        NodeProjectionAccess::CompositeOrdered { seek } => {
            let distinct = seek
                .equality_prefix
                .iter()
                .fold(1u64, |count, (property, _)| {
                    count.saturating_mul(catalog.distinct_count(label, property).max(1))
                });
            let rows = catalog.label_count(label).div_ceil(distinct).max(1);
            node_index_seek_work(rows, seek.equality_prefix.len() as u64)
        }
        NodeProjectionAccess::PropertyRange {
            property,
            lower,
            upper,
        } => {
            let rows = catalog
                .estimate_range_bounds_rows(label, property, lower.as_ref(), upper.as_ref())
                .max(1);
            node_index_seek_work(rows, NODE_INDEX_RANGE_STARTUP_COST)
        }
        NodeProjectionAccess::FullText { .. } => {
            let rows = estimate_full_text_rows(catalog.label_count(label));
            node_index_seek_work(rows, NODE_INDEX_TEXT_STARTUP_COST)
        }
    }
}

fn composite_range_cost(
    seek: &CompositeRangeSeek,
    label: &str,
    catalog: &OptimizerCatalog,
) -> PlanCostBreakdown {
    let equality_properties = seek
        .equality_prefix
        .iter()
        .map(|(property, _)| property.clone())
        .collect::<Vec<_>>();
    let rows = catalog.estimate_composite_prefix_range_rows(
        label,
        &seek.index_properties,
        &equality_properties,
        &seek.range_property,
        seek.lower.as_ref(),
        seek.upper.as_ref(),
    );
    node_index_seek_work(rows, seek.equality_prefix.len().saturating_add(1) as u64)
}

fn exact_property_union_cost(
    branches: &[ExactPropertySeekBranch],
    label: &str,
    catalog: &OptimizerCatalog,
) -> PlanCostBreakdown {
    let mut rows = 0u64;
    let mut cpu = 0u64;
    let mut random_io = 0u64;
    for branch in branches {
        let branch_rows = catalog.estimate_property_index_in_rows(
            label,
            &branch.property,
            branch.values.len() as u64,
        );
        rows = rows.saturating_add(branch_rows);
        let work = node_index_seek_work(branch_rows, branch.values.len().max(1) as u64);
        cpu = cpu.saturating_add(work.cpu);
        random_io = random_io.saturating_add(work.random_io);
    }
    PlanCostBreakdown::new(rows.min(catalog.label_count(label)), cpu, random_io, 0, 0)
}

pub(super) fn node_index_seek_is_cheaper(label_count: u64, seek_cost: u64) -> bool {
    label_count > NODE_INDEX_SMALL_LABEL_SCAN_THRESHOLD
        && seek_cost <= estimate_node_full_scan_cost(label_count)
}

/// Shares the equality access-cost boundary with query-local plan cache keys.
#[doc(hidden)]
pub fn node_equality_index_seek_is_cheaper(label_count: u64, matched_rows: u64) -> bool {
    node_index_seek_is_cheaper(
        label_count,
        estimate_node_index_seek_cost(matched_rows.max(1), NODE_INDEX_EQ_STARTUP_COST),
    )
}

pub(super) fn estimate_physical_plan_cost(
    plan: &PhysicalPlan,
    catalog: &OptimizerCatalog,
) -> PlanCost {
    estimate_physical_plan_cost_breakdown(plan, catalog).as_plan_cost()
}

pub(super) fn estimate_physical_plan_cost_with_context(
    plan: &PhysicalPlan,
    catalog: &OptimizerCatalog,
    context: &crate::OptimizerContext,
) -> PlanCost {
    estimate_costed_plan_with_context(plan, catalog, context)
        .cost
        .as_plan_cost()
}

fn estimate_costed_plan_with_context<'a>(
    plan: &'a PhysicalPlan,
    catalog: &OptimizerCatalog,
    context: &crate::OptimizerContext,
) -> CostedPlan<'a> {
    let inputs = estimate_input_costs(plan, |input| {
        estimate_costed_plan_with_context(input, catalog, context)
    });
    estimate_operator_cost_with_context(plan, catalog, inputs, context)
}

pub(super) fn estimate_physical_plan_cost_breakdown(
    plan: &PhysicalPlan,
    catalog: &OptimizerCatalog,
) -> PlanCostBreakdown {
    estimate_costed_plan(plan, catalog).cost
}

pub(super) fn estimate_physical_plan_cost_with_row_goal(
    plan: &PhysicalPlan,
    catalog: &OptimizerCatalog,
    context: &crate::OptimizerContext,
    rows: u64,
) -> PlanCost {
    let costed = estimate_costed_plan_with_context(plan, catalog, context);
    row_goal::ConsumptionCost {
        total: costed.cost,
        startup: costed.startup,
    }
    .prefix(rows)
    .as_plan_cost()
}

pub(super) struct CostedPlan<'a> {
    pub(super) cost: PlanCostBreakdown,
    startup: PlanCostBreakdown,
    shape: shape::RowShape<'a>,
    width_report: Option<work::WidthReport>,
    pub(super) statistics: Option<StatisticsUsage>,
    bindings: PlanBindings<'a>,
}

impl CostedPlan<'_> {
    pub(super) fn width_diagnostic(&self, ordinal: usize, plan: &PhysicalPlan) -> Option<String> {
        self.width_report.map(|width| format!(
            "physical width cost: operator={} ordinal={ordinal} row_bytes={} retained_bytes={} comparison_work={} spill_work={} memory_hint={:?} proxy_fields={} sampled_values={} units=logical_estimates",
            plan.kind().as_str(), width.row_bytes, width.retained_bytes,
            width.comparison_work, width.spill_work, width.memory_hint,
            width.proxy_fields, width.sampled_values,
        ))
    }
}

fn estimate_costed_plan<'a>(plan: &'a PhysicalPlan, catalog: &OptimizerCatalog) -> CostedPlan<'a> {
    let inputs = estimate_input_costs(plan, |input| estimate_costed_plan(input, catalog));
    estimate_operator_cost(plan, catalog, inputs)
}

// Keep the cost formulas fixed while tests substitute the original recursive
// metadata queries for the production fold.
#[cfg(test)]
pub(super) fn estimate_cost_with_test_bindings<'a>(
    plan: &'a PhysicalPlan,
    catalog: &OptimizerCatalog,
    bindings: &impl Fn(&'a PhysicalPlan) -> PlanBindings<'a>,
) -> PlanCostBreakdown {
    fn visit<'a>(
        plan: &'a PhysicalPlan,
        catalog: &OptimizerCatalog,
        bindings: &impl Fn(&'a PhysicalPlan) -> PlanBindings<'a>,
    ) -> CostedPlan<'a> {
        let inputs = estimate_input_costs(plan, |input| visit(input, catalog, bindings));
        estimate_operator_cost_internal(plan, catalog, inputs, Some(bindings(plan)), None)
    }
    visit(plan, catalog, bindings).cost
}

// Finish the child traversal before entering the large operator-cost match, so
// its stack frame does not accumulate with plan depth in unoptimized builds.
pub(super) fn estimate_input_costs<'a, T>(
    plan: &'a PhysicalPlan,
    mut visit: impl FnMut(&'a PhysicalPlan) -> T,
) -> [Option<T>; 2] {
    match plan.children() {
        PlanChildren::None => [None, None],
        PlanChildren::Unary(input) => [Some(visit(input)), None],
        PlanChildren::Binary(left, right) => [Some(visit(left)), Some(visit(right))],
    }
}

pub(super) fn estimate_operator_cost<'a>(
    plan: &'a PhysicalPlan,
    catalog: &OptimizerCatalog,
    inputs: [Option<CostedPlan<'a>>; 2],
) -> CostedPlan<'a> {
    estimate_operator_cost_internal(plan, catalog, inputs, None, None)
}

pub(super) fn estimate_operator_cost_with_context<'a>(
    plan: &'a PhysicalPlan,
    catalog: &OptimizerCatalog,
    inputs: [Option<CostedPlan<'a>>; 2],
    context: &crate::OptimizerContext,
) -> CostedPlan<'a> {
    estimate_operator_cost_internal(
        plan,
        catalog,
        inputs,
        None,
        context.resource_hints().max_memory_bytes,
    )
}

fn estimate_operator_cost_internal<'a>(
    plan: &'a PhysicalPlan,
    catalog: &OptimizerCatalog,
    mut inputs: [Option<CostedPlan<'a>>; 2],
    bindings_override: Option<PlanBindings<'a>>,
    memory: Option<u64>,
) -> CostedPlan<'a> {
    let consumption_inputs = inputs.each_ref().map(|input| {
        input.as_ref().map(|input| row_goal::ConsumptionCost {
            total: input.cost,
            startup: input.startup,
        })
    });
    let costs = row_goal::input_costs(plan, consumption_inputs);
    let mut statistics = None;
    let aggregate_cost = if matches!(plan, PhysicalPlan::AggregateExec { .. }) {
        Some(estimate_local_operator_cost(
            plan,
            catalog,
            costs,
            &inputs[0].as_ref().expect("unary input").bindings,
            &mut statistics,
        ))
    } else {
        None
    };
    let input_row_bytes = inputs.each_ref().map(|input| {
        input
            .as_ref()
            .map_or(0, |input| input.shape.retained_bytes())
    });
    let shapes = inputs
        .each_mut()
        .map(|input| input.as_mut().map(|input| std::mem::take(&mut input.shape)));
    let shape = shape::RowShape::for_operator(
        plan,
        catalog,
        shapes,
        inputs[0].as_ref().map(|input| &input.bindings),
    );
    let bindings = bindings_override.unwrap_or_else(|| {
        PlanBindings::for_operator(plan, inputs.map(|input| input.map(|input| input.bindings)))
    });
    let cost = aggregate_cost.unwrap_or_else(|| {
        estimate_local_operator_cost(plan, catalog, costs, &bindings, &mut statistics)
    });
    let (cost, width_report) = work::apply(
        plan,
        catalog,
        work::Inputs {
            costs,
            row_bytes: input_row_bytes,
        },
        &shape,
        &bindings,
        cost,
        memory,
    );
    // Width/decode/spill work participates in startup as well as total work.
    // In particular, a LIMIT must never discount a blocking operator's spill.
    let consumption = row_goal::cost_operator(plan, consumption_inputs, cost);
    CostedPlan {
        cost: consumption.total,
        startup: consumption.startup,
        shape,
        width_report,
        statistics,
        bindings,
    }
}

/// The step indexes before which `GraphMatchExec` evaluates WHERE conjuncts;
/// `steps.len()` stands for the end of the match.
fn graph_match_filter_points(
    program: &hawdb_plan_cypher::GraphMatchProgram,
) -> std::collections::BTreeSet<usize> {
    if program.predicate.is_none() {
        return std::collections::BTreeSet::new();
    }
    if program.predicate_steps.is_empty() {
        return std::collections::BTreeSet::from([program.steps.len()]);
    }
    program.predicate_steps.iter().copied().collect()
}

fn estimate_local_operator_cost(
    plan: &PhysicalPlan,
    catalog: &OptimizerCatalog,
    inputs: [Option<PlanCostBreakdown>; 2],
    bindings: &PlanBindings<'_>,
    statistics: &mut Option<StatisticsUsage>,
) -> PlanCostBreakdown {
    #[cfg(test)]
    COST_EVALUATIONS.with(|count| count.set(count.get() + 1));
    match plan {
        PhysicalPlan::EmptyExec => PlanCostBreakdown::new(1, 0, 0, 0, 0),
        PhysicalPlan::NodeCountExec { .. } | PhysicalPlan::RelationshipCountExec { .. } => {
            PlanCostBreakdown::new(1, 1, 0, 0, 0)
        }
        PhysicalPlan::UnwindExec { rows, .. } => {
            let count = rows.len() as u64;
            PlanCostBreakdown::new(count.max(1), count, 0, 0, 0)
        }
        PhysicalPlan::UnwindRowsExec { expression, .. } => {
            let input = inputs[0].expect("unary input cost");
            let width = match expression {
                ProjectionExpression::List(values) => values.len() as u64,
                ProjectionExpression::Literal(Value::List(values)) => values.len() as u64,
                ProjectionExpression::Literal(Value::Null) => 0,
                _ => 10,
            };
            let rows = input.estimated_rows.saturating_mul(width);
            input.with_cpu(input.estimated_rows.saturating_add(rows), rows, 0)
        }
        PhysicalPlan::UnwindMutation { rows, .. } => {
            let row_count = rows.len().max(1) as u64;
            PlanCostBreakdown::new(row_count, row_count, 0, 0, 0)
        }
        // File contents are unknown until execution; no plan alternative
        // competes with the single CSV source, so its cost is nominal.
        PhysicalPlan::LoadCsvMutation { .. } | PhysicalPlan::LoadCsvExec { .. } => {
            PlanCostBreakdown::new(1, 1, 0, 0, 0)
        }
        PhysicalPlan::SeqNodeScan { label, .. } => {
            let rows = catalog.label_count(label);
            node_full_scan_work(rows)
        }
        PhysicalPlan::RelationshipSeededNodeScan {
            label,
            rel_type,
            rel_properties,
            ..
        } => {
            // Seeds are distinct endpoints of the matching relationships, at
            // most the label's nodes; each one is an index-located point read.
            let matching = catalog
                .estimate_expand_rows(label, rel_type, rel_properties, "", 1, 1)
                .estimated_rows;
            let rows = matching.min(catalog.label_count(label));
            node_index_seek_work(rows, NODE_INDEX_EQ_STARTUP_COST)
        }
        PhysicalPlan::NodeProjectionScanExec {
            label,
            access,
            predicate,
            items,
            ..
        } => {
            let access_cost = projected_access_cost(access, label, catalog);
            let input_rows = access_cost.estimated_rows;
            let rows = predicate.as_ref().map_or(input_rows, |predicate| {
                estimate_filter_rows(predicate, plan, input_rows, catalog, bindings, statistics)
                    .max(1)
            });
            let cpu_rows = if !items.is_empty() || predicate.is_some() {
                rows
            } else {
                0
            };
            access_cost.with_cpu(rows, cpu_rows, 0)
        }
        PhysicalPlan::SourceSegmentScan { .. } => {
            let rows = catalog.label_count("Source");
            // Persisted segment summaries add bounded range I/O before the
            // sequential candidate scan.
            PlanCostBreakdown::new(rows, 0, NODE_FULL_SCAN_STARTUP_COST, rows, 0)
        }
        PhysicalPlan::GraphSeedScan { label, top_k, .. } => {
            let scanned = catalog.label_count(label);
            let rows = scanned.min(*top_k as u64);
            // Canonical relevance scans the label, including rejected candidates;
            // candidate TopK is an output bound, not a work estimate.
            PlanCostBreakdown::new(
                rows,
                scanned.saturating_mul(7),
                0,
                scanned.saturating_add(NODE_FULL_SCAN_STARTUP_COST),
                rows,
            )
        }
        PhysicalPlan::TextSeedScan { top_k, .. } => {
            let rows = *top_k as u64;
            // Output-transfer floor for an opaque external producer. The window
            // bounds output, not posting/corpus work; reader work is separate.
            PlanCostBreakdown::new(rows, rows, 0, 0, rows)
        }
        PhysicalPlan::VectorSeedScan { vector_plan, .. } => {
            let rows = vector_top_k(vector_plan) as u64;
            let total_cost = rows.saturating_mul(VECTOR_SEED_TOTAL_COST_PER_ROW).max(1);
            PlanCostBreakdown::new(rows, total_cost.saturating_sub(rows), 0, 0, rows)
        }
        PhysicalPlan::VectorIndexScan(scan) => {
            let rows = scan.top_k as u64;
            let upstream = inputs[0];
            let domain = upstream.map_or(scan.candidate_limit as u64, |cost| cost.estimated_rows);
            let work = domain.saturating_mul(VECTOR_SEED_TOTAL_COST_PER_ROW);
            upstream.map_or_else(
                || PlanCostBreakdown::new(rows, work, 0, 0, rows),
                |cost| cost.with_cpu(rows, work, rows),
            )
        }
        PhysicalPlan::HashJoinExec {
            left_key,
            right_key,
            ..
        } => {
            let left = inputs[0].expect("left input cost");
            let right = inputs[1].expect("right input cost");
            // Hash one key exactly as execution does. Additional equalities
            // remain residual work over this intermediate, even when joint
            // statistics estimate fewer final rows.
            let rows = super::cardinality::estimate_hash_join_rows(
                left_key,
                right_key,
                left.estimated_rows,
                right.estimated_rows,
                catalog,
                bindings,
                statistics,
            );
            let work = left
                .estimated_rows
                .saturating_add(right.estimated_rows)
                .saturating_add(rows);
            PlanCostBreakdown::combine_with_cpu(left, right, rows, work, 0)
        }
        PhysicalPlan::NodeCartesianProductExec { .. } => {
            let left_cost = inputs[0].expect("left input cost");
            let right_cost = inputs[1].expect("right input cost");
            combine_node_cartesian_product_cost(left_cost, right_cost)
        }
        PhysicalPlan::GraphMatchExec { program, .. } => {
            let base = inputs[0].unwrap_or_else(|| PlanCostBreakdown::new(1, 0, 0, 0, 0));
            let mut rows = base.estimated_rows;
            let mut output_rows = rows;
            let mut work = rows;
            // Steps run as a per-row nested loop in plan order. A step that
            // binds a fresh node multiplies the rows by its label; a step that
            // reaches an imported or already-bound node only filters them. The
            // output estimate is therefore order-independent, while the work
            // (the sum of intermediate rows) reflects the anchored order.
            let mut bound = std::collections::BTreeSet::new();
            // Each group of WHERE conjuncts keeps a default fraction of the
            // rows at the point it runs, so later steps expand fewer rows.
            let filter_points = graph_match_filter_points(program);
            let filter = |index: usize, rows: u64| {
                if filter_points.contains(&index) {
                    rows.div_ceil(crate::cardinality_defaults::FILTER_SELECTIVITY_DIVISOR)
                        .max(1)
                } else {
                    rows
                }
            };
            for (index, step) in program.steps.iter().enumerate() {
                rows = filter(index, rows);
                let node = match step {
                    hawdb_plan_cypher::GraphMatchStep::Node(node) => node,
                    hawdb_plan_cypher::GraphMatchStep::Expand { target, .. } => target,
                    // A search may visit every relationship of its type for
                    // each endpoint pair; it keeps the row count of its input.
                    hawdb_plan_cypher::GraphMatchStep::ShortestPath(step) => {
                        work = work.saturating_add(rows.saturating_mul(
                            catalog.traversable_relationship_count(&step.rel_type),
                        ));
                        continue;
                    }
                };
                let newly_bound =
                    bound.insert(&node.variable) && program.introduced.contains(&node.variable);
                if newly_bound {
                    let multiplier = catalog.label_count(&node.label).max(1);
                    rows = rows.saturating_mul(multiplier);
                    output_rows = output_rows.saturating_mul(multiplier);
                }
                work = work.saturating_add(rows);
            }
            // Placement changes intermediate work, not the selectivity of
            // the complete WHERE. Apply that output estimate only once.
            if program.predicate.is_some() {
                output_rows = output_rows
                    .div_ceil(crate::cardinality_defaults::FILTER_SELECTIVITY_DIVISOR)
                    .max(1);
            }
            base.with_random_io(output_rows, work, 0)
        }
        PhysicalPlan::NodeColumnLookupExec { label, .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            let label_rows = catalog.label_count(label).max(1);
            input_cost.with_random_io(
                input_cost.estimated_rows.max(1),
                input_cost.estimated_rows.saturating_mul(label_rows),
                0,
            )
        }
        PhysicalPlan::IndexNodeSeek {
            label, property, ..
        } => {
            let rows = catalog.estimate_property_index_eq_rows(label, property);
            node_index_seek_work(rows, NODE_INDEX_EQ_STARTUP_COST)
        }
        PhysicalPlan::IndexNodeMultiSeek {
            label,
            property,
            values,
            ..
        } => {
            let rows =
                catalog.estimate_property_index_in_rows(label, property, values.len() as u64);
            node_index_seek_work(rows, values.len() as u64)
        }
        PhysicalPlan::IndexNodeUnionSeek {
            label, branches, ..
        } => exact_property_union_cost(branches, label, catalog),
        PhysicalPlan::IndexNodeCompositeSeek {
            label, predicates, ..
        } => {
            let properties = predicates
                .iter()
                .map(|(property, _)| property.clone())
                .collect::<Vec<_>>();
            let rows = catalog.estimate_composite_property_index_rows(label, &properties);
            node_index_seek_work(rows, predicates.len() as u64)
        }
        PhysicalPlan::IndexNodeCompositeRangeSeek { label, seek, .. } => {
            composite_range_cost(seek, label, catalog)
        }
        PhysicalPlan::IndexNodeRangeSeek {
            label,
            property,
            lower,
            upper,
            ..
        } => {
            let rows =
                catalog.estimate_range_bounds_rows(label, property, lower.as_ref(), upper.as_ref());
            node_index_seek_work(rows, NODE_INDEX_RANGE_STARTUP_COST)
        }
        PhysicalPlan::IndexNodeTextSeek { label, .. } => {
            let rows = estimate_full_text_rows(catalog.label_count(label));
            node_index_seek_work(rows, NODE_INDEX_TEXT_STARTUP_COST)
        }
        PhysicalPlan::AdjacencyExpandExec {
            source_label,
            rel_type,
            rel_properties,
            target_label,
            min_hops,
            max_hops,
            input,
            ..
        } => {
            let input_cost = inputs[0].expect("unary input cost");
            let expand_estimate = catalog.estimate_expand_rows(
                source_label,
                rel_type,
                rel_properties,
                target_label,
                *min_hops,
                *max_hops,
            );
            let source_rows = catalog.label_count(source_label).max(1);
            // Seeded sources already are the matching relationships' endpoints,
            // so the expand yields its whole-label estimate, not a fraction.
            let scaled_rows = if matches!(**input, PhysicalPlan::RelationshipSeededNodeScan { .. })
            {
                expand_estimate.estimated_rows.max(1)
            } else {
                expand_estimate
                    .estimated_rows
                    .saturating_mul(input_cost.estimated_rows.max(1))
                    .div_ceil(source_rows)
                    .max(1)
            };
            input_cost.with_random_io(
                scaled_rows,
                input_cost.estimated_rows.saturating_add(scaled_rows),
                0,
            )
        }
        PhysicalPlan::AdjacencyExistsExec { .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            input_cost.with_random_io(input_cost.estimated_rows, input_cost.estimated_rows, 0)
        }
        PhysicalPlan::FilterExec { predicate, input } => {
            let input_cost = inputs[0].expect("unary input cost");
            let rows = estimate_filter_rows(
                predicate,
                input,
                input_cost.estimated_rows,
                catalog,
                bindings,
                statistics,
            );
            input_cost.with_cpu(rows, input_cost.estimated_rows, 0)
        }
        PhysicalPlan::ProjectExec { .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            input_cost.with_cpu(input_cost.estimated_rows, input_cost.estimated_rows, 0)
        }
        PhysicalPlan::OptionalDegreeExec {
            rel_type,
            rel_properties,
            direction,
            target_label,
            target_properties,
            ..
        } => {
            let input_cost = inputs[0].expect("unary input cost");
            let degree_work = estimate_optional_degree_work(
                rel_type,
                rel_properties,
                *direction,
                target_label,
                target_properties,
                catalog,
            );
            input_cost.with_random_io(
                input_cost.estimated_rows,
                input_cost.estimated_rows.saturating_mul(degree_work),
                0,
            )
        }
        PhysicalPlan::OptionalRelationshipCountSumExec {
            label,
            properties,
            legs,
            ..
        } => {
            let scalar =
                estimate_optional_relationship_count_sum(label, properties, legs, catalog).cost;
            PlanCostBreakdown::from_scalar(scalar)
        }
        PhysicalPlan::ThreadRepairStatsExec { .. } => PlanCostBreakdown::new(1, 32, 0, 0, 0),
        PhysicalPlan::ShortestPathExec { max_hops, .. } => PlanCostBreakdown::new(
            1,
            0,
            (*max_hops as u64).saturating_mul(8).saturating_add(4),
            0,
            0,
        ),
        PhysicalPlan::AggregateExec {
            group_keys, items, ..
        } => {
            let input_cost = inputs[0].expect("unary input cost");
            let rows = estimate_aggregate_rows(
                group_keys,
                bindings,
                input_cost.estimated_rows,
                catalog,
                statistics,
            );
            let work_rows =
                estimate_aggregate_work_rows(items, bindings, input_cost.estimated_rows, catalog);
            input_cost.with_cpu(rows, work_rows, 0)
        }
        PhysicalPlan::DistinctExec { .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            input_cost.with_cpu(input_cost.estimated_rows, input_cost.estimated_rows, 0)
        }
        PhysicalPlan::SortExec { .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            input_cost.with_cpu(
                input_cost.estimated_rows,
                input_cost.estimated_rows.saturating_mul(2),
                0,
            )
        }
        PhysicalPlan::TopNExec { offset, limit, .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            let retained_rows =
                (offset.saturating_add(*limit) as u64).min(input_cost.estimated_rows);
            let rows = input_cost
                .estimated_rows
                .saturating_sub(*offset as u64)
                .min(*limit as u64);
            let heap_depth = retained_rows.max(2).ilog2().max(1) as u64;
            let selection_cost = input_cost
                .estimated_rows
                .saturating_add(retained_rows.saturating_mul(heap_depth));
            input_cost.with_cpu(rows, selection_cost, 0)
        }
        PhysicalPlan::LimitExec { offset, limit, .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            let remaining_rows = input_cost.estimated_rows.saturating_sub(*offset as u64);
            let rows = limit
                .map(|limit| remaining_rows.min(limit as u64))
                .unwrap_or(remaining_rows)
                .max(1);
            input_cost.with_cpu(rows, rows, 0)
        }
        PhysicalPlan::ScoringProgramExec {
            program,
            limit,
            seed_graph_input,
            ..
        } => {
            let input_cost = inputs[0].expect("unary input cost");
            let retained_rows = (*limit as u64).min(input_cost.estimated_rows);
            let heap_depth = retained_rows.max(2).ilog2().max(1) as u64;
            let spec = program.specification();
            let feature_work = (spec.terms.len().saturating_add(spec.decay.len()) as u64)
                .saturating_add(if seed_graph_input.is_some() { 2 } else { 0 });
            let evaluation_cost = input_cost
                .estimated_rows
                .saturating_mul(feature_work)
                .saturating_add(retained_rows.saturating_mul(heap_depth));
            input_cost.with_cpu(retained_rows, evaluation_cost, 0)
        }
        PhysicalPlan::HostScoringExec { scoring, .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            let retained_rows = (scoring.limit() as u64).min(input_cost.estimated_rows);
            let heap_depth = retained_rows.max(2).ilog2().max(1) as u64;
            let evaluation_cost = input_cost
                .estimated_rows
                .saturating_mul(scoring.cpu_units_per_row().get())
                .saturating_add(retained_rows.saturating_mul(heap_depth));
            input_cost.with_cpu(retained_rows, evaluation_cost, 0)
        }
        PhysicalPlan::ScoringRerankExec { limit, .. } => {
            let input_cost = inputs[0].expect("unary input cost");
            let retained_rows = (*limit as u64).min(input_cost.estimated_rows);
            let heap_depth = retained_rows.max(2).ilog2().max(1) as u64;
            let evaluation_cost = input_cost
                .estimated_rows
                .saturating_add(retained_rows.saturating_mul(heap_depth));
            input_cost.with_cpu(retained_rows, evaluation_cost, 0)
        }
        PhysicalPlan::CreateNodeLabel { .. }
        | PhysicalPlan::CreateRelationshipType { .. }
        | PhysicalPlan::CreateNodeTable { .. }
        | PhysicalPlan::CreateRelationshipTable { .. }
        | PhysicalPlan::CreateProperty { .. }
        | PhysicalPlan::AlterTableState { .. }
        | PhysicalPlan::AlterPropertyState { .. }
        | PhysicalPlan::CreateIndex { .. }
        | PhysicalPlan::CreateCompositeIndex { .. }
        | PhysicalPlan::CreateRangeIndex { .. }
        | PhysicalPlan::CreateFullTextIndex { .. }
        | PhysicalPlan::CreateUniqueConstraint { .. }
        | PhysicalPlan::CreateNodePropertyExistsConstraint { .. }
        | PhysicalPlan::CreateRelationshipUniqueConstraint { .. }
        | PhysicalPlan::CreateRelationshipPropertyExistsConstraint { .. }
        | PhysicalPlan::ProjectGraph { .. }
        | PhysicalPlan::GraphAlgorithm { .. }
        | PhysicalPlan::GraphAlgorithmOutput(_)
        | PhysicalPlan::CreateNode { .. }
        | PhysicalPlan::MergeNode { .. }
        | PhysicalPlan::MergeRelationship { .. }
        | PhysicalPlan::MergeMatchedRelationship { .. }
        | PhysicalPlan::MergeRelationshipFromMatchedRelationship { .. }
        | PhysicalPlan::MergeRelationshipToMatchedTarget { .. }
        | PhysicalPlan::MergeRelationshipFromMatchedTarget { .. }
        | PhysicalPlan::CreateMatchedRelationship { .. }
        | PhysicalPlan::SetNodeProperty { .. }
        | PhysicalPlan::SetNodeProperties { .. }
        | PhysicalPlan::SetNodePropertiesReturn { .. }
        | PhysicalPlan::SetRelationshipProperty { .. }
        | PhysicalPlan::SetRelationshipProperties { .. }
        | PhysicalPlan::DeleteNode { .. }
        | PhysicalPlan::DeleteRelationship { .. }
        | PhysicalPlan::DeleteRelationshipTargetNodes { .. }
        | PhysicalPlan::CreateRelationship { .. } => PlanCostBreakdown::new(1, 1, 0, 0, 0),
    }
}

fn vector_top_k(plan: &hawdb_plan_cypher::VectorPhysicalPlan) -> usize {
    match plan {
        hawdb_plan_cypher::VectorPhysicalPlan::TopK { limit, .. } => *limit,
        _ => 1,
    }
}

pub(super) fn push_optional_relationship_count_sum_cost_decision(
    catalog: &OptimizerCatalog,
    decisions: &mut Vec<String>,
    label: &str,
    properties: &BTreeMap<String, Value>,
    legs: &[RelationshipCountLeg],
) {
    let estimate = estimate_optional_relationship_count_sum(label, properties, legs, catalog);
    let leg_rows = estimate
        .leg_rows
        .iter()
        .map(|leg| {
            format!(
                "{}:{}:{}",
                leg.rel_type,
                format_relationship_direction(leg.direction),
                leg.rows
            )
        })
        .collect::<Vec<_>>()
        .join(",");
    decisions.push(format!(
        "estimate OptionalRelationshipCountSum for {label}: seed_rows={} leg_rows=[{}] estimated_rows={} cost={}",
        estimate.seed_rows, leg_rows, estimate.cost.estimated_rows, estimate.cost.cost
    ));
}

struct OptionalRelationshipCountSumEstimate {
    seed_rows: u64,
    leg_rows: Vec<OptionalRelationshipCountLegEstimate>,
    cost: PlanCost,
}

struct OptionalRelationshipCountLegEstimate {
    rel_type: String,
    direction: RelationshipDirection,
    rows: u64,
}

fn estimate_optional_relationship_count_sum(
    label: &str,
    properties: &BTreeMap<String, Value>,
    legs: &[RelationshipCountLeg],
    catalog: &OptimizerCatalog,
) -> OptionalRelationshipCountSumEstimate {
    let seed_rows = estimate_seed_rows_from_properties(label, properties, catalog);
    let leg_rows = legs
        .iter()
        .map(|leg| OptionalRelationshipCountLegEstimate {
            rel_type: leg.rel_type.clone(),
            direction: leg.direction,
            rows: estimate_relationship_count_leg_rows(seed_rows, leg, catalog),
        })
        .collect::<Vec<_>>();
    let relationship_rows = leg_rows
        .iter()
        .map(|leg| leg.rows)
        .fold(0_u64, |acc, rows| acc.saturating_add(rows));
    let cost = PlanCost {
        estimated_rows: 1,
        cost: seed_rows
            .saturating_add(relationship_rows)
            .saturating_add(legs.len() as u64)
            .saturating_add(4),
    };
    OptionalRelationshipCountSumEstimate {
        seed_rows,
        leg_rows,
        cost,
    }
}

fn format_relationship_direction(direction: RelationshipDirection) -> &'static str {
    match direction {
        RelationshipDirection::Outgoing => "out",
        RelationshipDirection::Incoming => "in",
        RelationshipDirection::Undirected => "both",
    }
}

fn estimate_seed_rows_from_properties(
    label: &str,
    properties: &BTreeMap<String, Value>,
    catalog: &OptimizerCatalog,
) -> u64 {
    let label_rows = catalog.label_count(label).max(1);
    let distinct_product = properties
        .keys()
        .map(|property| catalog.distinct_count(label, property).max(1))
        .fold(1_u64, |acc, value| acc.saturating_mul(value))
        .max(1);
    label_rows.div_ceil(distinct_product).max(1)
}

fn estimate_relationship_count_leg_rows(
    seed_rows: u64,
    leg: &RelationshipCountLeg,
    catalog: &OptimizerCatalog,
) -> u64 {
    let rel_count = catalog
        .rel_type_counts
        .get(&leg.rel_type)
        .copied()
        .unwrap_or(1)
        .max(1);
    let source_count = catalog
        .rel_type_source_counts
        .get(&leg.rel_type)
        .copied()
        .unwrap_or(1)
        .max(1);
    let target_count = catalog
        .rel_type_target_counts
        .get(&leg.rel_type)
        .copied()
        .unwrap_or(1)
        .max(1);
    let per_seed = match leg.direction {
        RelationshipDirection::Outgoing => rel_count.div_ceil(source_count).max(1),
        RelationshipDirection::Incoming => rel_count.div_ceil(target_count).max(1),
        RelationshipDirection::Undirected => rel_count
            .div_ceil(source_count)
            .saturating_add(rel_count.div_ceil(target_count))
            .max(1),
    };
    seed_rows.saturating_mul(per_seed).max(1)
}

#[cfg(test)]
mod tests_width;