Skip to main content

hawdb_cascades/
qualification.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded, statement-scoped optimizer qualification controls. Legality and
5//! resource checks are not optional rules and cannot be disabled here.
6
7/// Optional proof transformations supported by the qualification interface.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub enum OptionalOptimizerRule {
10    RedundantOrdering,
11    RedundantDistinct,
12    SingletonGroup,
13    /// Starts a pattern path at a selective index-seekable node (#1485).
14    CostBasedPatternStart,
15    /// Runs a correlated MATCH as a hash join on its imported node (#1485).
16    GraphMatchHashJoin,
17    /// Checks `node IN column` against the list's id set before reading the
18    /// node (#1485).
19    GraphMatchIdSetSemiJoin,
20    /// Runs a first MATCH whose WHERE disjuncts each pin a different node by
21    /// an indexed equality as a union of seeded branches (#1625).
22    DisjunctiveSeedUnion,
23}
24
25impl OptionalOptimizerRule {
26    pub const ALL: [Self; 7] = [
27        Self::RedundantOrdering,
28        Self::RedundantDistinct,
29        Self::SingletonGroup,
30        Self::CostBasedPatternStart,
31        Self::GraphMatchHashJoin,
32        Self::GraphMatchIdSetSemiJoin,
33        Self::DisjunctiveSeedUnion,
34    ];
35
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::RedundantOrdering => "transformation:proof_redundant_ordering",
39            Self::RedundantDistinct => "transformation:proof_redundant_distinct",
40            Self::SingletonGroup => "transformation:proof_singleton_group",
41            Self::CostBasedPatternStart => "transformation:cost_based_pattern_start",
42            Self::GraphMatchHashJoin => "transformation:graph_match_hash_join",
43            Self::GraphMatchIdSetSemiJoin => "transformation:graph_match_id_set_semi_join",
44            Self::DisjunctiveSeedUnion => "transformation:disjunctive_seed_union",
45        }
46    }
47
48    const fn bit(self) -> u8 {
49        1 << self as u8
50    }
51}
52
53/// Reproducible ranking noise. It never changes a raw reported cost, a search
54/// budget, an expression, or whether a candidate is legal.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct OptimizerCostPerturbation {
57    seed: u64,
58    percent: u8,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct InvalidOptimizerCostPerturbation {
63    percent: u8,
64}
65
66impl std::fmt::Display for InvalidOptimizerCostPerturbation {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(
69            f,
70            "optimizer cost perturbation must be at most 25 percent, got {}",
71            self.percent
72        )
73    }
74}
75impl std::error::Error for InvalidOptimizerCostPerturbation {}
76
77impl OptimizerCostPerturbation {
78    pub fn new(seed: u64, percent: u8) -> Result<Self, InvalidOptimizerCostPerturbation> {
79        if percent > 25 {
80            return Err(InvalidOptimizerCostPerturbation { percent });
81        }
82        Ok(Self { seed, percent })
83    }
84    pub const fn seed(self) -> u64 {
85        self.seed
86    }
87    pub const fn percent(self) -> u8 {
88        self.percent
89    }
90
91    /// A stable byte hash makes replay independent of process hash randomization
92    /// and host pointer width. Caller supplies the legal candidate's fingerprint.
93    pub fn ranking_cost(self, raw_cost: u64, fingerprint: &str) -> u64 {
94        if self.percent == 0 || raw_cost == 0 {
95            return raw_cost;
96        }
97        let mut hash = 0xcbf2_9ce4_8422_2325u64 ^ self.seed;
98        for byte in fingerprint.bytes() {
99            hash = (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3);
100        }
101        let spread = u64::from(self.percent) * 2 + 1;
102        let factor = 100 - u64::from(self.percent) + hash % spread;
103        ((u128::from(raw_cost) * u128::from(factor) / 100).min(u128::from(u64::MAX)) as u64).max(1)
104    }
105}
106
107/// Named legal alternatives for one bounded `ORDER BY ... LIMIT` decision.
108///
109/// The optimizer still constructs and validates both physical candidates. This
110/// selector is available only through the offline qualification entry point;
111/// it cannot inject an arbitrary physical plan into serving execution.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum OptimizerBoundedOrderAlternative {
114    TopN,
115    SortThenLimit,
116}
117
118impl OptimizerBoundedOrderAlternative {
119    pub const fn as_str(self) -> &'static str {
120        match self {
121            Self::TopN => "top_n",
122            Self::SortThenLimit => "sort_then_limit",
123        }
124    }
125}
126
127/// Structured trace rule emitted exactly once when an explicit bounded-order
128/// alternative is selected successfully.
129pub const BOUNDED_ORDER_QUALIFICATION_RULE: &str = "qualification:bounded_order_alternative";
130
131/// Fixed-size controls; unknown/essential rules cannot enter the disabled mask.
132#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
133pub struct OptimizerQualificationOptions {
134    disabled_rules: u8,
135    perturbation: Option<OptimizerCostPerturbation>,
136    bounded_order_alternative: Option<OptimizerBoundedOrderAlternative>,
137}
138
139impl OptimizerQualificationOptions {
140    pub fn without_rule(mut self, rule: OptionalOptimizerRule) -> Self {
141        self.disabled_rules |= rule.bit();
142        self
143    }
144    pub fn with_cost_perturbation(mut self, perturbation: OptimizerCostPerturbation) -> Self {
145        self.perturbation = Some(perturbation);
146        self
147    }
148    pub fn with_bounded_order_alternative(
149        mut self,
150        alternative: OptimizerBoundedOrderAlternative,
151    ) -> Self {
152        self.bounded_order_alternative = Some(alternative);
153        self
154    }
155    pub const fn rule_enabled(self, rule: OptionalOptimizerRule) -> bool {
156        self.disabled_rules & rule.bit() == 0
157    }
158    pub const fn cost_perturbation(self) -> Option<OptimizerCostPerturbation> {
159        self.perturbation
160    }
161    pub const fn bounded_order_alternative(self) -> Option<OptimizerBoundedOrderAlternative> {
162        self.bounded_order_alternative
163    }
164    pub fn is_active(self) -> bool {
165        self != Self::default()
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    #[test]
173    fn qualification_is_bounded_and_cannot_disable_unlisted_legality_checks() {
174        let normal = OptimizerQualificationOptions::default();
175        assert!(!normal.is_active());
176        for rule in OptionalOptimizerRule::ALL {
177            assert!(normal.rule_enabled(rule));
178        }
179        let qualified = normal.without_rule(OptionalOptimizerRule::RedundantDistinct);
180        assert!(qualified.is_active());
181        assert!(qualified.rule_enabled(OptionalOptimizerRule::RedundantOrdering));
182        assert!(!qualified.rule_enabled(OptionalOptimizerRule::RedundantDistinct));
183        assert!(OptimizerCostPerturbation::new(7, 26).is_err());
184        assert_eq!(normal.bounded_order_alternative(), None);
185        assert_eq!(
186            normal
187                .with_bounded_order_alternative(OptimizerBoundedOrderAlternative::TopN)
188                .bounded_order_alternative(),
189            Some(OptimizerBoundedOrderAlternative::TopN)
190        );
191    }
192    #[test]
193    fn perturbation_replays_with_bounded_saturating_costs() {
194        for percent in [0, 1, 25] {
195            for raw in [0, 1, 1000, u64::MAX] {
196                for seed in 0..64 {
197                    let p = OptimizerCostPerturbation::new(seed, percent).unwrap();
198                    let ranked = p.ranking_cost(raw, "SortExec:stable-shape");
199                    assert_eq!(ranked, p.ranking_cost(raw, "SortExec:stable-shape"));
200                    let low = (u128::from(raw) * u128::from(100 - percent) / 100)
201                        .max(u128::from(raw != 0));
202                    let high = (u128::from(raw) * u128::from(100 + percent) / 100)
203                        .min(u128::from(u64::MAX));
204                    assert!(
205                        u128::from(ranked) >= low && u128::from(ranked) <= high.max(1),
206                        "seed={seed} raw={raw} percent={percent}"
207                    );
208                    if percent == 0 || raw == 0 {
209                        assert_eq!(ranked, raw);
210                    }
211                }
212            }
213        }
214        let costs = (0..64)
215            .map(|seed| {
216                OptimizerCostPerturbation::new(seed, 25)
217                    .unwrap()
218                    .ranking_cost(1000, "TopNExec:stable-shape")
219            })
220            .collect::<std::collections::BTreeSet<_>>();
221        assert!(
222            costs.len() > 20,
223            "seeds must exercise materially distinct ranking weights"
224        );
225    }
226
227    #[test]
228    fn rule_assertions_use_applied_events_and_bound_the_request() {
229        let rule = OptionalOptimizerRule::RedundantDistinct;
230        let events = [
231            crate::RuleEvent::skipped(rule.as_str(), "candidate retained"),
232            crate::RuleEvent::selected(rule.as_str(), "diagnostic mentions rule"),
233        ];
234        assert_eq!(
235            verify_optimizer_rule_assertions(&events, &[OptimizerRuleAssertion::Required(rule)]),
236            Err(OptimizerRuleAssertionError::MissingRequired(rule))
237        );
238        assert!(verify_optimizer_rule_assertions(
239            &events,
240            &[OptimizerRuleAssertion::Forbidden(rule)]
241        )
242        .is_ok());
243        let events = [crate::RuleEvent::applied(rule.as_str(), "removed")];
244        assert!(verify_optimizer_rule_assertions(
245            &events,
246            &[OptimizerRuleAssertion::Required(rule)]
247        )
248        .is_ok());
249        assert_eq!(
250            verify_optimizer_rule_assertions(&events, &[OptimizerRuleAssertion::Forbidden(rule)]),
251            Err(OptimizerRuleAssertionError::ForbiddenApplied(rule))
252        );
253        assert_eq!(
254            verify_optimizer_rule_assertions(
255                &[],
256                &[OptimizerRuleAssertion::Required(rule); OptionalOptimizerRule::ALL.len() * 2 + 1]
257            ),
258            Err(OptimizerRuleAssertionError::TooManyAssertions)
259        );
260    }
261}
262
263/// Assertions inspect structured applied outcomes, not mentions in plan text.
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub enum OptimizerRuleAssertion {
266    Required(OptionalOptimizerRule),
267    Forbidden(OptionalOptimizerRule),
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum OptimizerRuleAssertionError {
272    TooManyAssertions,
273    MissingRequired(OptionalOptimizerRule),
274    ForbiddenApplied(OptionalOptimizerRule),
275}
276impl std::fmt::Display for OptimizerRuleAssertionError {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        match self {
279            Self::TooManyAssertions => {
280                f.write_str("optimizer qualification accepts at most six rule assertions")
281            }
282            Self::MissingRequired(rule) => write!(
283                f,
284                "required optimizer rule did not apply: {}",
285                rule.as_str()
286            ),
287            Self::ForbiddenApplied(rule) => {
288                write!(f, "forbidden optimizer rule applied: {}", rule.as_str())
289            }
290        }
291    }
292}
293impl std::error::Error for OptimizerRuleAssertionError {}
294
295pub fn verify_optimizer_rule_assertions(
296    events: &[crate::RuleEvent],
297    assertions: &[OptimizerRuleAssertion],
298) -> Result<(), OptimizerRuleAssertionError> {
299    if assertions.len() > OptionalOptimizerRule::ALL.len() * 2 {
300        return Err(OptimizerRuleAssertionError::TooManyAssertions);
301    }
302    let mut applied = 0u8;
303    for event in events {
304        if event.outcome() != crate::RuleOutcome::Applied {
305            continue;
306        }
307        if let Some(rule) = OptionalOptimizerRule::ALL
308            .iter()
309            .find(|rule| rule.as_str() == event.rule())
310        {
311            applied |= rule.bit();
312        }
313    }
314    for assertion in assertions {
315        match *assertion {
316            OptimizerRuleAssertion::Required(rule) if applied & rule.bit() == 0 => {
317                return Err(OptimizerRuleAssertionError::MissingRequired(rule))
318            }
319            OptimizerRuleAssertion::Forbidden(rule) if applied & rule.bit() != 0 => {
320                return Err(OptimizerRuleAssertionError::ForbiddenApplied(rule))
321            }
322            _ => {}
323        }
324    }
325    Ok(())
326}