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}
14
15impl OptionalOptimizerRule {
16    pub const ALL: [Self; 3] = [
17        Self::RedundantOrdering,
18        Self::RedundantDistinct,
19        Self::SingletonGroup,
20    ];
21
22    pub const fn as_str(self) -> &'static str {
23        match self {
24            Self::RedundantOrdering => "transformation:proof_redundant_ordering",
25            Self::RedundantDistinct => "transformation:proof_redundant_distinct",
26            Self::SingletonGroup => "transformation:proof_singleton_group",
27        }
28    }
29
30    const fn bit(self) -> u8 {
31        1 << self as u8
32    }
33}
34
35/// Reproducible ranking noise. It never changes a raw reported cost, a search
36/// budget, an expression, or whether a candidate is legal.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct OptimizerCostPerturbation {
39    seed: u64,
40    percent: u8,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct InvalidOptimizerCostPerturbation {
45    percent: u8,
46}
47
48impl std::fmt::Display for InvalidOptimizerCostPerturbation {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(
51            f,
52            "optimizer cost perturbation must be at most 25 percent, got {}",
53            self.percent
54        )
55    }
56}
57impl std::error::Error for InvalidOptimizerCostPerturbation {}
58
59impl OptimizerCostPerturbation {
60    pub fn new(seed: u64, percent: u8) -> Result<Self, InvalidOptimizerCostPerturbation> {
61        if percent > 25 {
62            return Err(InvalidOptimizerCostPerturbation { percent });
63        }
64        Ok(Self { seed, percent })
65    }
66    pub const fn seed(self) -> u64 {
67        self.seed
68    }
69    pub const fn percent(self) -> u8 {
70        self.percent
71    }
72
73    /// A stable byte hash makes replay independent of process hash randomization
74    /// and host pointer width. Caller supplies the legal candidate's fingerprint.
75    pub fn ranking_cost(self, raw_cost: u64, fingerprint: &str) -> u64 {
76        if self.percent == 0 || raw_cost == 0 {
77            return raw_cost;
78        }
79        let mut hash = 0xcbf2_9ce4_8422_2325u64 ^ self.seed;
80        for byte in fingerprint.bytes() {
81            hash = (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3);
82        }
83        let spread = u64::from(self.percent) * 2 + 1;
84        let factor = 100 - u64::from(self.percent) + hash % spread;
85        ((u128::from(raw_cost) * u128::from(factor) / 100).min(u128::from(u64::MAX)) as u64).max(1)
86    }
87}
88
89/// Fixed-size controls; unknown/essential rules cannot enter the disabled mask.
90#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
91pub struct OptimizerQualificationOptions {
92    disabled_rules: u8,
93    perturbation: Option<OptimizerCostPerturbation>,
94}
95
96impl OptimizerQualificationOptions {
97    pub fn without_rule(mut self, rule: OptionalOptimizerRule) -> Self {
98        self.disabled_rules |= rule.bit();
99        self
100    }
101    pub fn with_cost_perturbation(mut self, perturbation: OptimizerCostPerturbation) -> Self {
102        self.perturbation = Some(perturbation);
103        self
104    }
105    pub const fn rule_enabled(self, rule: OptionalOptimizerRule) -> bool {
106        self.disabled_rules & rule.bit() == 0
107    }
108    pub const fn cost_perturbation(self) -> Option<OptimizerCostPerturbation> {
109        self.perturbation
110    }
111    pub fn is_active(self) -> bool {
112        self != Self::default()
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    #[test]
120    fn qualification_is_bounded_and_cannot_disable_unlisted_legality_checks() {
121        let normal = OptimizerQualificationOptions::default();
122        assert!(!normal.is_active());
123        for rule in OptionalOptimizerRule::ALL {
124            assert!(normal.rule_enabled(rule));
125        }
126        let qualified = normal.without_rule(OptionalOptimizerRule::RedundantDistinct);
127        assert!(qualified.is_active());
128        assert!(qualified.rule_enabled(OptionalOptimizerRule::RedundantOrdering));
129        assert!(!qualified.rule_enabled(OptionalOptimizerRule::RedundantDistinct));
130        assert!(OptimizerCostPerturbation::new(7, 26).is_err());
131    }
132    #[test]
133    fn perturbation_replays_with_bounded_saturating_costs() {
134        for percent in [0, 1, 25] {
135            for raw in [0, 1, 1000, u64::MAX] {
136                for seed in 0..64 {
137                    let p = OptimizerCostPerturbation::new(seed, percent).unwrap();
138                    let ranked = p.ranking_cost(raw, "SortExec:stable-shape");
139                    assert_eq!(ranked, p.ranking_cost(raw, "SortExec:stable-shape"));
140                    let low = (u128::from(raw) * u128::from(100 - percent) / 100)
141                        .max(u128::from(raw != 0));
142                    let high = (u128::from(raw) * u128::from(100 + percent) / 100)
143                        .min(u128::from(u64::MAX));
144                    assert!(
145                        u128::from(ranked) >= low && u128::from(ranked) <= high.max(1),
146                        "seed={seed} raw={raw} percent={percent}"
147                    );
148                    if percent == 0 || raw == 0 {
149                        assert_eq!(ranked, raw);
150                    }
151                }
152            }
153        }
154        let costs = (0..64)
155            .map(|seed| {
156                OptimizerCostPerturbation::new(seed, 25)
157                    .unwrap()
158                    .ranking_cost(1000, "TopNExec:stable-shape")
159            })
160            .collect::<std::collections::BTreeSet<_>>();
161        assert!(
162            costs.len() > 20,
163            "seeds must exercise materially distinct ranking weights"
164        );
165    }
166
167    #[test]
168    fn rule_assertions_use_applied_events_and_bound_the_request() {
169        let rule = OptionalOptimizerRule::RedundantDistinct;
170        let events = [
171            crate::RuleEvent::skipped(rule.as_str(), "candidate retained"),
172            crate::RuleEvent::selected(rule.as_str(), "diagnostic mentions rule"),
173        ];
174        assert_eq!(
175            verify_optimizer_rule_assertions(&events, &[OptimizerRuleAssertion::Required(rule)]),
176            Err(OptimizerRuleAssertionError::MissingRequired(rule))
177        );
178        assert!(verify_optimizer_rule_assertions(
179            &events,
180            &[OptimizerRuleAssertion::Forbidden(rule)]
181        )
182        .is_ok());
183        let events = [crate::RuleEvent::applied(rule.as_str(), "removed")];
184        assert!(verify_optimizer_rule_assertions(
185            &events,
186            &[OptimizerRuleAssertion::Required(rule)]
187        )
188        .is_ok());
189        assert_eq!(
190            verify_optimizer_rule_assertions(&events, &[OptimizerRuleAssertion::Forbidden(rule)]),
191            Err(OptimizerRuleAssertionError::ForbiddenApplied(rule))
192        );
193        assert_eq!(
194            verify_optimizer_rule_assertions(&[], &[OptimizerRuleAssertion::Required(rule); 7]),
195            Err(OptimizerRuleAssertionError::TooManyAssertions)
196        );
197    }
198}
199
200/// Assertions inspect structured applied outcomes, not mentions in plan text.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum OptimizerRuleAssertion {
203    Required(OptionalOptimizerRule),
204    Forbidden(OptionalOptimizerRule),
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum OptimizerRuleAssertionError {
209    TooManyAssertions,
210    MissingRequired(OptionalOptimizerRule),
211    ForbiddenApplied(OptionalOptimizerRule),
212}
213impl std::fmt::Display for OptimizerRuleAssertionError {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        match self {
216            Self::TooManyAssertions => {
217                f.write_str("optimizer qualification accepts at most six rule assertions")
218            }
219            Self::MissingRequired(rule) => write!(
220                f,
221                "required optimizer rule did not apply: {}",
222                rule.as_str()
223            ),
224            Self::ForbiddenApplied(rule) => {
225                write!(f, "forbidden optimizer rule applied: {}", rule.as_str())
226            }
227        }
228    }
229}
230impl std::error::Error for OptimizerRuleAssertionError {}
231
232pub fn verify_optimizer_rule_assertions(
233    events: &[crate::RuleEvent],
234    assertions: &[OptimizerRuleAssertion],
235) -> Result<(), OptimizerRuleAssertionError> {
236    if assertions.len() > OptionalOptimizerRule::ALL.len() * 2 {
237        return Err(OptimizerRuleAssertionError::TooManyAssertions);
238    }
239    let mut applied = 0u8;
240    for event in events {
241        if event.outcome() != crate::RuleOutcome::Applied {
242            continue;
243        }
244        if let Some(rule) = OptionalOptimizerRule::ALL
245            .iter()
246            .find(|rule| rule.as_str() == event.rule())
247        {
248            applied |= rule.bit();
249        }
250    }
251    for assertion in assertions {
252        match *assertion {
253            OptimizerRuleAssertion::Required(rule) if applied & rule.bit() == 0 => {
254                return Err(OptimizerRuleAssertionError::MissingRequired(rule))
255            }
256            OptimizerRuleAssertion::Forbidden(rule) if applied & rule.bit() != 0 => {
257                return Err(OptimizerRuleAssertionError::ForbiddenApplied(rule))
258            }
259            _ => {}
260        }
261    }
262    Ok(())
263}