Skip to main content

hawdb_cascades/
search.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
15use std::fmt::{Display, Formatter};
16use std::str::FromStr;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SearchMode {
20    Memo,
21    DirectFallback,
22}
23
24#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
25pub enum OptimizerSearchDirective {
26    #[default]
27    Auto,
28    Memo,
29    DirectFallback,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum OptimizerSearchDirectiveError {
34    MemoGroupBudgetExceeded {
35        required_groups: usize,
36        max_groups: usize,
37    },
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct RuleEvent {
42    rule: String,
43    outcome: RuleOutcome,
44    detail: String,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum RuleOutcome {
49    Applied,
50    Skipped,
51    Estimated,
52    Selected,
53}
54
55impl RuleEvent {
56    /// Requested owned heap, excluding the containing vector/inline layout.
57    #[doc(hidden)]
58    pub fn retained_heap_bytes(&self) -> Option<usize> {
59        let Self {
60            rule,
61            outcome,
62            detail,
63        } = self;
64        fn leaf<T: Copy>(_: &T) {}
65        leaf(outcome);
66        rule.capacity().checked_add(detail.capacity())
67    }
68
69    pub fn applied(rule: impl Into<String>, detail: impl Into<String>) -> Self {
70        Self::new(rule, RuleOutcome::Applied, detail)
71    }
72
73    pub fn skipped(rule: impl Into<String>, detail: impl Into<String>) -> Self {
74        Self::new(rule, RuleOutcome::Skipped, detail)
75    }
76
77    pub fn estimated(rule: impl Into<String>, detail: impl Into<String>) -> Self {
78        Self::new(rule, RuleOutcome::Estimated, detail)
79    }
80
81    pub fn selected(rule: impl Into<String>, detail: impl Into<String>) -> Self {
82        Self::new(rule, RuleOutcome::Selected, detail)
83    }
84
85    pub fn new(rule: impl Into<String>, outcome: RuleOutcome, detail: impl Into<String>) -> Self {
86        Self {
87            rule: rule.into(),
88            outcome,
89            detail: detail.into(),
90        }
91    }
92
93    pub fn rule(&self) -> &str {
94        &self.rule
95    }
96
97    pub fn outcome(&self) -> RuleOutcome {
98        self.outcome
99    }
100
101    pub fn detail(&self) -> &str {
102        &self.detail
103    }
104
105    pub fn into_decision(self) -> String {
106        format!("{} {}: {}", self.outcome.as_str(), self.rule, self.detail)
107    }
108
109    pub fn from_decision(decision: &str) -> Option<Self> {
110        let (outcome, rest) = decision.split_once(' ')?;
111        let (rule, detail) = rest.split_once(": ")?;
112        Some(Self::new(
113            rule,
114            outcome.parse::<RuleOutcome>().ok()?,
115            detail,
116        ))
117    }
118}
119
120impl SearchMode {
121    pub fn all() -> &'static [Self] {
122        const ALL: &[SearchMode] = &[SearchMode::Memo, SearchMode::DirectFallback];
123        ALL
124    }
125
126    pub fn as_str(self) -> &'static str {
127        match self {
128            SearchMode::Memo => "memo",
129            SearchMode::DirectFallback => "direct_fallback",
130        }
131    }
132}
133
134impl OptimizerSearchDirective {
135    pub const fn as_str(self) -> &'static str {
136        match self {
137            Self::Auto => "auto",
138            Self::Memo => "memo",
139            Self::DirectFallback => "direct_fallback",
140        }
141    }
142}
143
144impl FromStr for OptimizerSearchDirective {
145    type Err = &'static str;
146
147    fn from_str(value: &str) -> Result<Self, Self::Err> {
148        match value {
149            "auto" => Ok(Self::Auto),
150            "memo" => Ok(Self::Memo),
151            "direct_fallback" => Ok(Self::DirectFallback),
152            _ => Err("unknown optimizer search directive"),
153        }
154    }
155}
156
157impl Display for OptimizerSearchDirectiveError {
158    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
159        match self {
160            Self::MemoGroupBudgetExceeded {
161                required_groups,
162                max_groups,
163            } => write!(
164                formatter,
165                "memo search directive requires {required_groups} groups but max_groups is {max_groups}"
166            ),
167        }
168    }
169}
170
171impl std::error::Error for OptimizerSearchDirectiveError {}
172
173impl RuleOutcome {
174    pub fn all() -> &'static [Self] {
175        const ALL: &[RuleOutcome] = &[
176            RuleOutcome::Applied,
177            RuleOutcome::Skipped,
178            RuleOutcome::Estimated,
179            RuleOutcome::Selected,
180        ];
181        ALL
182    }
183
184    pub fn as_str(self) -> &'static str {
185        match self {
186            RuleOutcome::Applied => "apply",
187            RuleOutcome::Skipped => "skip",
188            RuleOutcome::Estimated => "estimate",
189            RuleOutcome::Selected => "selected",
190        }
191    }
192}
193
194impl FromStr for SearchMode {
195    type Err = &'static str;
196
197    fn from_str(value: &str) -> Result<Self, Self::Err> {
198        Self::all()
199            .iter()
200            .copied()
201            .find(|mode| mode.as_str() == value)
202            .ok_or("unknown optimizer search mode")
203    }
204}
205
206impl FromStr for RuleOutcome {
207    type Err = &'static str;
208
209    fn from_str(value: &str) -> Result<Self, Self::Err> {
210        Self::all()
211            .iter()
212            .copied()
213            .find(|outcome| outcome.as_str() == value)
214            .ok_or("unknown optimizer rule outcome")
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::{OptimizerSearchDirective, RuleEvent, RuleOutcome, SearchMode};
221
222    #[test]
223    fn search_directive_strings_round_trip() {
224        for directive in [
225            OptimizerSearchDirective::Auto,
226            OptimizerSearchDirective::Memo,
227            OptimizerSearchDirective::DirectFallback,
228        ] {
229            assert_eq!(
230                directive.as_str().parse::<OptimizerSearchDirective>(),
231                Ok(directive)
232            );
233        }
234        assert!("unknown".parse::<OptimizerSearchDirective>().is_err());
235    }
236
237    #[test]
238    fn search_mode_and_rule_outcome_strings_round_trip() {
239        for mode in SearchMode::all() {
240            assert_eq!(mode.as_str().parse::<SearchMode>(), Ok(*mode));
241        }
242        assert!("unknown".parse::<SearchMode>().is_err());
243        for outcome in RuleOutcome::all() {
244            assert_eq!(outcome.as_str().parse::<RuleOutcome>(), Ok(*outcome));
245        }
246        assert!("unknown".parse::<RuleOutcome>().is_err());
247    }
248
249    #[test]
250    fn rule_event_round_trips_through_legacy_decision_text() {
251        let event = RuleEvent::estimated("index_seek", "rows=1 cost=3");
252
253        assert_eq!(event.into_decision(), "estimate index_seek: rows=1 cost=3");
254        let parsed = RuleEvent::from_decision("estimate index_seek: rows=1 cost=3").unwrap();
255        assert_eq!(parsed.rule(), "index_seek");
256        assert_eq!(parsed.outcome(), RuleOutcome::Estimated);
257        assert_eq!(parsed.detail(), "rows=1 cost=3");
258    }
259}