relate-model 1.0.0

Data model types (CypherValue) for the Relate graph database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! The query-notification vocabulary and its two wire forms (ADR-0363):
//! one table of kinds (code, GQLSTATUS, severity, category, title and
//! canonical remedy), the notification record every surface projects from,
//! and the native and Neo4j-shaped serializers.
//!
//! Lives beside the plan vocabulary in `plan_wire` — whose presentation
//! model lives with its one consumer in the formatter (ADR-0400) — and is
//! re-exported through [`super`] so `wire::Notification` is the one public
//! path, matching that layout.
//!
//! Two shapes exist by design (ADR-0363 decisions 9/11/12):
//!
//! - the **native** form carries `code`, `gql_status`, `severity`,
//!   `category`, `title`, `description`, `remedy` and — on operator-scoped
//!   kinds — `operator_id`, with the diagnosis and the action as separate
//!   fields;
//! - the **Neo4j-shaped** form (Bolt and the HTTP Query API v2) carries
//!   exactly `code`, `title`, `description`, `severity`, `category`; the
//!   remedy folds into `description` as ` (remedy: <remedy>)` and no
//!   `remedy` or `position` key ever appears.

use serde_json::{Map, Value};

/// The severity spellings (ADR-0363 decision 1): Neo4j's two severities.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NotificationSeverity {
    /// An informational hint (`INFORMATION`).
    Information,
    /// A warning (`WARNING`).
    Warning,
}

impl NotificationSeverity {
    /// The wire spelling — the one severity vocabulary.
    pub fn as_str(self) -> &'static str {
        match self {
            NotificationSeverity::Information => "INFORMATION",
            NotificationSeverity::Warning => "WARNING",
        }
    }
}

impl std::fmt::Display for NotificationSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The category spellings (ADR-0363 decision 1): the categories in scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NotificationCategory {
    /// A performance hint (`PERFORMANCE`).
    Performance,
    /// A name the catalog does not know (`UNRECOGNIZED`).
    Unrecognized,
    /// A deprecated feature (`DEPRECATION`).
    Deprecation,
    /// A schema DDL note (`SCHEMA`): the informational 00NA0-00NA2 family.
    Schema,
    /// An unfulfilled planner hint (`HINT`): the 01N31/01N30 family.
    Hint,
}

impl NotificationCategory {
    /// The wire spelling — the one category vocabulary.
    pub fn as_str(self) -> &'static str {
        match self {
            NotificationCategory::Performance => "PERFORMANCE",
            NotificationCategory::Unrecognized => "UNRECOGNIZED",
            NotificationCategory::Deprecation => "DEPRECATION",
            NotificationCategory::Schema => "SCHEMA",
            NotificationCategory::Hint => "HINT",
        }
    }
}

