Skip to main content

hawdb_cascades/
cost.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct PlanCost {
17    pub estimated_rows: u64,
18    pub cost: u64,
19}
20
21impl PlanCost {
22    pub fn with_cardinality_floor(self) -> Self {
23        Self {
24            estimated_rows: self.estimated_rows.max(1),
25            ..self
26        }
27    }
28}
29
30/// Cardinality and unweighted logical work, plus the weighted scalar total.
31///
32/// CPU work is the scalar normalization unit. Random/sequential work describes
33/// access patterns, not physical file pages; output work counts produced rows.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct PlanCostBreakdown {
36    pub estimated_rows: u64,
37    pub cost: u64,
38    pub cpu: u64,
39    pub random_io: u64,
40    pub sequential_io: u64,
41    pub output_rows: u64,
42}
43
44/// Relative weights applied once to raw logical work components.
45///
46/// These are planning units rather than hardware latency coefficients. Exposing
47/// the immutable policy lets offline qualification re-score frozen candidates;
48/// it does not add a runtime tuning surface or change the engine default.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct PlanCostWeights {
51    pub cpu: u64,
52    pub random_access: u64,
53    pub sequential_access: u64,
54    pub output: u64,
55}
56
57impl PlanCostWeights {
58    pub const fn new(cpu: u64, random_access: u64, sequential_access: u64, output: u64) -> Self {
59        Self {
60            cpu,
61            random_access,
62            sequential_access,
63            output,
64        }
65    }
66
67    fn score(self, cpu: u64, random_access: u64, sequential_access: u64, output: u64) -> u64 {
68        cpu.saturating_mul(self.cpu)
69            .saturating_add(random_access.saturating_mul(self.random_access))
70            .saturating_add(sequential_access.saturating_mul(self.sequential_access))
71            .saturating_add(output.saturating_mul(self.output))
72    }
73}
74
75/// Stable identity of the default logical-work policy recorded in qualification
76/// evidence. A different default requires a separately reviewed policy change.
77pub const DEFAULT_PLAN_COST_POLICY_ID: &str = "hawdb-logical-cost-v1";
78
79// CPU is the scalar normalization unit: from_scalar must not weight a cost twice.
80// These are conservative logical-work weights, not physical page counts or time.
81// Random access costs more than sequential access even when the OS caches bytes.
82pub const DEFAULT_PLAN_COST_WEIGHTS: PlanCostWeights = PlanCostWeights::new(1, 2, 1, 1);
83
84impl PlanCostBreakdown {
85    pub fn with_cardinality_floor(self) -> Self {
86        Self {
87            estimated_rows: self.estimated_rows.max(1),
88            ..self
89        }
90    }
91
92    pub fn new(
93        estimated_rows: u64,
94        cpu: u64,
95        random_io: u64,
96        sequential_io: u64,
97        output_rows: u64,
98    ) -> Self {
99        Self {
100            estimated_rows,
101            cost: DEFAULT_PLAN_COST_WEIGHTS.score(cpu, random_io, sequential_io, output_rows),
102            cpu,
103            random_io,
104            sequential_io,
105            output_rows,
106        }
107        .with_cardinality_floor()
108    }
109
110    /// Re-scores retained raw work without changing cardinality or the stored
111    /// engine-default total. Intended for offline qualification and fitting.
112    pub fn score_with_weights(self, weights: PlanCostWeights) -> PlanCost {
113        PlanCost {
114            estimated_rows: self.estimated_rows,
115            cost: weights.score(
116                self.cpu,
117                self.random_io,
118                self.sequential_io,
119                self.output_rows,
120            ),
121        }
122        .with_cardinality_floor()
123    }
124
125    pub fn from_scalar(cost: PlanCost) -> Self {
126        Self::new(cost.estimated_rows, cost.cost, 0, 0, 0)
127    }
128
129    pub fn with_cpu(self, estimated_rows: u64, cpu: u64, output_rows: u64) -> Self {
130        Self::new(
131            estimated_rows,
132            self.cpu.saturating_add(cpu),
133            self.random_io,
134            self.sequential_io,
135            self.output_rows.saturating_add(output_rows),
136        )
137    }
138
139    pub fn with_random_io(self, estimated_rows: u64, random_io: u64, output_rows: u64) -> Self {
140        Self::new(
141            estimated_rows,
142            self.cpu,
143            self.random_io.saturating_add(random_io),
144            self.sequential_io,
145            self.output_rows.saturating_add(output_rows),
146        )
147    }
148
149    pub fn combine_with_cpu(
150        left: Self,
151        right: Self,
152        estimated_rows: u64,
153        cpu: u64,
154        output_rows: u64,
155    ) -> Self {
156        Self::new(
157            estimated_rows,
158            left.cpu.saturating_add(right.cpu).saturating_add(cpu),
159            left.random_io.saturating_add(right.random_io),
160            left.sequential_io.saturating_add(right.sequential_io),
161            left.output_rows
162                .saturating_add(right.output_rows)
163                .saturating_add(output_rows),
164        )
165    }
166
167    pub fn as_plan_cost(self) -> PlanCost {
168        PlanCost {
169            estimated_rows: self.estimated_rows,
170            cost: self.cost,
171        }
172        .with_cardinality_floor()
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::{
179        PlanCost, PlanCostBreakdown, PlanCostWeights, DEFAULT_PLAN_COST_POLICY_ID,
180        DEFAULT_PLAN_COST_WEIGHTS,
181    };
182
183    #[test]
184    fn cost_breakdown_sums_stable_components() {
185        let cost = PlanCostBreakdown::new(7, 10, 20, 30, 40);
186
187        assert_eq!(cost.estimated_rows, 7);
188        assert_eq!(cost.cost, 120);
189        assert_eq!(
190            cost.as_plan_cost(),
191            PlanCost {
192                estimated_rows: 7,
193                cost: 120,
194            }
195        );
196    }
197
198    #[test]
199    fn cost_breakdown_combines_child_costs_with_parent_cpu() {
200        let left = PlanCostBreakdown::new(2, 3, 5, 7, 11);
201        let right = PlanCostBreakdown::new(13, 17, 19, 23, 29);
202
203        let combined = PlanCostBreakdown::combine_with_cpu(left, right, 26, 31, 37);
204
205        assert_eq!(combined.estimated_rows, 26);
206        assert_eq!(combined.cpu, 51);
207        assert_eq!(combined.random_io, 24);
208        assert_eq!(combined.sequential_io, 30);
209        assert_eq!(combined.output_rows, 77);
210        assert_eq!(combined.cost, 206);
211    }
212
213    #[test]
214    fn cost_breakdown_preserves_a_non_zero_cardinality_floor() {
215        let cost = PlanCostBreakdown::new(0, 0, 0, 0, 0);
216
217        assert_eq!(cost.estimated_rows, 1);
218        assert_eq!(cost.as_plan_cost().estimated_rows, 1);
219    }
220
221    #[test]
222    fn scalar_cost_preserves_a_non_zero_cardinality_floor() {
223        let cost = PlanCost {
224            estimated_rows: 0,
225            cost: 7,
226        }
227        .with_cardinality_floor();
228
229        assert_eq!(cost.estimated_rows, 1);
230        assert_eq!(cost.cost, 7);
231    }
232
233    #[test]
234    fn qualification_can_rescore_raw_work_without_mutating_the_default_total() {
235        let cost = PlanCostBreakdown::new(7, 10, 20, 30, 40);
236
237        assert_eq!(DEFAULT_PLAN_COST_POLICY_ID, "hawdb-logical-cost-v1");
238        assert_eq!(DEFAULT_PLAN_COST_WEIGHTS, PlanCostWeights::new(1, 2, 1, 1));
239        assert_eq!(cost.cost, 120);
240        assert_eq!(
241            cost.score_with_weights(PlanCostWeights::new(1, 5, 2, 0)),
242            PlanCost {
243                estimated_rows: 7,
244                cost: 170,
245            }
246        );
247        assert_eq!(cost.cost, 120);
248    }
249}