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