impl std::fmt::Display for NotificationCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The notification kinds (ADR-0363 decision 1) — the row identities of the
/// one vocabulary below. `NotificationKind::row` binds each kind to its row
/// through an exhaustive `match`, so a new kind fails the build until it
/// names its metadata; no row is reachable by position.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotificationKind {
    /// A multi-pattern `MATCH` whose patterns share no join anchor.
    CartesianProduct,
    /// A variable-length relationship pattern with no upper bound.
    UnboundedVariableLengthPattern,
    /// A label-less node scan while a property index exists.
    AllNodesScan,
    /// A static label disjunction no seek serves: the scan answers per
    /// disjunct label (LABS-1083).
    LabelDisjunctionScan,
    /// A label/property equality with no range index on the pair.
    MissingIndex,
    /// An aggregation whose input estimate reaches the eager threshold.
    EagerAggregation,
    /// `PROFILE` only: an estimate at least 10x the actual rows.
    EstimationMiss,
    /// A node pattern naming a label absent from the catalog.
    UnknownLabelWarning,
    /// A relationship pattern naming a type absent from the catalog.
    UnknownRelationshipTypeWarning,
    /// A predicate or property access naming an absent property key.
    UnknownPropertyKeyWarning,
    /// A function call resolving to a deprecated catalog entry.
    DeprecatedFunction,
    /// A `CALL` resolving to a deprecated procedure.
    DeprecatedProcedure,
    /// A `CALL { … }` subquery with no variable scope clause.
    CallSubqueryWithoutScope,
    /// A `MERGE` whose property map references the entity it merges.
    MergeSelfReference,
    /// A projection subclause expression (`ORDER BY`/`WHERE`) referencing a
    /// variable that the projection's own alias re-binds.
    AmbiguousSubclauseReference,
    /// A projection subclause expression containing a complex projection
    /// item expression as a proper sub-expression.
    ComplexSubclauseReference,
    /// A `CREATE` whose property definition references an entity created in
    /// the same clause.
    CreateSelfReference,
    /// A variable declared in a subquery that shadows an outer variable.
    SubqueryVariableShadowing,
    /// A dynamic property-key predicate on a variable whose label (or
    /// relationship type) carries an index no static predicate can serve.
    DynamicProperty,
    /// A relationship type expression no single type can satisfy.
    UnsatisfiableRelationshipTypeExpression,
    /// A relationship variable repeated across pattern elements.
    RepeatedRelationshipVariable,
    /// A `SEARCH` index identifier sharing a name with a variable in scope.
    SearchIdentifierShadowingVariable,
    /// A `shortestPath` whose predicates force exhaustive evaluation.
    ExhaustiveShortestPath,
    /// A schema DDL command that had no effect because an identical or
    /// schema-equivalent index/constraint already exists (`00NA0`).
    SchemaIndexOrConstraintAlreadyExists,
    /// A `DROP INDEX/CONSTRAINT … IF EXISTS` that had no effect because no
    /// such index/constraint exists (`00NA1`).
    SchemaIndexOrConstraintDoesNotExist,
    /// A `CREATE VECTOR INDEX` that omitted `vector.dimensions` (`00NA2`).
    SchemaVectorIndexDimensionsNotSpecified,
    /// A `USING INDEX` hint no catalog index can serve (`01N31`).
    HintedIndexNotFound,
    /// A `USING JOIN ON` hint the planner could not fulfil (`01N30`).
    JoinHintUnfulfillable,
}

/// One row of the notification vocabulary (ADR-0363 decision 1). The
/// trigger column of the ADR's table is documentation for the detector
/// nodes; the runtime needs the metadata below.
struct NotificationRow {
    code: &'static str,
    gql_status: &'static str,
    severity: NotificationSeverity,
    category: NotificationCategory,
    title: &'static str,
    remedy: &'static str,
    /// Whether the plan table renders this kind in its `Warnings` column
    /// (ADR-0363 decision 8) — the one membership fact `is_plan_warning`
    /// reads.
    plan_warning: bool,
    /// Whether two notifications of this kind with the same description
    /// are two occurrences that must both be reported (ADR-0363
    /// decision 6) — the one membership fact `dedups_identical` reads.
    /// Neo4j reports one notification per occurrence (a deprecated call,
    /// a clause-shaped deprecation, a per-hint diagnostic), so those kinds
    /// set it; a name-based diagnostic collapses and does not.
    occurrence_scoped: bool,
}

// The one notification vocabulary (ADR-0363 decision 1): every kind's code,
// GQLSTATUS, severity, category, title and canonical remedy, one named row
// per `NotificationKind`. Engine-own kinds use the
// `Relate.Notification.*` namespace and a `C` in GQLSTATUS position 3; a
// kind whose diagnostic matches Neo4j's keeps Neo4j's code and status.
const CARTESIAN_PRODUCT_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.CartesianProduct",
    gql_status: "03N90",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Cartesian product",
    remedy: "Give the patterns a join anchor: reuse a node variable across them, or add a \
             pattern that relates their endpoints; otherwise run them as separate queries.",
    plan_warning: true,
    occurrence_scoped: true,
};

