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