Skip to main content

relate_model/
notification_wire.rs

1//! The query-notification vocabulary and its two wire forms (ADR-0363):
2//! one table of kinds (code, GQLSTATUS, severity, category, title and
3//! canonical remedy), the notification record every surface projects from,
4//! and the native and Neo4j-shaped serializers.
5//!
6//! Lives beside the plan vocabulary in `plan_wire` — whose presentation
7//! model lives with its one consumer in the formatter (ADR-0400) — and is
8//! re-exported through [`super`] so `wire::Notification` is the one public
9//! path, matching that layout.
10//!
11//! Two shapes exist by design (ADR-0363 decisions 9/11/12):
12//!
13//! - the **native** form carries `code`, `gql_status`, `severity`,
14//!   `category`, `title`, `description`, `remedy` and — on operator-scoped
15//!   kinds — `operator_id`, with the diagnosis and the action as separate
16//!   fields;
17//! - the **Neo4j-shaped** form (Bolt and the HTTP Query API v2) carries
18//!   exactly `code`, `title`, `description`, `severity`, `category`; the
19//!   remedy folds into `description` as ` (remedy: <remedy>)` and no
20//!   `remedy` or `position` key ever appears.
21
22use serde_json::{Map, Value};
23
24/// The severity spellings (ADR-0363 decision 1): Neo4j's two severities.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum NotificationSeverity {
27    /// An informational hint (`INFORMATION`).
28    Information,
29    /// A warning (`WARNING`).
30    Warning,
31}
32
33impl NotificationSeverity {
34    /// The wire spelling — the one severity vocabulary.
35    pub fn as_str(self) -> &'static str {
36        match self {
37            NotificationSeverity::Information => "INFORMATION",
38            NotificationSeverity::Warning => "WARNING",
39        }
40    }
41}
42
43impl std::fmt::Display for NotificationSeverity {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.write_str(self.as_str())
46    }
47}
48
49/// The category spellings (ADR-0363 decision 1): the categories in scope.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum NotificationCategory {
52    /// A performance hint (`PERFORMANCE`).
53    Performance,
54    /// A name the catalog does not know (`UNRECOGNIZED`).
55    Unrecognized,
56    /// A deprecated feature (`DEPRECATION`).
57    Deprecation,
58    /// A schema DDL note (`SCHEMA`): the informational 00NA0-00NA2 family.
59    Schema,
60    /// An unfulfilled planner hint (`HINT`): the 01N31/01N30 family.
61    Hint,
62}
63
64impl NotificationCategory {
65    /// The wire spelling — the one category vocabulary.
66    pub fn as_str(self) -> &'static str {
67        match self {
68            NotificationCategory::Performance => "PERFORMANCE",
69            NotificationCategory::Unrecognized => "UNRECOGNIZED",
70            NotificationCategory::Deprecation => "DEPRECATION",
71            NotificationCategory::Schema => "SCHEMA",
72            NotificationCategory::Hint => "HINT",
73        }
74    }
75}
76
77impl std::fmt::Display for NotificationCategory {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(self.as_str())
80    }
81}
82
83/// The notification kinds (ADR-0363 decision 1) — the row identities of the
84/// one vocabulary below. `NotificationKind::row` binds each kind to its row
85/// through an exhaustive `match`, so a new kind fails the build until it
86/// names its metadata; no row is reachable by position.
87#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
88pub enum NotificationKind {
89    /// A multi-pattern `MATCH` whose patterns share no join anchor.
90    CartesianProduct,
91    /// A variable-length relationship pattern with no upper bound.
92    UnboundedVariableLengthPattern,
93    /// A label-less node scan while a property index exists.
94    AllNodesScan,
95    /// A static label disjunction no seek serves: the scan answers per
96    /// disjunct label (LABS-1083).
97    LabelDisjunctionScan,
98    /// A label/property equality with no range index on the pair.
99    MissingIndex,
100    /// An aggregation whose input estimate reaches the eager threshold.
101    EagerAggregation,
102    /// `PROFILE` only: an estimate at least 10x the actual rows.
103    EstimationMiss,
104    /// A node pattern naming a label absent from the catalog.
105    UnknownLabelWarning,
106    /// A relationship pattern naming a type absent from the catalog.
107    UnknownRelationshipTypeWarning,
108    /// A predicate or property access naming an absent property key.
109    UnknownPropertyKeyWarning,
110    /// A function call resolving to a deprecated catalog entry.
111    DeprecatedFunction,
112    /// A `CALL` resolving to a deprecated procedure.
113    DeprecatedProcedure,
114    /// A `CALL { … }` subquery with no variable scope clause.
115    CallSubqueryWithoutScope,
116    /// A `MERGE` whose property map references the entity it merges.
117    MergeSelfReference,
118    /// A projection subclause expression (`ORDER BY`/`WHERE`) referencing a
119    /// variable that the projection's own alias re-binds.
120    AmbiguousSubclauseReference,
121    /// A projection subclause expression containing a complex projection
122    /// item expression as a proper sub-expression.
123    ComplexSubclauseReference,
124    /// A `CREATE` whose property definition references an entity created in
125    /// the same clause.
126    CreateSelfReference,
127    /// A variable declared in a subquery that shadows an outer variable.
128    SubqueryVariableShadowing,
129    /// A dynamic property-key predicate on a variable whose label (or
130    /// relationship type) carries an index no static predicate can serve.
131    DynamicProperty,
132    /// A relationship type expression no single type can satisfy.
133    UnsatisfiableRelationshipTypeExpression,
134    /// A relationship variable repeated across pattern elements.
135    RepeatedRelationshipVariable,
136    /// A `SEARCH` index identifier sharing a name with a variable in scope.
137    SearchIdentifierShadowingVariable,
138    /// A `shortestPath` whose predicates force exhaustive evaluation.
139    ExhaustiveShortestPath,
140    /// A schema DDL command that had no effect because an identical or
141    /// schema-equivalent index/constraint already exists (`00NA0`).
142    SchemaIndexOrConstraintAlreadyExists,
143    /// A `DROP INDEX/CONSTRAINT … IF EXISTS` that had no effect because no
144    /// such index/constraint exists (`00NA1`).
145    SchemaIndexOrConstraintDoesNotExist,
146    /// A `CREATE VECTOR INDEX` that omitted `vector.dimensions` (`00NA2`).
147    SchemaVectorIndexDimensionsNotSpecified,
148    /// A `USING INDEX` hint no catalog index can serve (`01N31`).
149    HintedIndexNotFound,
150    /// A `USING JOIN ON` hint the planner could not fulfil (`01N30`).
151    JoinHintUnfulfillable,
152    /// An `OPTIONAL CALL` over a procedure that produces no rows (`03N61`).
153    RedundantOptionalProcedure,
154    /// An `OPTIONAL CALL { … }` whose body projects no columns (`03N62`).
155    RedundantOptionalSubquery,
156}
157
158/// One row of the notification vocabulary (ADR-0363 decision 1). The
159/// trigger column of the ADR's table is documentation for the detector
160/// nodes; the runtime needs the metadata below.
161struct NotificationRow {
162    code: &'static str,
163    gql_status: &'static str,
164    severity: NotificationSeverity,
165    category: NotificationCategory,
166    title: &'static str,
167    remedy: &'static str,
168    /// Whether the plan table renders this kind in its `Warnings` column
169    /// (ADR-0363 decision 8) — the one membership fact `is_plan_warning`
170    /// reads.
171    plan_warning: bool,
172    /// Whether two notifications of this kind with the same description
173    /// are two occurrences that must both be reported (ADR-0363
174    /// decision 6) — the one membership fact `dedups_identical` reads.
175    /// Neo4j reports one notification per occurrence (a deprecated call,
176    /// a clause-shaped deprecation, a per-hint diagnostic), so those kinds
177    /// set it; a name-based diagnostic collapses and does not.
178    occurrence_scoped: bool,
179}
180
181// The one notification vocabulary (ADR-0363 decision 1): every kind's code,
182// GQLSTATUS, severity, category, title and canonical remedy, one named row
183// per `NotificationKind`. Engine-own kinds use the
184// `Relate.Notification.*` namespace and a `C` in GQLSTATUS position 3; a
185// kind whose diagnostic matches Neo4j's keeps Neo4j's code and status.
186const CARTESIAN_PRODUCT_ROW: NotificationRow = NotificationRow {
187    code: "Neo.ClientNotification.Statement.CartesianProduct",
188    gql_status: "03N90",
189    severity: NotificationSeverity::Information,
190    category: NotificationCategory::Performance,
191    title: "Cartesian product",
192    remedy: "Give the patterns a join anchor: reuse a node variable across them, or add a \
193             pattern that relates their endpoints; otherwise run them as separate queries.",
194    plan_warning: true,
195    occurrence_scoped: true,
196};
197
198const UNBOUNDED_VARIABLE_LENGTH_PATTERN_ROW: NotificationRow = NotificationRow {
199    code: "Neo.ClientNotification.Statement.UnboundedVariableLengthPattern",
200    gql_status: "03N91",
201    severity: NotificationSeverity::Information,
202    category: NotificationCategory::Performance,
203    title: "Unbounded variable-length pattern",
204    remedy: "Bound the expansion (`[:R*1..5]`) where arbitrary length is not required, or add \
205             a selective endpoint/label predicate and a `LIMIT`.",
206    plan_warning: false,
207    occurrence_scoped: true,
208};
209
210const ALL_NODES_SCAN_ROW: NotificationRow = NotificationRow {
211    code: "Relate.Notification.Statement.AllNodesScan",
212    gql_status: "03C90",
213    severity: NotificationSeverity::Information,
214    category: NotificationCategory::Performance,
215    title: "All nodes scan",
216    remedy: "Name the label the scan intends (`MATCH (n:<Label>)`); on the index's label the \
217             scan becomes an index-backed lookup.",
218    plan_warning: true,
219    occurrence_scoped: false,
220};
221
222const LABEL_DISJUNCTION_SCAN_ROW: NotificationRow = NotificationRow {
223    code: "Relate.Notification.Statement.LabelDisjunctionScan",
224    gql_status: "03C94",
225    severity: NotificationSeverity::Information,
226    category: NotificationCategory::Performance,
227    title: "Label disjunction scan",
228    remedy: "Create a range index on each disjunct label's filtered property: the disjunction \
229             then serves as per-label keyed lookups instead of per-label scans.",
230    plan_warning: true,
231    occurrence_scoped: false,
232};
233
234const MISSING_INDEX_ROW: NotificationRow = NotificationRow {
235    code: "Relate.Notification.Statement.MissingIndex",
236    gql_status: "03C91",
237    severity: NotificationSeverity::Information,
238    category: NotificationCategory::Performance,
239    title: "Missing index",
240    remedy: "`CREATE INDEX relate_Person__email FOR (n:Person) ON (n.email)` — the exact \
241             runnable statement, with the name derived deterministically from label and \
242             property.",
243    plan_warning: false,
244    occurrence_scoped: false,
245};
246
247const EAGER_AGGREGATION_ROW: NotificationRow = NotificationRow {
248    code: "Relate.Notification.Statement.EagerAggregation",
249    gql_status: "03C92",
250    severity: NotificationSeverity::Information,
251    category: NotificationCategory::Performance,
252    title: "Eager aggregation",
253    remedy: "Reduce the rows reaching the aggregation with a selective label/property \
254             predicate or a `LIMIT` before it; profile again to confirm the buffered input \
255             shrank.",
256    plan_warning: false,
257    occurrence_scoped: false,
258};
259
260const ESTIMATION_MISS_ROW: NotificationRow = NotificationRow {
261    code: "Relate.Notification.Statement.EstimationMiss",
262    gql_status: "03C93",
263    severity: NotificationSeverity::Information,
264    category: NotificationCategory::Performance,
265    title: "Estimation miss",
266    remedy: "Rework the operator's input so the estimate can see the filter (add the \
267             selective predicate at the scan, or reorder the join); the estimate is a planner \
268             assumption, not a runtime fact.",
269    plan_warning: true,
270    occurrence_scoped: false,
271};
272
273const UNKNOWN_LABEL_WARNING_ROW: NotificationRow = NotificationRow {
274    code: "Neo.ClientNotification.Statement.UnknownLabelWarning",
275    gql_status: "01N50",
276    severity: NotificationSeverity::Warning,
277    category: NotificationCategory::Unrecognized,
278    title: "Unknown label",
279    remedy: "Check the spelling; the label exists after the first write that creates it, and \
280             no index or constraint uses the unknown name.",
281    plan_warning: false,
282    occurrence_scoped: false,
283};
284
285const UNKNOWN_RELATIONSHIP_TYPE_WARNING_ROW: NotificationRow = NotificationRow {
286    code: "Neo.ClientNotification.Statement.UnknownRelationshipTypeWarning",
287    gql_status: "01N51",
288    severity: NotificationSeverity::Warning,
289    category: NotificationCategory::Unrecognized,
290    title: "Unknown relationship type",
291    remedy: "Check the spelling; the type exists after the first write that creates it.",
292    plan_warning: false,
293    occurrence_scoped: false,
294};
295
296const UNKNOWN_PROPERTY_KEY_WARNING_ROW: NotificationRow = NotificationRow {
297    code: "Neo.ClientNotification.Statement.UnknownPropertyKeyWarning",
298    gql_status: "01N52",
299    severity: NotificationSeverity::Warning,
300    category: NotificationCategory::Unrecognized,
301    title: "Unknown property key",
302    remedy: "Check the spelling; the key exists after the first write that sets it.",
303    plan_warning: false,
304    occurrence_scoped: false,
305};
306
307const DEPRECATED_FUNCTION_ROW: NotificationRow = NotificationRow {
308    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
309    gql_status: "01N01",
310    severity: NotificationSeverity::Warning,
311    category: NotificationCategory::Deprecation,
312    title: "Deprecated function",
313    remedy: "Replace the call with the catalog's `deprecated_by` (`id(n)` → `elementId(n)`).",
314    plan_warning: false,
315    occurrence_scoped: true,
316};
317
318const DEPRECATED_PROCEDURE_ROW: NotificationRow = NotificationRow {
319    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
320    gql_status: "01N01",
321    severity: NotificationSeverity::Warning,
322    category: NotificationCategory::Deprecation,
323    title: "Deprecated procedure",
324    remedy: "Use the registry's `deprecated_by` replacement instead; the replacement is the \
325             remedy.",
326    plan_warning: false,
327    occurrence_scoped: true,
328};
329
330const CALL_SUBQUERY_WITHOUT_SCOPE_ROW: NotificationRow = NotificationRow {
331    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
332    gql_status: "01N00",
333    severity: NotificationSeverity::Warning,
334    category: NotificationCategory::Deprecation,
335    title: "CALL subquery without scope",
336    remedy: "Add the scope clause the body imports: `CALL (n) { … }`, or `CALL () { … }` when \
337             it imports nothing.",
338    plan_warning: false,
339    occurrence_scoped: true,
340};
341
342const MERGE_SELF_REFERENCE_ROW: NotificationRow = NotificationRow {
343    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
344    gql_status: "01N00",
345    severity: NotificationSeverity::Warning,
346    category: NotificationCategory::Deprecation,
347    title: "Merge self-reference",
348    remedy: "Compute the property into a separate variable before the MERGE, or set it \
349             with ON CREATE SET after the merge.",
350    plan_warning: false,
351    occurrence_scoped: true,
352};
353
354const AMBIGUOUS_SUBCLAUSE_REFERENCE_ROW: NotificationRow = NotificationRow {
355    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
356    gql_status: "01N01",
357    severity: NotificationSeverity::Warning,
358    category: NotificationCategory::Deprecation,
359    title: "Deprecated ambiguous subclause reference",
360    remedy: "Reference the projection item by an alias, or use the `GROUP BY` clause.",
361    plan_warning: false,
362    occurrence_scoped: true,
363};
364
365const COMPLEX_SUBCLAUSE_REFERENCE_ROW: NotificationRow = NotificationRow {
366    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
367    gql_status: "01N01",
368    severity: NotificationSeverity::Warning,
369    category: NotificationCategory::Deprecation,
370    title: "Deprecated complex subclause reference",
371    remedy: "Reference the projection item expression by an alias.",
372    plan_warning: false,
373    occurrence_scoped: true,
374};
375
376const CREATE_SELF_REFERENCE_ROW: NotificationRow = NotificationRow {
377    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
378    gql_status: "01N00",
379    severity: NotificationSeverity::Warning,
380    category: NotificationCategory::Deprecation,
381    title: "Create self-reference",
382    remedy: "Create the entity in a separate `CREATE` clause before referencing it, or set \
383             the property afterwards.",
384    plan_warning: false,
385    occurrence_scoped: true,
386};
387
388const SUBQUERY_VARIABLE_SHADOWING_ROW: NotificationRow = NotificationRow {
389    code: "Neo.ClientNotification.Statement.SubqueryVariableShadowing",
390    gql_status: "03N60",
391    severity: NotificationSeverity::Information,
392    category: NotificationCategory::Unrecognized,
393    title: "Subquery variable shadowing",
394    remedy: "Import the outer variable with `CALL (name) { … }`, or rename the inner one.",
395    plan_warning: false,
396    occurrence_scoped: true,
397};
398
399const DYNAMIC_PROPERTY_ROW: NotificationRow = NotificationRow {
400    code: "Neo.ClientNotification.Statement.DynamicProperty",
401    gql_status: "03N95",
402    severity: NotificationSeverity::Information,
403    category: NotificationCategory::Performance,
404    title: "Queries using dynamic properties will use neither index seeks nor \
405            index scans for those properties",
406    remedy: "Use a static property so index lookups stay possible.",
407    plan_warning: false,
408    occurrence_scoped: false,
409};
410
411const HINTED_INDEX_NOT_FOUND_ROW: NotificationRow = NotificationRow {
412    code: "Neo.ClientNotification.Schema.HintedIndexNotFound",
413    gql_status: "01N31",
414    severity: NotificationSeverity::Warning,
415    category: NotificationCategory::Hint,
416    title: "The request (directly or indirectly) referred to an index that \
417            does not exist.",
418    remedy: "Create the index, or drop the hint.",
419    plan_warning: false,
420    occurrence_scoped: true,
421};
422
423const JOIN_HINT_UNFULFILLABLE_ROW: NotificationRow = NotificationRow {
424    code: "Neo.ClientNotification.Statement.JoinHintUnfulfillableWarning",
425    gql_status: "01N30",
426    severity: NotificationSeverity::Warning,
427    category: NotificationCategory::Hint,
428    title: "The database was unable to plan a hinted join.",
429    remedy: "Try a different join key or restructure the query.",
430    plan_warning: false,
431    occurrence_scoped: true,
432};
433
434const UNSATISFIABLE_RELATIONSHIP_TYPE_EXPRESSION_ROW: NotificationRow = NotificationRow {
435    code: "Neo.ClientNotification.Statement.UnsatisfiableRelationshipTypeExpression",
436    gql_status: "01N61",
437    severity: NotificationSeverity::Warning,
438    category: NotificationCategory::Unrecognized,
439    title: "Unsatisfiable relationship type expression",
440    remedy: "Request one type or a disjunction of types; a relationship has exactly one type.",
441    plan_warning: false,
442    occurrence_scoped: true,
443};
444
445const REPEATED_RELATIONSHIP_VARIABLE_ROW: NotificationRow = NotificationRow {
446    code: "Neo.ClientNotification.Statement.RepeatedRelationshipVariable",
447    gql_status: "01N63",
448    severity: NotificationSeverity::Warning,
449    category: NotificationCategory::Unrecognized,
450    title: "Repeated relationship pattern variable",
451    remedy: "Use a distinct variable per relationship position; a relationship cannot be \
452             traversed twice in one pattern.",
453    plan_warning: false,
454    occurrence_scoped: true,
455};
456
457const SEARCH_IDENTIFIER_SHADOWING_VARIABLE_ROW: NotificationRow = NotificationRow {
458    code: "Neo.ClientNotification.Statement.IdentifierShadowingVariable",
459    gql_status: "03N63",
460    severity: NotificationSeverity::Information,
461    category: NotificationCategory::Unrecognized,
462    title: "Identifier shadowing variable",
463    remedy: "Rename the index or the variable; the index name is taken literally.",
464    plan_warning: false,
465    occurrence_scoped: true,
466};
467
468const EXHAUSTIVE_SHORTEST_PATH_ROW: NotificationRow = NotificationRow {
469    code: "Neo.ClientNotification.Statement.ExhaustiveShortestPath",
470    gql_status: "03N92",
471    severity: NotificationSeverity::Information,
472    category: NotificationCategory::Performance,
473    title: "Exhaustive shortest path",
474    remedy: "Separate the existential predicate from the `MATCH` with `WITH` where possible.",
475    plan_warning: false,
476    occurrence_scoped: true,
477};
478
479const INDEX_OR_CONSTRAINT_ALREADY_EXISTS_ROW: NotificationRow = NotificationRow {
480    code: "Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists",
481    gql_status: "00NA0",
482    severity: NotificationSeverity::Information,
483    category: NotificationCategory::Schema,
484    title: "Index or constraint already exists",
485    remedy: "Drop the existing index or constraint first, or use a different name or schema.",
486    plan_warning: false,
487    occurrence_scoped: false,
488};
489
490const INDEX_OR_CONSTRAINT_DOES_NOT_EXIST_ROW: NotificationRow = NotificationRow {
491    code: "Neo.ClientNotification.Schema.IndexOrConstraintDoesNotExist",
492    gql_status: "00NA1",
493    severity: NotificationSeverity::Information,
494    category: NotificationCategory::Schema,
495    title: "Index or constraint does not exist",
496    remedy: "Check the name; `IF EXISTS` makes a missing index or constraint a no-op.",
497    plan_warning: false,
498    occurrence_scoped: false,
499};
500
501const VECTOR_INDEX_DIMENSIONS_NOT_SPECIFIED_ROW: NotificationRow = NotificationRow {
502    code: "Neo.ClientNotification.Schema.VectorIndexDimensionsNotSpecified",
503    gql_status: "00NA2",
504    severity: NotificationSeverity::Information,
505    category: NotificationCategory::Schema,
506    title: "Vector index dimensions not specified",
507    remedy: "Set `vector.dimensions` in `OPTIONS { indexConfig: { … } }` when creating the index.",
508    plan_warning: false,
509    occurrence_scoped: false,
510};
511
512const REDUNDANT_OPTIONAL_PROCEDURE_ROW: NotificationRow = NotificationRow {
513    code: "Neo.ClientNotification.Statement.RedundantOptionalProcedure",
514    gql_status: "03N61",
515    severity: NotificationSeverity::Information,
516    category: NotificationCategory::Performance,
517    title: "Redundant optional procedure",
518    remedy: "Drop `OPTIONAL`: the procedure declares no return columns, so the call yields \
519             the same single row either way.",
520    plan_warning: false,
521    occurrence_scoped: true,
522};
523
524const REDUNDANT_OPTIONAL_SUBQUERY_ROW: NotificationRow = NotificationRow {
525    code: "Neo.ClientNotification.Statement.RedundantOptionalSubquery",
526    gql_status: "03N62",
527    severity: NotificationSeverity::Information,
528    category: NotificationCategory::Performance,
529    title: "Redundant optional subquery",
530    remedy: "Drop `OPTIONAL`: the subquery projects no columns, so the call yields the same \
531             single row either way.",
532    plan_warning: false,
533    occurrence_scoped: true,
534};
535
536impl NotificationKind {
537    /// The vocabulary row for this kind — the one lookup every metadata
538    /// accessor reads, so no accessor re-spells a code or status. The
539    /// `match` is exhaustive, so a new kind is a compile error until it
540    /// names its row.
541    fn row(self) -> &'static NotificationRow {
542        match self {
543            NotificationKind::CartesianProduct => &CARTESIAN_PRODUCT_ROW,
544            NotificationKind::UnboundedVariableLengthPattern => {
545                &UNBOUNDED_VARIABLE_LENGTH_PATTERN_ROW
546            }
547            NotificationKind::AllNodesScan => &ALL_NODES_SCAN_ROW,
548            NotificationKind::LabelDisjunctionScan => &LABEL_DISJUNCTION_SCAN_ROW,
549            NotificationKind::MissingIndex => &MISSING_INDEX_ROW,
550            NotificationKind::EagerAggregation => &EAGER_AGGREGATION_ROW,
551            NotificationKind::EstimationMiss => &ESTIMATION_MISS_ROW,
552            NotificationKind::UnknownLabelWarning => &UNKNOWN_LABEL_WARNING_ROW,
553            NotificationKind::UnknownRelationshipTypeWarning => {
554                &UNKNOWN_RELATIONSHIP_TYPE_WARNING_ROW
555            }
556            NotificationKind::UnknownPropertyKeyWarning => &UNKNOWN_PROPERTY_KEY_WARNING_ROW,
557            NotificationKind::DeprecatedFunction => &DEPRECATED_FUNCTION_ROW,
558            NotificationKind::DeprecatedProcedure => &DEPRECATED_PROCEDURE_ROW,
559            NotificationKind::CallSubqueryWithoutScope => &CALL_SUBQUERY_WITHOUT_SCOPE_ROW,
560            NotificationKind::MergeSelfReference => &MERGE_SELF_REFERENCE_ROW,
561            NotificationKind::AmbiguousSubclauseReference => &AMBIGUOUS_SUBCLAUSE_REFERENCE_ROW,
562            NotificationKind::ComplexSubclauseReference => &COMPLEX_SUBCLAUSE_REFERENCE_ROW,
563            NotificationKind::CreateSelfReference => &CREATE_SELF_REFERENCE_ROW,
564            NotificationKind::SubqueryVariableShadowing => &SUBQUERY_VARIABLE_SHADOWING_ROW,
565            NotificationKind::DynamicProperty => &DYNAMIC_PROPERTY_ROW,
566            NotificationKind::UnsatisfiableRelationshipTypeExpression => {
567                &UNSATISFIABLE_RELATIONSHIP_TYPE_EXPRESSION_ROW
568            }
569            NotificationKind::RepeatedRelationshipVariable => &REPEATED_RELATIONSHIP_VARIABLE_ROW,
570            NotificationKind::SearchIdentifierShadowingVariable => {
571                &SEARCH_IDENTIFIER_SHADOWING_VARIABLE_ROW
572            }
573            NotificationKind::ExhaustiveShortestPath => &EXHAUSTIVE_SHORTEST_PATH_ROW,
574            NotificationKind::RedundantOptionalProcedure => &REDUNDANT_OPTIONAL_PROCEDURE_ROW,
575            NotificationKind::RedundantOptionalSubquery => &REDUNDANT_OPTIONAL_SUBQUERY_ROW,
576            NotificationKind::SchemaIndexOrConstraintAlreadyExists => {
577                &INDEX_OR_CONSTRAINT_ALREADY_EXISTS_ROW
578            }
579            NotificationKind::SchemaIndexOrConstraintDoesNotExist => {
580                &INDEX_OR_CONSTRAINT_DOES_NOT_EXIST_ROW
581            }
582            NotificationKind::SchemaVectorIndexDimensionsNotSpecified => {
583                &VECTOR_INDEX_DIMENSIONS_NOT_SPECIFIED_ROW
584            }
585            NotificationKind::HintedIndexNotFound => &HINTED_INDEX_NOT_FOUND_ROW,
586            NotificationKind::JoinHintUnfulfillable => &JOIN_HINT_UNFULFILLABLE_ROW,
587        }
588    }
589
590    /// Whether two notifications of this kind with the same description are
591    /// the same finding (`true`) or two occurrences that must both be
592    /// reported (`false`). Name-based diagnostics collapse; every
593    /// occurrence-scoped kind — a deprecated call, a clause-shaped
594    /// deprecation, a per-pattern performance hint — keeps its duplicates,
595    /// because Neo4j reports one notification per occurrence.
596    pub fn dedups_identical(self) -> bool {
597        !self.row().occurrence_scoped
598    }
599
600    /// Whether the plan table already renders this kind (ADR-0363
601    /// decision 8): `CartesianProduct`, `AllNodesScan` and `EstimationMiss`
602    /// are the three `PlanWarning` variants, and their one text rendering is
603    /// the plan table's `Warnings` column plus footer (ADR-0344/0345). The
604    /// other operator-scoped kinds (`UnboundedVariableLengthPattern`,
605    /// `MissingIndex`, `EagerAggregation`) do not join that column, so a
606    /// text block carries them. The membership is the row's `plan_warning`
607    /// column, so a new kind states its side where it names its metadata.
608    pub fn is_plan_warning(self) -> bool {
609        self.row().plan_warning
610    }
611
612    /// The diagnostic code (`Neo.ClientNotification.*` for a Neo4j analog,
613    /// `Relate.Notification.*` for an engine-own kind).
614    pub fn code(self) -> &'static str {
615        self.row().code
616    }
617
618    /// The GQLSTATUS value (`03N90`, `03C90`, `01N50`, …).
619    pub fn gql_status(self) -> &'static str {
620        self.row().gql_status
621    }
622
623    /// The severity (INFORMATION or WARNING).
624    pub fn severity(self) -> NotificationSeverity {
625        self.row().severity
626    }
627
628    /// The category (PERFORMANCE, UNRECOGNIZED or DEPRECATION).
629    pub fn category(self) -> NotificationCategory {
630        self.row().category
631    }
632
633    /// The one canonical human title for this kind — defined here, never
634    /// invented by a caller.
635    pub fn title(self) -> &'static str {
636        self.row().title
637    }
638
639    /// The kind's canonical remedy, used when a notification carries no
640    /// instance-specific one.
641    pub fn remedy(self) -> &'static str {
642        self.row().remedy
643    }
644}
645
646/// One query notification (ADR-0363 decision 1): the record
647/// `{ kind, description, remedy, operator_id }`.
648///
649/// The kind supplies the metadata — code, GQLSTATUS, severity, category,
650/// title and the canonical remedy — so the record stores no copy of it and
651/// the two cannot drift. `description` carries the instance detail (the
652/// unknown name, the index text, the procedure name); an instance-specific
653/// `remedy` overrides the kind's canonical text where the detector can name
654/// the precise action (the exact `CREATE INDEX`, the `deprecated_by`
655/// replacement). `operator_id` is the raising operator's `PlanNode.id`,
656/// present only on operator-scoped kinds.
657#[derive(Clone, Debug, PartialEq, Eq)]
658pub struct Notification {
659    kind: NotificationKind,
660    description: String,
661    remedy: Option<String>,
662    operator_id: Option<usize>,
663}
664
665impl Notification {
666    /// One notification of `kind` with its instance `description`; no
667    /// instance remedy (the kind's canonical remedy applies) and no
668    /// operator association (statement-scoped until [`Self::with_operator_id`]).
669    pub fn new(kind: NotificationKind, description: impl Into<String>) -> Self {
670        Notification {
671            kind,
672            description: description.into(),
673            remedy: None,
674            operator_id: None,
675        }
676    }
677
678    /// Attach an operator association — the raising `PlanNode.id` — the one
679    /// way an operator-scoped notification gains `operator_id`.
680    pub fn with_operator_id(mut self, operator_id: usize) -> Self {
681        self.operator_id = Some(operator_id);
682        self
683    }
684
685    /// Override the kind's canonical remedy with the instance-specific
686    /// action (the exact runnable statement, the replacement name).
687    pub fn with_remedy(mut self, remedy: impl Into<String>) -> Self {
688        self.remedy = Some(remedy.into());
689        self
690    }
691
692    /// The notification's kind — the vocabulary row identity.
693    pub fn kind(&self) -> NotificationKind {
694        self.kind
695    }
696
697    /// The instance detail — the unknown name, index text, procedure name
698    /// or warning message.
699    pub fn description(&self) -> &str {
700        &self.description
701    }
702
703    /// The kind's diagnostic code.
704    pub fn code(&self) -> &'static str {
705        self.kind.code()
706    }
707
708    /// The kind's GQLSTATUS value.
709    pub fn gql_status(&self) -> &'static str {
710        self.kind.gql_status()
711    }
712
713    /// The kind's canonical title.
714    pub fn title(&self) -> &'static str {
715        self.kind.title()
716    }
717
718    /// The kind's severity.
719    pub fn severity(&self) -> NotificationSeverity {
720        self.kind.severity()
721    }
722
723    /// The kind's category.
724    pub fn category(&self) -> NotificationCategory {
725        self.kind.category()
726    }
727
728    /// The effective remedy: the instance-specific one when the detector
729    /// supplied it, else the kind's canonical remedy. Every vocabulary kind
730    /// carries a remedy, so this is never absent.
731    pub fn remedy(&self) -> &str {
732        self.remedy.as_deref().unwrap_or_else(|| self.kind.remedy())
733    }
734
735    /// The raising operator's `PlanNode.id`, on operator-scoped kinds only.
736    pub fn operator_id(&self) -> Option<usize> {
737        self.operator_id
738    }
739}
740
741/// The engine-native notification keys (ADR-0363 decision 9) — the
742/// vocabulary [`notification_to_wire_json`] emits and every consumer
743/// reads, single-sourced like [`super::plan_keys`].
744pub mod notification_keys {
745    /// The diagnostic code.
746    pub const CODE: &str = "code";
747    /// The GQLSTATUS value.
748    pub const GQL_STATUS: &str = "gql_status";
749    /// The severity spelling.
750    pub const SEVERITY: &str = "severity";
751    /// The category spelling.
752    pub const CATEGORY: &str = "category";
753    /// The canonical title.
754    pub const TITLE: &str = "title";
755    /// The instance diagnosis.
756    pub const DESCRIPTION: &str = "description";
757    /// The effective remedy (always present on the native form).
758    pub const REMEDY: &str = "remedy";
759    /// The raising operator's id (operator-scoped kinds only).
760    pub const OPERATOR_ID: &str = "operator_id";
761    /// The response envelope's always-present notification list.
762    pub const NOTIFICATIONS: &str = "notifications";
763}
764
765/// The seven diagnostic fields of one notification's engine-native wire
766/// object, keyed by the [`notification_keys`] vocabulary — the core
767/// [`notification_to_wire_json`] layers the operator id onto, and the exact
768/// object the agent-native plan document projects for a node's `warnings`
769/// (the node already scopes the operator, so the join key is not repeated
770/// there). One spelling of the field set, so a field added to the canonical
771/// notification reaches every projection instead of drifting in a second
772/// hand-rolled one.
773pub(crate) fn notification_fields(notification: &Notification) -> Map<String, Value> {
774    let mut obj = Map::new();
775    obj.insert(
776        notification_keys::CODE.into(),
777        Value::String(notification.code().into()),
778    );
779    obj.insert(
780        notification_keys::GQL_STATUS.into(),
781        Value::String(notification.gql_status().into()),
782    );
783    obj.insert(
784        notification_keys::SEVERITY.into(),
785        Value::String(notification.severity().as_str().into()),
786    );
787    obj.insert(
788        notification_keys::CATEGORY.into(),
789        Value::String(notification.category().as_str().into()),
790    );
791    obj.insert(
792        notification_keys::TITLE.into(),
793        Value::String(notification.title().into()),
794    );
795    obj.insert(
796        notification_keys::DESCRIPTION.into(),
797        Value::String(notification.description().into()),
798    );
799    obj.insert(
800        notification_keys::REMEDY.into(),
801        Value::String(notification.remedy().into()),
802    );
803    obj
804}
805
806/// One notification's engine-native wire object (ADR-0363 decision 9):
807/// `code`, `gql_status`, `severity`, `category`, `title`, `description`,
808/// `remedy` and — on operator-scoped kinds — `operator_id`.
809pub fn notification_to_wire_json(notification: &Notification) -> Value {
810    let mut obj = notification_fields(notification);
811    if let Some(operator_id) = notification.operator_id() {
812        obj.insert(
813            notification_keys::OPERATOR_ID.into(),
814            Value::from(operator_id),
815        );
816    }
817    Value::Object(obj)
818}
819
820/// A notification list in the engine-native form — the array the shared
821/// success envelope always carries (empty on a plain run).
822pub fn notifications_to_wire_json(notifications: &[Notification]) -> Value {
823    Value::Array(
824        notifications
825            .iter()
826            .map(notification_to_wire_json)
827            .collect(),
828    )
829}
830
831/// One notification's Neo4j-shaped entries (ADR-0363 decisions 11/12), in
832/// Bolt's entry order: `code`, `title`, `description`, `severity`,
833/// `category`. The effective remedy is folded into `description` as
834/// ` (remedy: <remedy>)`; no `remedy` and no `position` entry is ever
835/// emitted. This is the ordered form Bolt packs directly, without building
836/// or re-reading a JSON object; [`notification_to_neo4j_json`] is the JSON
837/// projection of the same entries.
838pub fn notification_to_neo4j_entries(notification: &Notification) -> Vec<(&'static str, String)> {
839    vec![
840        (notification_keys::CODE, notification.code().to_string()),
841        (notification_keys::TITLE, notification.title().to_string()),
842        (
843            notification_keys::DESCRIPTION,
844            format!(
845                "{} (remedy: {})",
846                notification.description(),
847                notification.remedy()
848            ),
849        ),
850        (
851            notification_keys::SEVERITY,
852            notification.severity().as_str().to_string(),
853        ),
854        (
855            notification_keys::CATEGORY,
856            notification.category().as_str().to_string(),
857        ),
858    ]
859}
860
861/// One notification's Neo4j-shaped wire object (ADR-0363 decisions 11/12):
862/// exactly `code`, `title`, `description`, `severity`, `category`, with the
863/// remedy folded into `description` as ` (remedy: <remedy>)` and no `remedy`
864/// or `position` key. Built from [`notification_to_neo4j_entries`].
865///
866/// `serde_json::Map` is a sorted map in this workspace (it does not enable
867/// `preserve_order`), so the object's key order is sorted, not Bolt's.
868/// Callers that emit ordered entries — Bolt — read
869/// [`notification_to_neo4j_entries`] instead.
870pub fn notification_to_neo4j_json(notification: &Notification) -> Value {
871    let obj: Map<String, Value> = notification_to_neo4j_entries(notification)
872        .into_iter()
873        .map(|(key, value)| (key.to_owned(), Value::String(value)))
874        .collect();
875    Value::Object(obj)
876}
877
878#[cfg(test)]
879#[path = "notification_wire/tests.rs"]
880mod tests;