const UNBOUNDED_VARIABLE_LENGTH_PATTERN_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.UnboundedVariableLengthPattern",
    gql_status: "03N91",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Unbounded variable-length pattern",
    remedy: "Bound the expansion (`[:R*1..5]`) where arbitrary length is not required, or add \
             a selective endpoint/label predicate and a `LIMIT`.",
    plan_warning: false,
    occurrence_scoped: true,
};

const ALL_NODES_SCAN_ROW: NotificationRow = NotificationRow {
    code: "Relate.Notification.Statement.AllNodesScan",
    gql_status: "03C90",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "All nodes scan",
    remedy: "Name the label the scan intends (`MATCH (n:<Label>)`); on the index's label the \
             scan becomes an index-backed lookup.",
    plan_warning: true,
    occurrence_scoped: false,
};

const LABEL_DISJUNCTION_SCAN_ROW: NotificationRow = NotificationRow {
    code: "Relate.Notification.Statement.LabelDisjunctionScan",
    gql_status: "03C94",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Label disjunction scan",
    remedy: "Create a range index on each disjunct label's filtered property: the disjunction \
             then serves as per-label keyed lookups instead of per-label scans.",
    plan_warning: true,
    occurrence_scoped: false,
};

const MISSING_INDEX_ROW: NotificationRow = NotificationRow {
    code: "Relate.Notification.Statement.MissingIndex",
    gql_status: "03C91",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Missing index",
    remedy: "`CREATE INDEX relate_Person__email FOR (n:Person) ON (n.email)` — the exact \
             runnable statement, with the name derived deterministically from label and \
             property.",
    plan_warning: false,
    occurrence_scoped: false,
};

const EAGER_AGGREGATION_ROW: NotificationRow = NotificationRow {
    code: "Relate.Notification.Statement.EagerAggregation",
    gql_status: "03C92",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Eager aggregation",
    remedy: "Reduce the rows reaching the aggregation with a selective label/property \
             predicate or a `LIMIT` before it; profile again to confirm the buffered input \
             shrank.",
    plan_warning: false,
    occurrence_scoped: false,
};

const ESTIMATION_MISS_ROW: NotificationRow = NotificationRow {
    code: "Relate.Notification.Statement.EstimationMiss",
    gql_status: "03C93",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Estimation miss",
    remedy: "Rework the operator's input so the estimate can see the filter (add the \
             selective predicate at the scan, or reorder the join); the estimate is a planner \
             assumption, not a runtime fact.",
    plan_warning: true,
    occurrence_scoped: false,
};

const UNKNOWN_LABEL_WARNING_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.UnknownLabelWarning",
    gql_status: "01N50",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Unrecognized,
    title: "Unknown label",
    remedy: "Check the spelling; the label exists after the first write that creates it, and \
             no index or constraint uses the unknown name.",
    plan_warning: false,
    occurrence_scoped: false,
};

const UNKNOWN_RELATIONSHIP_TYPE_WARNING_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.UnknownRelationshipTypeWarning",
    gql_status: "01N51",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Unrecognized,
    title: "Unknown relationship type",
    remedy: "Check the spelling; the type exists after the first write that creates it.",
    plan_warning: false,
    occurrence_scoped: false,
};

const UNKNOWN_PROPERTY_KEY_WARNING_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.UnknownPropertyKeyWarning",
    gql_status: "01N52",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Unrecognized,
    title: "Unknown property key",
    remedy: "Check the spelling; the key exists after the first write that sets it.",
    plan_warning: false,
    occurrence_scoped: false,
};

const DEPRECATED_FUNCTION_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N01",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Deprecated function",
    remedy: "Replace the call with the catalog's `deprecated_by` (`id(n)` → `elementId(n)`).",
    plan_warning: false,
    occurrence_scoped: true,
};

