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