Skip to main content

relate_model/
plan_warning.rs

1//! The typed plan-warning vocabulary (ADR-0344, typed node warnings;
2//! LABS-461): the one warning type — the [`PlanWarning`] enum owning the
3//! wire name, the message text, the payload variant, and the notification
4//! projection once each — beside the estimate-vs-actual policy its
5//! `EstimationMiss` variant derives from and the wire-shape serializer
6//! the HTTP plan reads. It lives here, beside the notification vocabulary
7//! it projects into and the wire parse it coordinates, so the engine's
8//! detection, the wire parse, and every surface's rendering cannot drift
9//! (not three review-coordinated layers).
10
11use super::notification_wire::NotificationKind;
12use super::plan_keys;
13
14/// The typed warnings vocabulary's wire name, by variant — the one
15/// spelling the engine's detection serializes into the wire form and
16/// [`PlanWarning::from_wire_parts`] parses back; a name outside the
17/// vocabulary is a contract break. In-crate today (the parse and the
18/// model's tests); re-widened to `pub` in the same change as the first
19/// cross-crate consumer naming a wire warning.
20pub(crate) const WARNING_ESTIMATION_MISS: &str = "EstimationMiss";
21/// See [`WARNING_ESTIMATION_MISS`].
22pub(crate) const WARNING_CARTESIAN_PRODUCT: &str = "CartesianProduct";
23/// See [`WARNING_ESTIMATION_MISS`].
24pub(crate) const WARNING_ALL_NODES_SCAN: &str = "AllNodesScan";
25/// See [`WARNING_ESTIMATION_MISS`].
26pub(crate) const WARNING_LABEL_DISJUNCTION_SCAN: &str = "LabelDisjunctionScan";
27
28/// The `EstimationMiss` overshoot factor (ADR-0344): the estimate misses
29/// when it overshoots the actual rows by this many times or more — the
30/// one spelling both the policy ([`estimation_miss`]) divides by and the
31/// variant's message text names, so the factor and its "10x" cannot
32/// drift apart.
33const ESTIMATION_MISS_FACTOR: u64 = 10;
34
35/// One typed warning a plan node carries (ADR-0344, typed node warnings):
36/// the vocabulary's one definition — the wire name it serializes by, the
37/// message text that renders beside the affected operator and in the
38/// warnings footer, the payload variant that names the property index, and
39/// the notification kind it projects to (ADR-0363 decision 1) — each owned
40/// here once, beside the notification vocabulary it projects into, so the
41/// engine's detection, the wire parse, and every surface's rendering
42/// cannot drift (LABS-461: one warning type, not three coordinated
43/// layers).
44///
45/// The engine constructs the variants at plan-tree construction (the
46/// MATCH-shape detection in `relate`'s `plan_node/warning.rs`); the
47/// wire accessor parses the `{name, index}` maps back into them — the one
48/// typed vocabulary in both directions.
49///
50/// ```rust
51/// # use relate_model::wire::PlanWarning;
52/// let cartesian = PlanWarning::CartesianProduct;
53/// assert_eq!(cartesian.name(), "CartesianProduct");
54/// assert_eq!(
55///     cartesian.message(),
56///     "the MATCH patterns share no join anchor"
57/// );
58/// // The AllNodesScan warning names no index: a label-less pattern
59/// // cannot use one, so the advice is the label.
60/// let scan = PlanWarning::AllNodesScan;
61/// assert_eq!(scan.name(), "AllNodesScan");
62/// assert_eq!(
63///     scan.message(),
64///     "the scan matches every node; add a label to narrow it"
65/// );
66/// // The label-disjunction scan carries the per-label pairs its own
67/// // predicate wants indexed (LABS-1083).
68/// let disjunction = PlanWarning::LabelDisjunctionScan {
69///     indexes: ":Model(id), :Source(id)".to_string(),
70/// };
71/// assert_eq!(disjunction.name(), "LabelDisjunctionScan");
72/// assert_eq!(
73///     disjunction.message(),
74///     "the disjunction scan answers per label; consider the property index \
75///      (:Model(id), :Source(id))"
76/// );
77/// ```
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub enum PlanWarning {
80    /// The operator's estimate overshot its actual rows by 10x or more —
81    /// the same policy the ratio cell's `!` marker reads. PROFILE only:
82    /// it needs the actual rows, so it never fires on an EXPLAIN tree.
83    EstimationMiss,
84    /// A multi-pattern `MATCH` whose patterns share no join anchor (no
85    /// node variable appears in more than one pattern) — the patterns
86    /// multiply instead of joining.
87    CartesianProduct,
88    /// A label-less scan (`MATCH (n)`) while the store carries a property
89    /// index. The warning names no index: no property index serves a
90    /// pattern without a label, and the one the store carries may be
91    /// unrelated to the query, so the advice is the label alone.
92    AllNodesScan,
93    /// A static label disjunction no seek serves (`MATCH (p) WHERE
94    /// p:Model OR p:Source` after the planner's fold, LABS-1083): the
95    /// scan answers per disjunct label, never every node — its own
96    /// warning shape, never the `AllNodesScan` text. The warning carries
97    /// the per-label `:Label(property)` pairs its equality predicate
98    /// wants indexed, comma-joined, as the suggestion.
99    LabelDisjunctionScan {
100        /// The per-label index pairs the suggestion names.
101        indexes: String,
102    },
103}
104
105/// The payload-less variants, the one table the wire parse searches by
106/// [`PlanWarning::name`] — a new payload-less variant is added here and
107/// to [`PlanWarning::identity`]'s exhaustive match.
108const PAYLOAD_LESS: [PlanWarning; 3] = [
109    PlanWarning::EstimationMiss,
110    PlanWarning::CartesianProduct,
111    PlanWarning::AllNodesScan,
112];
113
114impl PlanWarning {
115    /// One exhaustive variant mapping of the allocation-free half of the
116    /// vocabulary: the wire name and the notification kind the warning
117    /// projects to (ADR-0363 decision 1) — a fifth warning variant must
118    /// choose both here rather than falling through a wildcard. Every
119    /// projected kind is a plan warning in the model's partition
120    /// ([`NotificationKind::is_plan_warning`]), so the plan table's
121    /// warning text and the notification description are one spelling.
122    fn identity(&self) -> (&'static str, NotificationKind) {
123        match self {
124            PlanWarning::EstimationMiss => {
125                (WARNING_ESTIMATION_MISS, NotificationKind::EstimationMiss)
126            }
127            PlanWarning::CartesianProduct => (
128                WARNING_CARTESIAN_PRODUCT,
129                NotificationKind::CartesianProduct,
130            ),
131            PlanWarning::AllNodesScan => (WARNING_ALL_NODES_SCAN, NotificationKind::AllNodesScan),
132            PlanWarning::LabelDisjunctionScan { .. } => (
133                WARNING_LABEL_DISJUNCTION_SCAN,
134                NotificationKind::LabelDisjunctionScan,
135            ),
136        }
137    }
138
139    /// The base message text, before any payload — one exhaustive match,
140    /// built only where a message is rendered ([`Self::message`]).
141    fn base_text(&self) -> String {
142        match self {
143            PlanWarning::EstimationMiss => {
144                format!("estimated rows {ESTIMATION_MISS_FACTOR}x or more above the actual rows")
145            }
146            PlanWarning::CartesianProduct => "the MATCH patterns share no join anchor".to_string(),
147            PlanWarning::AllNodesScan => {
148                "the scan matches every node; add a label to narrow it".to_string()
149            }
150            PlanWarning::LabelDisjunctionScan { .. } => {
151                "the disjunction scan answers per label; consider the property index".to_string()
152            }
153        }
154    }
155
156    /// The warning's wire name — the one spelling the wire form
157    /// serializes (`warnings` on the node) and
158    /// [`Self::from_wire_parts`] validates against.
159    pub fn name(&self) -> &'static str {
160        self.identity().0
161    }
162
163    /// The warning's index payload — the `LabelDisjunctionScan` warning's
164    /// per-label index pairs, `None` on the payload-less variants. The one spelling
165    /// of which warnings carry a payload, read by both the message text
166    /// and the wire form's `index` field, so the vocabulary is matched once.
167    pub fn suggested_index(&self) -> Option<&str> {
168        match self {
169            PlanWarning::LabelDisjunctionScan { indexes } => Some(indexes.as_str()),
170            PlanWarning::EstimationMiss
171            | PlanWarning::CartesianProduct
172            | PlanWarning::AllNodesScan => None,
173        }
174    }
175
176    /// The notification kind this warning projects to (ADR-0363
177    /// decision 1) — from the one exhaustive variant mapping [`Self::name`]
178    /// reads, so a fourth warning variant must choose its vocabulary row
179    /// there rather than falling through a wildcard.
180    ///
181    /// ```rust
182    /// # use relate_model::wire::PlanWarning;
183    /// # use relate_model::wire::NotificationKind;
184    /// assert_eq!(
185    ///     PlanWarning::CartesianProduct.notification_kind(),
186    ///     NotificationKind::CartesianProduct
187    /// );
188    /// assert!(PlanWarning::EstimationMiss
189    ///     .notification_kind()
190    ///     .is_plan_warning());
191    /// ```
192    pub fn notification_kind(&self) -> NotificationKind {
193        self.identity().1
194    }
195
196    /// The warning's message text — the vocabulary's base text
197    /// ([`Self::base_text`]'s one spelling), with the payload appended in
198    /// parentheses when the warning carries one (the `LabelDisjunctionScan`
199    /// warning's suggested index pairs). The one spelling the engine
200    /// renderer and every surface's table layout render, so the text
201    /// cannot drift between the forms.
202    pub fn message(&self) -> String {
203        match self.suggested_index() {
204            Some(index) => format!("{} ({index})", self.base_text()),
205            None => self.base_text(),
206        }
207    }
208
209    /// The wire parse — the one validating match back into the typed
210    /// vocabulary: a name from it with the payload shape its variant
211    /// carries (`LabelDisjunctionScan` requires the pairs, the payload-less
212    /// variants carry none). `None` names a warning outside the
213    /// vocabulary or a payload shape its variant does not carry — a
214    /// wire-contract break the accessor fails loudly on, never a
215    /// silently dropped or reinterpreted warning. In-crate today (the
216    /// accessor and the model's tests); re-widened to `pub` in the same
217    /// change as the first cross-crate consumer parsing raw wire
218    /// warning maps.
219    pub(crate) fn from_wire_parts(name: &str, index: Option<&str>) -> Option<Self> {
220        match index {
221            None => PAYLOAD_LESS.into_iter().find(|w| w.name() == name),
222            Some(indexes) => {
223                // The payload variant's name comes from `identity()`
224                // like every other, not a second hand comparison.
225                let candidate = PlanWarning::LabelDisjunctionScan {
226                    indexes: indexes.to_string(),
227                };
228                (candidate.name() == name).then_some(candidate)
229            }
230        }
231    }
232}
233
234/// Whether the estimated-vs-actual ratio is defined (ADR-0344 metric
235/// fields): the operator produced rows. The one predicate both the
236/// ratio cell and the overshoot policy read — never a second
237/// `actual > 0` spelling at either site.
238pub fn ratio_defined(actual: u64) -> bool {
239    actual > 0
240}
241
242/// The one estimated-vs-actual overshoot policy (ADR-0344 metric
243/// fields + typed node warnings): the estimate misses when it
244/// overshoots the actual rows by 10x or more and the operator
245/// produced rows (an estimate over zero actual rows has no ratio).
246/// Both the ratio cell's warning marker and the `EstimationMiss`
247/// warning derive from this one policy, never a second computation.
248pub fn estimation_miss(estimated: u64, actual: u64) -> bool {
249    // Integer comparison — exact for every saturated u64 (f64's 53-bit
250    // mantissa would lose the boundary); floor division preserves the
251    // "ten times or more" test for actual > 0.
252    ratio_defined(actual) && estimated / ESTIMATION_MISS_FACTOR >= actual
253}
254
255/// The wire shape of one typed warning: `{name, index?}`, built from
256/// the one [`PlanWarning`] vocabulary — the spelling the plan-wire
257/// warning projections read (the HTTP v2 plan), never a re-assembled
258/// `{name, index}` at each site. The agent-native document does not read
259/// it: per ADR-0381 its node `warnings` derive from the result's
260/// remedy-bearing notifications.
261pub fn warning_wire_json(warning: &PlanWarning) -> serde_json::Value {
262    let mut out = serde_json::Map::new();
263    out.insert(
264        plan_keys::WARNING_NAME.to_string(),
265        serde_json::Value::String(warning.name().to_string()),
266    );
267    if let Some(index) = warning.suggested_index() {
268        out.insert(
269            plan_keys::WARNING_INDEX.to_string(),
270            serde_json::Value::String(index.to_string()),
271        );
272    }
273    serde_json::Value::Object(out)
274}