const DEPRECATED_PROCEDURE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N01",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Deprecated procedure",
    remedy: "Use the registry's `deprecated_by` replacement instead; the replacement is the \
             remedy.",
    plan_warning: false,
    occurrence_scoped: true,
};

const CALL_SUBQUERY_WITHOUT_SCOPE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N00",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "CALL subquery without scope",
    remedy: "Add the scope clause the body imports: `CALL (n) { … }`, or `CALL () { … }` when \
             it imports nothing.",
    plan_warning: false,
    occurrence_scoped: true,
};

const MERGE_SELF_REFERENCE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N00",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Merge self-reference",
    remedy: "Compute the property into a separate variable before the MERGE, or set it \
             with ON CREATE SET after the merge.",
    plan_warning: false,
    occurrence_scoped: true,
};

const AMBIGUOUS_SUBCLAUSE_REFERENCE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N01",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Deprecated ambiguous subclause reference",
    remedy: "Reference the projection item by an alias, or use the `GROUP BY` clause.",
    plan_warning: false,
    occurrence_scoped: true,
};

const COMPLEX_SUBCLAUSE_REFERENCE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N01",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Deprecated complex subclause reference",
    remedy: "Reference the projection item expression by an alias.",
    plan_warning: false,
    occurrence_scoped: true,
};

const CREATE_SELF_REFERENCE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.FeatureDeprecationWarning",
    gql_status: "01N00",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Deprecation,
    title: "Create self-reference",
    remedy: "Create the entity in a separate `CREATE` clause before referencing it, or set \
             the property afterwards.",
    plan_warning: false,
    occurrence_scoped: true,
};

const SUBQUERY_VARIABLE_SHADOWING_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.SubqueryVariableShadowing",
    gql_status: "03N60",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Unrecognized,
    title: "Subquery variable shadowing",
    remedy: "Import the outer variable with `CALL (name) { … }`, or rename the inner one.",
    plan_warning: false,
    occurrence_scoped: true,
};

const DYNAMIC_PROPERTY_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.DynamicProperty",
    gql_status: "03N95",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Queries using dynamic properties will use neither index seeks nor \
            index scans for those properties",
    remedy: "Use a static property so index lookups stay possible.",
    plan_warning: false,
    occurrence_scoped: false,
};

const HINTED_INDEX_NOT_FOUND_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Schema.HintedIndexNotFound",
    gql_status: "01N31",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Hint,
    title: "The request (directly or indirectly) referred to an index that \
            does not exist.",
    remedy: "Create the index, or drop the hint.",
    plan_warning: false,
    occurrence_scoped: true,
};

const JOIN_HINT_UNFULFILLABLE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.JoinHintUnfulfillableWarning",
    gql_status: "01N30",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Hint,
    title: "The database was unable to plan a hinted join.",
    remedy: "Try a different join key or restructure the query.",
    plan_warning: false,
    occurrence_scoped: true,
};

const UNSATISFIABLE_RELATIONSHIP_TYPE_EXPRESSION_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.UnsatisfiableRelationshipTypeExpression",
    gql_status: "01N61",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Unrecognized,
    title: "Unsatisfiable relationship type expression",
    remedy: "Request one type or a disjunction of types; a relationship has exactly one type.",
    plan_warning: false,
    occurrence_scoped: true,
};

const REPEATED_RELATIONSHIP_VARIABLE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.RepeatedRelationshipVariable",
    gql_status: "01N63",
    severity: NotificationSeverity::Warning,
    category: NotificationCategory::Unrecognized,
    title: "Repeated relationship pattern variable",
    remedy: "Use a distinct variable per relationship position; a relationship cannot be \
             traversed twice in one pattern.",
    plan_warning: false,
    occurrence_scoped: true,
};

const SEARCH_IDENTIFIER_SHADOWING_VARIABLE_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.IdentifierShadowingVariable",
    gql_status: "03N63",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Unrecognized,
    title: "Identifier shadowing variable",
    remedy: "Rename the index or the variable; the index name is taken literally.",
    plan_warning: false,
    occurrence_scoped: true,
};

