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 carries the existing property index it
59/// // suggests, so the text names it.
60/// let scan = PlanWarning::AllNodesScan {
61///     index: ":Person(name)".to_string(),
62/// };
63/// assert_eq!(scan.name(), "AllNodesScan");
64/// assert_eq!(
65///     scan.message(),
66///     "the scan matches every node; consider the property index (:Person(name))"
67/// );
68/// // The label-disjunction scan carries the per-label pairs its own
69/// // predicate wants indexed (LABS-1083).
70/// let disjunction = PlanWarning::LabelDisjunctionScan {
71///     indexes: ":Model(id), :Source(id)".to_string(),
72/// };
73/// assert_eq!(disjunction.name(), "LabelDisjunctionScan");
74/// assert_eq!(
75///     disjunction.message(),
76///     "the disjunction scan answers per label; consider the property index \
77///      (:Model(id), :Source(id))"
78/// );
79/// ```
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub enum PlanWarning {
82    /// The operator's estimate overshot its actual rows by 10x or more —
83    /// the same policy the ratio cell's `!` marker reads. PROFILE only:
84    /// it needs the actual rows, so it never fires on an EXPLAIN tree.
85    EstimationMiss,
86    /// A multi-pattern `MATCH` whose patterns share no join anchor (no
87    /// node variable appears in more than one pattern) — the patterns
88    /// multiply instead of joining.
89    CartesianProduct,
90    /// A label-less scan (`MATCH (n)`) while the store carries a property
91    /// index: the warning carries the existing index's text
92    /// (`:Label(property)`) as the suggestion.
93    AllNodesScan {
94        /// The existing property index the suggestion names.
95        index: String,
96    },
97    /// A static label disjunction no seek serves (`MATCH (p) WHERE
98    /// p:Model OR p:Source` after the planner's fold, LABS-1083): the
99    /// scan answers per disjunct label, never every node — its own
100    /// warning shape, never the `AllNodesScan` text. The warning carries
101    /// the per-label `:Label(property)` pairs its equality predicate
102    /// wants indexed, comma-joined, as the suggestion.
103    LabelDisjunctionScan {
104        /// The per-label index pairs the suggestion names.
105        indexes: String,
106    },
107}
108
109/// One variant's vocabulary row — the wire name, the base message text,
110/// and the notification kind the warning projects to, each named so a
111/// transposed read (`name()` reading the text) stops compiling, the
112/// same boundary the notification vocabulary's own row struct draws.
113struct VocabularyRow {
114    name: &'static str,
115    /// The base message text — `String` because the `EstimationMiss`
116    /// row names [`ESTIMATION_MISS_FACTOR`], built here rather than
117    /// spelled a second time.
118    text: String,
119    kind: NotificationKind,
120}
121
122impl PlanWarning {
123    /// One exhaustive variant mapping: the wire name, the base message
124    /// text, and the notification kind the warning projects to (ADR-0363
125    /// decision 1) — a fourth warning variant must choose all three
126    /// here rather than falling through a wildcard. Every projected kind
127    /// is a plan warning in the model's partition
128    /// ([`NotificationKind::is_plan_warning`]), so the plan table's
129    /// warning text and the notification description are one spelling.
130    fn vocabulary(&self) -> VocabularyRow {
131        match self {
132            PlanWarning::EstimationMiss => VocabularyRow {
133                name: WARNING_ESTIMATION_MISS,
134                text: format!(
135                    "estimated rows {ESTIMATION_MISS_FACTOR}x or more above the actual rows"
136                ),
137                kind: NotificationKind::EstimationMiss,
138            },
139            PlanWarning::CartesianProduct => VocabularyRow {
140                name: WARNING_CARTESIAN_PRODUCT,
141                text: "the MATCH patterns share no join anchor".to_string(),
142                kind: NotificationKind::CartesianProduct,
143            },
144            PlanWarning::AllNodesScan { .. } => VocabularyRow {
145                name: WARNING_ALL_NODES_SCAN,
146                text: "the scan matches every node; consider the property index".to_string(),
147                kind: NotificationKind::AllNodesScan,
148            },
149            PlanWarning::LabelDisjunctionScan { .. } => VocabularyRow {
150                name: WARNING_LABEL_DISJUNCTION_SCAN,
151                text: "the disjunction scan answers per label; consider the property index"
152                    .to_string(),
153                kind: NotificationKind::LabelDisjunctionScan,
154            },
155        }
156    }
157
158    /// The warning's wire name — the one spelling the wire form
159    /// serializes (`warnings` on the node) and
160    /// [`Self::from_wire_parts`] validates against.
161    pub fn name(&self) -> &'static str {
162        self.vocabulary().name
163    }
164
165    /// The warning's index payload — the `AllNodesScan` warning's suggested
166    /// property index, `None` on the payload-less variants. The one spelling
167    /// of which warnings carry a payload, read by both the message text
168    /// and the wire form's `index` field, so the vocabulary is matched once.
169    pub fn suggested_index(&self) -> Option<&str> {
170        match self {
171            PlanWarning::AllNodesScan { index } => Some(index.as_str()),
172            PlanWarning::LabelDisjunctionScan { indexes } => Some(indexes.as_str()),
173            PlanWarning::EstimationMiss | PlanWarning::CartesianProduct => None,
174        }
175    }
176
177    /// The notification kind this warning projects to (ADR-0363
178    /// decision 1) — from the one exhaustive variant mapping [`Self::name`]
179    /// reads, so a fourth warning variant must choose its vocabulary row
180    /// there rather than falling through a wildcard.
181    ///
182    /// ```rust
183    /// # use relate_model::wire::PlanWarning;
184    /// # use relate_model::wire::NotificationKind;
185    /// assert_eq!(
186    ///     PlanWarning::CartesianProduct.notification_kind(),
187    ///     NotificationKind::CartesianProduct
188    /// );
189    /// assert!(PlanWarning::EstimationMiss
190    ///     .notification_kind()
191    ///     .is_plan_warning());
192    /// ```
193    pub fn notification_kind(&self) -> NotificationKind {
194        self.vocabulary().kind
195    }
196
197    /// The warning's message text — the vocabulary's base text
198    /// ([`Self::vocabulary`]'s one spelling), with the payload appended in
199    /// parentheses when the warning carries one (the `AllNodesScan`
200    /// warning's suggested property index). The one spelling the engine
201    /// renderer and every surface's table layout render, so the text
202    /// cannot drift between the forms.
203    pub fn message(&self) -> String {
204        match self.suggested_index() {
205            Some(index) => format!("{} ({index})", self.vocabulary().text),
206            None => self.vocabulary().text.to_string(),
207        }
208    }
209
210    /// The wire parse — the one validating match back into the typed
211    /// vocabulary: a name from it with the payload shape its variant
212    /// carries (`AllNodesScan` requires the index, the payload-less
213    /// variants carry none). `None` names a warning outside the
214    /// vocabulary or a payload shape its variant does not carry — a
215    /// wire-contract break the accessor fails loudly on, never a
216    /// silently dropped or reinterpreted warning. In-crate today (the
217    /// accessor and the model's tests); re-widened to `pub` in the same
218    /// change as the first cross-crate consumer parsing raw wire
219    /// warning maps.
220    pub(crate) fn from_wire_parts(name: &str, index: Option<&str>) -> Option<Self> {
221        match (name, index) {
222            (WARNING_ESTIMATION_MISS, None) => Some(PlanWarning::EstimationMiss),
223            (WARNING_CARTESIAN_PRODUCT, None) => Some(PlanWarning::CartesianProduct),
224            (WARNING_ALL_NODES_SCAN, Some(index)) => Some(PlanWarning::AllNodesScan {
225                index: index.to_string(),
226            }),
227            (WARNING_LABEL_DISJUNCTION_SCAN, Some(indexes)) => {
228                Some(PlanWarning::LabelDisjunctionScan {
229                    indexes: indexes.to_string(),
230                })
231            }
232            _ => None,
233        }
234    }
235}
236
237/// Whether the estimated-vs-actual ratio is defined (ADR-0344 metric
238/// fields): the operator produced rows. The one predicate both the
239/// ratio cell and the overshoot policy read — never a second
240/// `actual > 0` spelling at either site.
241pub fn ratio_defined(actual: u64) -> bool {
242    actual > 0
243}
244
245/// The one estimated-vs-actual overshoot policy (ADR-0344 metric
246/// fields + typed node warnings): the estimate misses when it
247/// overshoots the actual rows by 10x or more and the operator
248/// produced rows (an estimate over zero actual rows has no ratio).
249/// Both the ratio cell's warning marker and the `EstimationMiss`
250/// warning derive from this one policy, never a second computation.
251pub fn estimation_miss(estimated: u64, actual: u64) -> bool {
252    // Integer comparison — exact for every saturated u64 (f64's 53-bit
253    // mantissa would lose the boundary); floor division preserves the
254    // "ten times or more" test for actual > 0.
255    ratio_defined(actual) && estimated / ESTIMATION_MISS_FACTOR >= actual
256}
257
258/// The wire shape of one typed warning: `{name, index?}`, built from
259/// the one [`PlanWarning`] vocabulary — the spelling the plan-wire
260/// warning projections read (the HTTP v2 plan), never a re-assembled
261/// `{name, index}` at each site. The agent-native document does not read
262/// it: per ADR-0381 its node `warnings` derive from the result's
263/// remedy-bearing notifications.
264pub fn warning_wire_json(warning: &PlanWarning) -> serde_json::Value {
265    let mut out = serde_json::Map::new();
266    out.insert(
267        plan_keys::WARNING_NAME.to_string(),
268        serde_json::Value::String(warning.name().to_string()),
269    );
270    if let Some(index) = warning.suggested_index() {
271        out.insert(
272            plan_keys::WARNING_INDEX.to_string(),
273            serde_json::Value::String(index.to_string()),
274        );
275    }
276    serde_json::Value::Object(out)
277}