const EXHAUSTIVE_SHORTEST_PATH_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Statement.ExhaustiveShortestPath",
    gql_status: "03N92",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Performance,
    title: "Exhaustive shortest path",
    remedy: "Separate the existential predicate from the `MATCH` with `WITH` where possible.",
    plan_warning: false,
    occurrence_scoped: true,
};

const INDEX_OR_CONSTRAINT_ALREADY_EXISTS_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists",
    gql_status: "00NA0",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Schema,
    title: "Index or constraint already exists",
    remedy: "Drop the existing index or constraint first, or use a different name or schema.",
    plan_warning: false,
    occurrence_scoped: false,
};

const INDEX_OR_CONSTRAINT_DOES_NOT_EXIST_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Schema.IndexOrConstraintDoesNotExist",
    gql_status: "00NA1",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Schema,
    title: "Index or constraint does not exist",
    remedy: "Check the name; `IF EXISTS` makes a missing index or constraint a no-op.",
    plan_warning: false,
    occurrence_scoped: false,
};

const VECTOR_INDEX_DIMENSIONS_NOT_SPECIFIED_ROW: NotificationRow = NotificationRow {
    code: "Neo.ClientNotification.Schema.VectorIndexDimensionsNotSpecified",
    gql_status: "00NA2",
    severity: NotificationSeverity::Information,
    category: NotificationCategory::Schema,
    title: "Vector index dimensions not specified",
    remedy: "Set `vector.dimensions` in `OPTIONS { indexConfig: { … } }` when creating the index.",
    plan_warning: false,
    occurrence_scoped: false,
};

impl NotificationKind {
    /// The vocabulary row for this kind — the one lookup every metadata
    /// accessor reads, so no accessor re-spells a code or status. The
    /// `match` is exhaustive, so a new kind is a compile error until it
    /// names its row.
    fn row(self) -> &'static NotificationRow {
        match self {
            NotificationKind::CartesianProduct => &CARTESIAN_PRODUCT_ROW,
            NotificationKind::UnboundedVariableLengthPattern => {
                &UNBOUNDED_VARIABLE_LENGTH_PATTERN_ROW
            }
            NotificationKind::AllNodesScan => &ALL_NODES_SCAN_ROW,
            NotificationKind::LabelDisjunctionScan => &LABEL_DISJUNCTION_SCAN_ROW,
            NotificationKind::MissingIndex => &MISSING_INDEX_ROW,
            NotificationKind::EagerAggregation => &EAGER_AGGREGATION_ROW,
            NotificationKind::EstimationMiss => &ESTIMATION_MISS_ROW,
            NotificationKind::UnknownLabelWarning => &UNKNOWN_LABEL_WARNING_ROW,
            NotificationKind::UnknownRelationshipTypeWarning => {
                &UNKNOWN_RELATIONSHIP_TYPE_WARNING_ROW
            }
            NotificationKind::UnknownPropertyKeyWarning => &UNKNOWN_PROPERTY_KEY_WARNING_ROW,
            NotificationKind::DeprecatedFunction => &DEPRECATED_FUNCTION_ROW,
            NotificationKind::DeprecatedProcedure => &DEPRECATED_PROCEDURE_ROW,
            NotificationKind::CallSubqueryWithoutScope => &CALL_SUBQUERY_WITHOUT_SCOPE_ROW,
            NotificationKind::MergeSelfReference => &MERGE_SELF_REFERENCE_ROW,
            NotificationKind::AmbiguousSubclauseReference => &AMBIGUOUS_SUBCLAUSE_REFERENCE_ROW,
            NotificationKind::ComplexSubclauseReference => &COMPLEX_SUBCLAUSE_REFERENCE_ROW,
            NotificationKind::CreateSelfReference => &CREATE_SELF_REFERENCE_ROW,
            NotificationKind::SubqueryVariableShadowing => &SUBQUERY_VARIABLE_SHADOWING_ROW,
            NotificationKind::DynamicProperty => &DYNAMIC_PROPERTY_ROW,
            NotificationKind::UnsatisfiableRelationshipTypeExpression => {
                &UNSATISFIABLE_RELATIONSHIP_TYPE_EXPRESSION_ROW
            }
            NotificationKind::RepeatedRelationshipVariable => &REPEATED_RELATIONSHIP_VARIABLE_ROW,
            NotificationKind::SearchIdentifierShadowingVariable => {
                &SEARCH_IDENTIFIER_SHADOWING_VARIABLE_ROW
            }
            NotificationKind::ExhaustiveShortestPath => &EXHAUSTIVE_SHORTEST_PATH_ROW,
            NotificationKind::SchemaIndexOrConstraintAlreadyExists => {
                &INDEX_OR_CONSTRAINT_ALREADY_EXISTS_ROW
            }
            NotificationKind::SchemaIndexOrConstraintDoesNotExist => {
                &INDEX_OR_CONSTRAINT_DOES_NOT_EXIST_ROW
            }
            NotificationKind::SchemaVectorIndexDimensionsNotSpecified => {
                &VECTOR_INDEX_DIMENSIONS_NOT_SPECIFIED_ROW
            }
            NotificationKind::HintedIndexNotFound => &HINTED_INDEX_NOT_FOUND_ROW,
            NotificationKind::JoinHintUnfulfillable => &JOIN_HINT_UNFULFILLABLE_ROW,
        }
    }

    /// Whether two notifications of this kind with the same description are
    /// the same finding (`true`) or two occurrences that must both be
    /// reported (`false`). Name-based diagnostics collapse; every
    /// occurrence-scoped kind — a deprecated call, a clause-shaped
    /// deprecation, a per-pattern performance hint — keeps its duplicates,
    /// because Neo4j reports one notification per occurrence.
    pub fn dedups_identical(self) -> bool {
        !self.row().occurrence_scoped
    }

    /// Whether the plan table already renders this kind (ADR-0363
    /// decision 8): `CartesianProduct`, `AllNodesScan` and `EstimationMiss`
    /// are the three `PlanWarning` variants, and their one text rendering is
    /// the plan table's `Warnings` column plus footer (ADR-0344/0345). The
    /// other operator-scoped kinds (`UnboundedVariableLengthPattern`,
    /// `MissingIndex`, `EagerAggregation`) do not join that column, so a
    /// text block carries them. The membership is the row's `plan_warning`
    /// column, so a new kind states its side where it names its metadata.
    pub fn is_plan_warning(self) -> bool {
        self.row().plan_warning
    }

    /// The diagnostic code (`Neo.ClientNotification.*` for a Neo4j analog,
    /// `Relate.Notification.*` for an engine-own kind).
    pub fn code(self) -> &'static str {
        self.row().code
    }

    /// The GQLSTATUS value (`03N90`, `03C90`, `01N50`, …).
    pub fn gql_status(self) -> &'static str {
        self.row().gql_status
    }

    /// The severity (INFORMATION or WARNING).
    pub fn severity(self) -> NotificationSeverity {
        self.row().severity
    }

    /// The category (PERFORMANCE, UNRECOGNIZED or DEPRECATION).
    pub fn category(self) -> NotificationCategory {
        self.row().category
    }

    /// The one canonical human title for this kind — defined here, never
    /// invented by a caller.
    pub fn title(self) -> &'static str {
        self.row().title
    }

    /// The kind's canonical remedy, used when a notification carries no
    /// instance-specific one.
    pub fn remedy(self) -> &'static str {
        self.row().remedy
    }
}

/// One query notification (ADR-0363 decision 1): the record
/// `{ kind, description, remedy, operator_id }`.
///
/// The kind supplies the metadata — code, GQLSTATUS, severity, category,
/// title and the canonical remedy — so the record stores no copy of it and
/// the two cannot drift. `description` carries the instance detail (the
/// unknown name, the index text, the procedure name); an instance-specific
/// `remedy` overrides the kind's canonical text where the detector can name
/// the precise action (the exact `CREATE INDEX`, the `deprecated_by`
/// replacement). `operator_id` is the raising operator's `PlanNode.id`,
/// present only on operator-scoped kinds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notification {
    kind: NotificationKind,
    description: String,
    remedy: Option<String>,
    operator_id: Option<usize>,
}

impl Notification {
    /// One notification of `kind` with its instance `description`; no
    /// instance remedy (the kind's canonical remedy applies) and no
    /// operator association (statement-scoped until [`Self::with_operator_id`]).
    pub fn new(kind: NotificationKind, description: impl Into<String>) -> Self {
        Notification {
            kind,
            description: description.into(),
            remedy: None,
            operator_id: None,
        }
    }

    /// Attach an operator association — the raising `PlanNode.id` — the one
    /// way an operator-scoped notification gains `operator_id`.
    pub fn with_operator_id(mut self, operator_id: usize) -> Self {
        self.operator_id = Some(operator_id);
        self
    }

    /// Override the kind's canonical remedy with the instance-specific
    /// action (the exact runnable statement, the replacement name).
    pub fn with_remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    /// The notification's kind — the vocabulary row identity.
    pub fn kind(&self) -> NotificationKind {
        self.kind
    }

    /// The instance detail — the unknown name, index text, procedure name
    /// or warning message.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// The kind's diagnostic code.
    pub fn code(&self) -> &'static str {
        self.kind.code()
    }

    /// The kind's GQLSTATUS value.
    pub fn gql_status(&self) -> &'static str {
        self.kind.gql_status()
    }

    /// The kind's canonical title.
    pub fn title(&self) -> &'static str {
        self.kind.title()
    }

    /// The kind's severity.
    pub fn severity(&self) -> NotificationSeverity {
        self.kind.severity()
    }

    /// The kind's category.
    pub fn category(&self) -> NotificationCategory {
        self.kind.category()
    }

    /// The effective remedy: the instance-specific one when the detector
    /// supplied it, else the kind's canonical remedy. Every vocabulary kind
    /// carries a remedy, so this is never absent.
    pub fn remedy(&self) -> &str {
        self.remedy.as_deref().unwrap_or_else(|| self.kind.remedy())
    }

    /// The raising operator's `PlanNode.id`, on operator-scoped kinds only.
    pub fn operator_id(&self) -> Option<usize> {
        self.operator_id
    }
}

/// The engine-native notification keys (ADR-0363 decision 9) — the
/// vocabulary [`notification_to_wire_json`] emits and every consumer
/// reads, single-sourced like [`super::plan_keys`].
pub mod notification_keys {
    /// The diagnostic code.
    pub const CODE: &str = "code";
    /// The GQLSTATUS value.
    pub const GQL_STATUS: &str = "gql_status";
    /// The severity spelling.
    pub const SEVERITY: &str = "severity";
    /// The category spelling.
    pub const CATEGORY: &str = "category";
    /// The canonical title.
    pub const TITLE: &str = "title";
    /// The instance diagnosis.
    pub const DESCRIPTION: &str = "description";
    /// The effective remedy (always present on the native form).
    pub const REMEDY: &str = "remedy";
    /// The raising operator's id (operator-scoped kinds only).
    pub const OPERATOR_ID: &str = "operator_id";
    /// The response envelope's always-present notification list.
    pub const NOTIFICATIONS: &str = "notifications";
}

/// The seven diagnostic fields of one notification's engine-native wire
/// object, keyed by the [`notification_keys`] vocabulary — the core
/// [`notification_to_wire_json`] layers the operator id onto, and the exact
/// object the agent-native plan document projects for a node's `warnings`
/// (the node already scopes the operator, so the join key is not repeated
/// there). One spelling of the field set, so a field added to the canonical
/// notification reaches every projection instead of drifting in a second
/// hand-rolled one.
pub(crate) fn notification_fields(notification: &Notification) -> Map<String, Value> {
    let mut obj = Map::new();
    obj.insert(
        notification_keys::CODE.into(),
        Value::String(notification.code().into()),
    );
    obj.insert(
        notification_keys::GQL_STATUS.into(),
        Value::String(notification.gql_status().into()),
    );
    obj.insert(
        notification_keys::SEVERITY.into(),
        Value::String(notification.severity().as_str().into()),
    );
    obj.insert(
        notification_keys::CATEGORY.into(),
        Value::String(notification.category().as_str().into()),
    );
    obj.insert(
        notification_keys::TITLE.into(),
        Value::String(notification.title().into()),
    );
    obj.insert(
        notification_keys::DESCRIPTION.into(),
        Value::String(notification.description().into()),
    );
    obj.insert(
        notification_keys::REMEDY.into(),
        Value::String(notification.remedy().into()),
    );
    obj
}

/// One notification's engine-native wire object (ADR-0363 decision 9):
/// `code`, `gql_status`, `severity`, `category`, `title`, `description`,
/// `remedy` and — on operator-scoped kinds — `operator_id`.
pub fn notification_to_wire_json(notification: &Notification) -> Value {
    let mut obj = notification_fields(notification);
    if let Some(operator_id) = notification.operator_id() {
        obj.insert(
            notification_keys::OPERATOR_ID.into(),
            Value::from(operator_id),
        );
    }
    Value::Object(obj)
}

/// A notification list in the engine-native form — the array the shared
/// success envelope always carries (empty on a plain run).
pub fn notifications_to_wire_json(notifications: &[Notification]) -> Value {
    Value::Array(
        notifications
            .iter()
            .map(notification_to_wire_json)
            .collect(),
    )
}

/// One notification's Neo4j-shaped entries (ADR-0363 decisions 11/12), in
/// Bolt's entry order: `code`, `title`, `description`, `severity`,
/// `category`. The effective remedy is folded into `description` as
/// ` (remedy: <remedy>)`; no `remedy` and no `position` entry is ever
/// emitted. This is the ordered form Bolt packs directly, without building
/// or re-reading a JSON object; [`notification_to_neo4j_json`] is the JSON
/// projection of the same entries.
pub fn notification_to_neo4j_entries(notification: &Notification) -> Vec<(&'static str, String)> {
    vec![
        (notification_keys::CODE, notification.code().to_string()),
        (notification_keys::TITLE, notification.title().to_string()),
        (
            notification_keys::DESCRIPTION,
            format!(
                "{} (remedy: {})",
                notification.description(),
                notification.remedy()
            ),
        ),
        (
            notification_keys::SEVERITY,
            notification.severity().as_str().to_string(),
        ),
        (
            notification_keys::CATEGORY,
            notification.category().as_str().to_string(),
        ),
    ]
}

/// One notification's Neo4j-shaped wire object (ADR-0363 decisions 11/12):
/// exactly `code`, `title`, `description`, `severity`, `category`, with the
/// remedy folded into `description` as ` (remedy: <remedy>)` and no `remedy`
/// or `position` key. Built from [`notification_to_neo4j_entries`].
///
/// `serde_json::Map` is a sorted map in this workspace (it does not enable
/// `preserve_order`), so the object's key order is sorted, not Bolt's.
/// Callers that emit ordered entries — Bolt — read
/// [`notification_to_neo4j_entries`] instead.
pub fn notification_to_neo4j_json(notification: &Notification) -> Value {
    let obj: Map<String, Value> = notification_to_neo4j_entries(notification)
        .into_iter()
        .map(|(key, value)| (key.to_owned(), Value::String(value)))
        .collect();
    Value::Object(obj)
}

#[cfg(test)]
#[path = "notification_wire/tests.rs"]
mod tests;